CombinedText
stringlengths
4
3.42M
#include <iostream> #include <fstream> #include <codecvt> //#include <cstddef> #include <locale> #include <clocale> #include <string> #include <iomanip> #include <ctime> #include "cp-neural.h" using std::wcout; using std::wstring; using std::cerr; using std::vector; class Text { private: bool isinit=false; bool readDataFile(string inputfile) { std::wifstream txtfile(inputfile, std::ios::binary); if (!txtfile.is_open()) { return false; } txtfile.imbue(std::locale("en_US.UTF-8")); wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)), std::istreambuf_iterator<wchar_t>()); txtfile.close(); text=ttext; filename=inputfile; return true; } public: wstring text; string filename; std::map<wchar_t,int> freq; std::map<wchar_t,int> w2v; std::map<int,wchar_t> v2w; Text(string filename) { if (readDataFile(filename)) { for (auto wc : text) { freq[wc]++; } int it=0; for (auto wc : freq) { w2v[wc.first]=it; v2w[it]=wc.first; ++it; } isinit=true; cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl; } } ~Text() { } bool isInit() { return isinit; } int vocsize() { if (!isinit) return 0; return (int)v2w.size(); } wstring sample(int len) { int p=std::rand()%(text.size()-len); return text.substr(p,len); } }; void currentDateTime(wstring& timestr) { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); timestr=std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(buf); } int main(int argc, char *argv[]) { #ifndef __APPLE__ std::setlocale(LC_ALL, ""); #else setlocale(LC_ALL, ""); std::wcout.imbue(std::locale("en_US.UTF-8")); #endif wcout << L"Rnn-Readär" << std::endl; bool allOk=true; if (argc!=2) { cerr << L"rnnreader <path-to-text-file>" << endl; exit(-1); } Text txt(argv[1]); if (!txt.isInit()) { cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl; exit(-1); } wcout << L"Text size: " << txt.text.size() << endl; wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl; /* for (auto f : txt.freq) { int c=(int)f.first; wstring wc(1,f.first); wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl; } */ Color::Modifier red(Color::FG_RED); Color::Modifier green(Color::FG_GREEN); Color::Modifier def(Color::FG_DEFAULT); int T=96; int N=(int)txt.text.size() / (T+1); cerr << N << " Max datasets" << endl; MatrixN Xr(N,T); MatrixN yr(N,T); wstring chunk,chunky; int n=0; for (int i=0; i<N; i++) { wstring smp = txt.sample(T+1); chunk=smp.substr(0,T); chunky=smp.substr(1,T); for (int t=0; t<T; t++) { Xr(i,t)=txt.w2v[chunk[t]]; yr(i,t)=txt.w2v[chunky[t]]; } ++n; } int maxN = 100000; if (n>maxN) n=maxN; int n1=n*0.9; int dn=(n-n1)/2; if (n1+2*dn > n) { cerr << "Math doesn't work out." << endl; } cerr << n1 << " datasets, " << dn << " test-sets, " << dn << " validation-sets" << endl; /* MatrixN X(n1,T); MatrixN y(n1,T); MatrixN Xv(dn,T); MatrixN yv(dn,T); MatrixN Xt(dn,T); MatrixN yt(dn,T); */ MatrixN X=Xr.block(0,0,n1,T); MatrixN y=yr.block(0,0,n1,T); MatrixN Xv=Xr.block(n1,0,dn,T); MatrixN yv=yr.block(n1,0,dn,T); MatrixN Xt=Xr.block(n1+dn,0,dn,T); MatrixN yt=yr.block(n1+dn,0,dn,T); unsigned int ctm=(unsigned int)std::time(0); std::srand(ctm); cpInitCompute("Rnnreader"); registerLayers(); LayerBlockOldStyle lb(R"({"name":"rnnreader","init":"orthonormal"})"_json); int VS=txt.vocsize(); int H=128; // 400; int BS=128; // 96; //float clip=5.0; //int D=64; // CpParams cp0; // cp0.setPar("inputShape",vector<int>{T}); // cp0.setPar("V",VS); // cp0.setPar("D",D); // cp0.setPar("clip",clip); // cp0.setPar("init",(string)"orthonormal"); // lb.addLayer("WordEmbedding","WE0",cp0,{"input"}); string rnntype="LSTM"; // or "RNN" cerr << "RNN-type: " << rnntype << endl; json j0; string oName{"OH0"}; j0["inputShape"]=vector<int>{T}; j0["V"]=VS; lb.addLayer("OneHot",oName,j0,{"input"}); string nName; json j1; j1["inputShape"]=vector<int>{VS,T}; j1["N"]=BS; j1["H"]=H; j1["forgetgateinitones"]=true; //j1["forgetbias"]=0.10; //j1["clip"]=clip; int layer_depth1=2; // 6; j1["H"]=H; for (auto l=0; l<layer_depth1; l++) { if (l>0) j1["inputShape"]=vector<int>{H,T}; nName="lstm"+std::to_string(l); lb.addLayer(rnntype,nName,j1,{oName}); oName=nName; } json j10; j10["inputShape"]=vector<int>{H,T}; j10["M"]=VS; lb.addLayer("TemporalAffine","af1",j10,{oName}); json j11; j11["inputShape"]=vector<int>{VS,T}; cerr << "Adding softmax layer, inputShape: " << j11["inputShape"] << " VS: " << VS << " T: " << T << endl; lb.addLayer("TemporalSoftmax","sm1",j11,{"af1"}); if (!lb.checkTopology(true)) { allOk=false; cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl; } else { cerr << green << "Topology-check for LayerBlock: ok." << def << endl; } //json jc; //lb.getLayerConfiguration(jc); //cerr << jc.dump(4) << endl; // preseverstates no longer necessary for training! json jo(R"({"verbose":true,"shuffle":false,"preservestates":false,"notests":false,"nofragmentbatches":true})"_json); jo["lossfactor"]=1.0/(floatN)T; // Allows to normalize the loss with T. //j_opt["inputShape"]=vector<int>{H,T}; floatN dep=5.0; // 70.0; floatN sep=0.0; jo["epochs"]=(floatN)dep; jo["batch_size"]=BS; jo["lr_decay"] = 1.0; // XXX: regularization crashes the training. // jo["regularization"]=1.0e-5; // jo["regularization_decay"]=0.95; json j_opt(R"({"learning_rate": 1e-2})"_json); Optimizer *pOpt=optimizerFactory("Adam",j_opt); t_cppl OptimizerState{}; json j_loss(R"({"name":"temporalsoftmax"})"_json); j_loss["inputShape"]=vector<int>{VS,T}; Loss *pLoss=lossFactory("TemporalCrossEntropy",j_loss); for (int i=0; i<1000; i++) { jo["startepoch"]=(floatN)sep; t_cppl states; t_cppl statesv; states["y"] = new MatrixN(y); statesv["y"] = new MatrixN(yv); lb.train(X, &states, Xv, &statesv, pOpt, &OptimizerState, pLoss, jo); cppl_delete(&states); cppl_delete(&statesv); sep+=dep; int pos=rand() % 1000 + 5000; wstring instr=txt.text.substr(pos,T); MatrixN xg(1,T); for (int i=0; i<T; i++) { xg(0,i)=txt.w2v[instr[i]]; } wstring sout{}; Layer* plstm0=lb.layerMap["lstm0"]; t_cppl statesg{}; plstm0->genZeroStates(&statesg, 1); int g,t,v; for (g=0; g<300; g++) { t_cppl cache{}; MatrixN probst=lb.forward(xg,&cache, &statesg); /* Wrong idea: // Forward generates the 'wrong' permutation of output. QUick-hack is abusing the 'cache' to get the permutation. if (cache.find("sm1-probst")==cache.end()) { cerr << "probst didn't make it, FATAL" << endl; exit(1); } MatrixN probst=*(cache["sm1-probst"]); // XXX check if temporal softmax uses redundant morpher! */ MatrixN probsd=MatrixN(T,VS); for (t=0; t<T; t++) { for (v=0; v<VS; v++) { probsd(t,v)=probst(0,t*VS+v); } } int li = -1; for (t=0; t<T; t++) { vector<floatN> probs(VS); vector<floatN> index(VS); for (v=0; v<VS; v++) { probs[v]=probsd(t,v); index[v]=v; } li=(int)index[randomChoice(index, probs)]; } cppl_delete(&cache); for (int t=0; t<T-1; t++) { xg(0,t)=xg(0,t+1); } xg(0,T-1)=li; sout += txt.v2w[li]; } wcout << "output: " << sout << endl; wstring timestr; currentDateTime(timestr); std::wofstream fl("rnnreader.txt", std::ios_base::app); fl << "---- " << timestr << ", ep:" << sep << " ---" << endl; fl << sout << endl; fl.close(); cppl_delete(&statesg); } delete pOpt; cppl_delete(&OptimizerState); delete pLoss; } cleaning #include <iostream> #include <fstream> #include <codecvt> //#include <cstddef> #include <locale> #include <clocale> #include <string> #include <iomanip> #include <ctime> #include "cp-neural.h" using std::wcout; using std::wstring; using std::cerr; using std::vector; class Text { private: bool isinit=false; bool readDataFile(string inputfile) { std::wifstream txtfile(inputfile, std::ios::binary); if (!txtfile.is_open()) { return false; } txtfile.imbue(std::locale("en_US.UTF-8")); wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)), std::istreambuf_iterator<wchar_t>()); txtfile.close(); text=ttext; filename=inputfile; return true; } public: wstring text; string filename; std::map<wchar_t,int> freq; std::map<wchar_t,int> w2v; std::map<int,wchar_t> v2w; Text(string filename) { if (readDataFile(filename)) { for (auto wc : text) { freq[wc]++; } int it=0; for (auto wc : freq) { w2v[wc.first]=it; v2w[it]=wc.first; ++it; } isinit=true; cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl; } } ~Text() { } bool isInit() { return isinit; } int vocsize() { if (!isinit) return 0; return (int)v2w.size(); } wstring sample(int len) { int p=std::rand()%(text.size()-len); return text.substr(p,len); } }; void currentDateTime(wstring& timestr) { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); timestr=std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(buf); } int main(int argc, char *argv[]) { #ifndef __APPLE__ std::setlocale(LC_ALL, ""); #else setlocale(LC_ALL, ""); std::wcout.imbue(std::locale("en_US.UTF-8")); #endif wcout << L"Rnn-Readär" << std::endl; bool allOk=true; if (argc!=2) { cerr << L"rnnreader <path-to-text-file>" << endl; exit(-1); } Text txt(argv[1]); if (!txt.isInit()) { cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl; exit(-1); } wcout << L"Text size: " << txt.text.size() << endl; wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl; /* for (auto f : txt.freq) { int c=(int)f.first; wstring wc(1,f.first); wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl; } */ Color::Modifier red(Color::FG_RED); Color::Modifier green(Color::FG_GREEN); Color::Modifier def(Color::FG_DEFAULT); int timeSteps=96; int N=(int)txt.text.size() / (timeSteps+1); cerr << N << " Max datasets" << endl; MatrixN Xr(N,timeSteps); MatrixN yr(N,timeSteps); wstring chunk,chunky; int n=0; for (int i=0; i<N; i++) { wstring smp = txt.sample(timeSteps+1); chunk=smp.substr(0,timeSteps); chunky=smp.substr(1,timeSteps); for (int t=0; t<timeSteps; t++) { Xr(i,t)=txt.w2v[chunk[t]]; yr(i,t)=txt.w2v[chunky[t]]; } ++n; } int maxN = 100000; if (n>maxN) n=maxN; int n1=n*0.9; int dn=(n-n1)/2; if (n1+2*dn > n) { cerr << "Math doesn't work out." << endl; } cerr << n1 << " datasets, " << dn << " test-sets, " << dn << " validation-sets" << endl; MatrixN X=Xr.block(0,0,n1,timeSteps); MatrixN y=yr.block(0,0,n1,timeSteps); MatrixN xVal=Xr.block(n1,0,dn,timeSteps); MatrixN yVal=yr.block(n1,0,dn,timeSteps); MatrixN xTest=Xr.block(n1+dn,0,dn,timeSteps); MatrixN yTest=yr.block(n1+dn,0,dn,timeSteps); unsigned int ctm=(unsigned int)std::time(0); std::srand(ctm); cpInitCompute("Rnnreader"); registerLayers(); LayerBlockOldStyle lb(R"({"name":"rnnreader","init":"orthonormal"})"_json); int vocabularySize=txt.vocsize(); int H=128; // 400; int batchSize=128; // 96; //float clip=5.0; string rnntype="LSTM"; // or "RNN" cerr << "RNN-type: " << rnntype << endl; json j0; string oName{"OH0"}; j0["inputShape"]=vector<int>{timeSteps}; j0["V"]=vocabularySize; lb.addLayer("OneHot",oName,j0,{"input"}); string nName; json j1; j1["inputShape"]=vector<int>{vocabularySize,timeSteps}; j1["N"]=batchSize; j1["H"]=H; j1["forgetgateinitones"]=true; //j1["forgetbias"]=0.10; //j1["clip"]=clip; int layerDepth=8; // 6; j1["H"]=H; for (auto l=0; l<layerDepth; l++) { if (l>0) j1["inputShape"]=vector<int>{H,timeSteps}; nName="lstm"+std::to_string(l); lb.addLayer(rnntype,nName,j1,{oName}); oName=nName; } json j10; j10["inputShape"]=vector<int>{H,timeSteps}; j10["M"]=vocabularySize; lb.addLayer("TemporalAffine","af1",j10,{oName}); json j11; j11["inputShape"]=vector<int>{vocabularySize,timeSteps}; // currently inputShape of TempSoftmax MUST match inputShape of TemporalLoss lb.addLayer("TemporalSoftmax","sm1",j11,{"af1"}); if (!lb.checkTopology(true)) { allOk=false; cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl; exit(-1); } else { cerr << green << "Topology-check for LayerBlock: ok." << def << endl; } floatN episodes=5.0; // 70.0; floatN currentEpoch=0.0; json train_params(R"({"verbose":true,"shuffle":false,"notests":false,"nofragmentbatches":true})"_json); train_params["lossfactor"]=1.0/(floatN)timeSteps; // Allows to normalize the loss with timeSteps. train_params["epochs"]=(floatN)episodes; train_params["batch_size"]=batchSize; train_params["lr_decay"] = 0.945; // every 40 epochs, lr = lr/10 (0.945^40 = 0.104) json j_opt(R"({"learning_rate": 1e-2})"_json); Optimizer *pOpt=optimizerFactory("Adam",j_opt); t_cppl OptimizerState{}; json j_loss(R"({"name":"temporalsoftmax"})"_json); j_loss["inputShape"]=vector<int>{vocabularySize,timeSteps}; Loss *pLoss=lossFactory("TemporalCrossEntropy",j_loss); for (int i=0; i<1000; i++) { train_params["startepoch"]=(floatN)currentEpoch; t_cppl states; t_cppl statesVal; states["y"] = new MatrixN(y); statesVal["y"] = new MatrixN(yVal); lb.train(X, &states, xVal, &statesVal, pOpt, &OptimizerState, pLoss, train_params); cppl_delete(&states); cppl_delete(&statesVal); currentEpoch+=episodes; int pos=rand() % 1000 + 5000; wstring instr=txt.text.substr(pos,timeSteps); MatrixN xg(1,timeSteps); for (int i=0; i<timeSteps; i++) { xg(0,i)=txt.w2v[instr[i]]; } wstring sout{}; Layer* plstm0=lb.layerMap["lstm0"]; t_cppl statesg{}; plstm0->genZeroStates(&statesg, 1); int g,t,v; for (g=0; g<300; g++) { t_cppl cache{}; MatrixN probst=lb.forward(xg,&cache, &statesg); MatrixN probsd=MatrixN(timeSteps,vocabularySize); for (t=0; t<timeSteps; t++) { for (v=0; v<vocabularySize; v++) { probsd(t,v)=probst(0,t*vocabularySize+v); } } int li = -1; for (t=0; t<timeSteps; t++) { vector<floatN> probs(vocabularySize); vector<floatN> index(vocabularySize); for (v=0; v<vocabularySize; v++) { probs[v]=probsd(t,v); index[v]=v; } li=(int)index[randomChoice(index, probs)]; } cppl_delete(&cache); for (int t=0; t<timeSteps-1; t++) { xg(0,t)=xg(0,t+1); } xg(0,timeSteps-1)=li; sout += txt.v2w[li]; } wcout << "output: " << sout << endl; wstring timestr; currentDateTime(timestr); std::wofstream fl("rnnreader.txt", std::ios_base::app); fl << "---- " << timestr << ", ep:" << currentEpoch << " ---" << endl; fl << sout << endl; fl.close(); cppl_delete(&statesg); } delete pOpt; cppl_delete(&OptimizerState); delete pLoss; }
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2019 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "NFChatModule.h" #include "NFComm/NFMessageDefine/NFProtocolDefine.hpp" #include "NFComm/NFPluginModule/NFIEventModule.h" bool NFChatModule::Init() { m_pNetModule = pPluginManager->FindModule<NFINetModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pEventModule = pPluginManager->FindModule<NFIEventModule>(); m_pSceneModule = pPluginManager->FindModule<NFISceneModule>(); m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>(); m_pGameServerToWorldModule = pPluginManager->FindModule<NFIGameServerToWorldModule>(); return true; } bool NFChatModule::AfterInit() { m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_CHAT, this, &NFChatModule::OnClienChatProcess); return true; } bool NFChatModule::Shut() { return true; } bool NFChatModule::Execute() { return true; } void NFChatModule::OnClienChatProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { CLIENT_MSG_PROCESS( nMsgID, msg, nLen, NFMsg::ReqAckPlayerChat); switch (xMsg.chat_type()) { case NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_WORLD: { m_pNetModule->SendMsgPBToAllClient(NFMsg::EGMI_ACK_CHAT, xMsg); } break; case NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_CLAN: { NFGUID xTargetID = NFINetModule::PBToNF(xMsg.target_id()); NFGUID xClanID = m_pKernelModule->GetPropertyObject(nPlayerID, NFrame::Player::Clan_ID()); if (!xClanID.IsNull() && xClanID == xTargetID) { //send to world server m_pGameServerToWorldModule->TransmitToWorld(xClanID.nData64, nMsgID, xMsg); } } break; case NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_PRIVATE: case NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_TEAM: { if (xMsg.has_target_id()) { NFGUID xTargetID = NFINetModule::PBToNF(xMsg.target_id()); if (!xTargetID.IsNull()) { if (m_pKernelModule->GetObject(xTargetID)) { } else { //send to world server m_pGameServerToWorldModule->TransmitToWorld(xTargetID.nData64, nMsgID, xMsg); } } } } break; default: break;; } } Chat system /* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2019 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "NFChatModule.h" #include "NFComm/NFMessageDefine/NFProtocolDefine.hpp" #include "NFComm/NFPluginModule/NFIEventModule.h" bool NFChatModule::Init() { m_pNetModule = pPluginManager->FindModule<NFINetModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pEventModule = pPluginManager->FindModule<NFIEventModule>(); m_pSceneModule = pPluginManager->FindModule<NFISceneModule>(); m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>(); m_pGameServerToWorldModule = pPluginManager->FindModule<NFIGameServerToWorldModule>(); return true; } bool NFChatModule::AfterInit() { m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_CHAT, this, &NFChatModule::OnClienChatProcess); return true; } bool NFChatModule::Shut() { return true; } bool NFChatModule::Execute() { return true; } void NFChatModule::OnClienChatProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { CLIENT_MSG_PROCESS( nMsgID, msg, nLen, NFMsg::ReqAckPlayerChat); switch (xMsg.chat_type()) { case NFMsg::ReqAckPlayerChat::EGCT_WORLD: { m_pNetModule->SendMsgPBToAllClient(NFMsg::EGMI_ACK_CHAT, xMsg); } break; case NFMsg::ReqAckPlayerChat::EGCT_CLAN: { NFGUID xTargetID = NFINetModule::PBToNF(xMsg.target_id()); NFGUID xClanID = m_pKernelModule->GetPropertyObject(nPlayerID, NFrame::Player::Clan_ID()); if (!xClanID.IsNull() && xClanID == xTargetID) { //send to world server m_pGameServerToWorldModule->TransmitToWorld(xClanID.nData64, nMsgID, xMsg); } } break; case NFMsg::ReqAckPlayerChat::EGCT_PRIVATE: { NFGUID xTargetID = NFINetModule::PBToNF(xMsg.target_id()); if (m_pKernelModule->ExistObject(xTargetID)) { m_pGameServerNet_ServerModule->SendMsgPBToGate(nMsgID, xMsg, xTargetID); } else { //send to world server m_pGameServerToWorldModule->TransmitToWorld(xTargetID.nData64, nMsgID, xMsg); } } break; case NFMsg::ReqAckPlayerChat::EGCT_TEAM: { const int sceneID = m_pKernelModule->GetPropertyInt(nPlayerID, NFrame::Player::SceneID()); const int groupID = m_pKernelModule->GetPropertyInt(nPlayerID, NFrame::Player::GroupID()); m_pGameServerNet_ServerModule->SendGroupMsgPBToGate(nMsgID, xMsg, sceneID, groupID); } break; default: break;; } }
/* OpenSceneGraph example, osgstereoimage. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <osgViewer/Viewer> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgUtil/Optimizer> #include <osg/Geode> #include <osg/Notify> #include <osg/MatrixTransform> #include <osg/Switch> #include <osg/TexMat> #include <osg/Texture2D> #include <iostream> typedef std::vector<std::string> FileList; class SlideEventHandler : public osgGA::GUIEventHandler { public: SlideEventHandler(); META_Object(osgStereImageApp,SlideEventHandler); void set(osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float timePerSlide, bool autoSteppingActive); virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&); virtual void getUsage(osg::ApplicationUsage& usage) const; virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); void nextSlide(); void previousSlide(); void scaleImage(float s); void offsetImage(float ds,float dt); void rotateImage(float rx,float ry); void initTexMatrices(); protected: ~SlideEventHandler() {} SlideEventHandler(const SlideEventHandler&,const osg::CopyOp&) {} osg::ref_ptr<osg::Switch> _switch; osg::ref_ptr<osg::TexMat> _texmatLeft; osg::ref_ptr<osg::TexMat> _texmatRight; bool _firstTraversal; unsigned int _activeSlide; double _previousTime; double _timePerSlide; bool _autoSteppingActive; float _initSeperationX; float _currentSeperationX; float _initSeperationY; float _currentSeperationY; }; SlideEventHandler::SlideEventHandler(): _switch(0), _texmatLeft(0), _texmatRight(0), _firstTraversal(true), _activeSlide(0), _previousTime(-1.0f), _timePerSlide(5.0), _autoSteppingActive(false) { } void SlideEventHandler::set(osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float timePerSlide, bool autoSteppingActive) { _switch = sw; _switch->setUpdateCallback(this); _texmatLeft = texmatLeft; _texmatRight = texmatRight; _timePerSlide = timePerSlide; _autoSteppingActive = autoSteppingActive; _initSeperationX = offsetX; _currentSeperationX = _initSeperationX; _initSeperationY = offsetY; _currentSeperationY = _initSeperationY; initTexMatrices(); } bool SlideEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&) { switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYDOWN): { if (ea.getKey()=='a') { _autoSteppingActive = !_autoSteppingActive; _previousTime = ea.getTime(); return true; } else if (ea.getKey()=='n') { nextSlide(); return true; } else if (ea.getKey()=='p') { previousSlide(); return true; } else if (ea.getKey()=='w') { scaleImage(0.99f); return true; } else if (ea.getKey()=='s') { scaleImage(1.01f); return true; } else if (ea.getKey()=='j') { offsetImage(-0.001f,0.0f); return true; } else if (ea.getKey()=='k') { offsetImage(0.001f,0.0f); return true; } else if (ea.getKey()=='i') { offsetImage(0.0f,-0.001f); return true; } else if (ea.getKey()=='m') { offsetImage(0.0f,0.001f); return true; } else if (ea.getKey()==' ') { initTexMatrices(); return true; } return false; } case(osgGA::GUIEventAdapter::DRAG): case(osgGA::GUIEventAdapter::MOVE): { static float px = ea.getXnormalized(); static float py = ea.getYnormalized(); float dx = ea.getXnormalized()-px; float dy = ea.getYnormalized()-py; px = ea.getXnormalized(); py = ea.getYnormalized(); rotateImage(dx,dy); return true; } default: return false; } } void SlideEventHandler::getUsage(osg::ApplicationUsage& usage) const { usage.addKeyboardMouseBinding("Space","Reset the image position to center"); usage.addKeyboardMouseBinding("a","Toggle on/off the automatic advancement for image to image"); usage.addKeyboardMouseBinding("n","Advance to next image"); usage.addKeyboardMouseBinding("p","Move to previous image"); usage.addKeyboardMouseBinding("q","Zoom into the image"); usage.addKeyboardMouseBinding("a","Zoom out of the image"); usage.addKeyboardMouseBinding("j","Reduce horizontal offset"); usage.addKeyboardMouseBinding("k","Increase horizontal offset"); usage.addKeyboardMouseBinding("m","Reduce vertical offset"); usage.addKeyboardMouseBinding("i","Increase vertical offset"); } void SlideEventHandler::operator()(osg::Node* node, osg::NodeVisitor* nv) { if (_autoSteppingActive && nv->getFrameStamp()) { double time = nv->getFrameStamp()->getSimulationTime(); if (_firstTraversal) { _firstTraversal = false; _previousTime = time; } else if (time-_previousTime>_timePerSlide) { _previousTime = time; nextSlide(); } } traverse(node,nv); } void SlideEventHandler::nextSlide() { if (_switch->getNumChildren()==0) return; ++_activeSlide; if (_activeSlide>=_switch->getNumChildren()) _activeSlide = 0; _switch->setSingleChildOn(_activeSlide); } void SlideEventHandler::previousSlide() { if (_switch->getNumChildren()==0) return; if (_activeSlide==0) _activeSlide = _switch->getNumChildren()-1; else --_activeSlide; _switch->setSingleChildOn(_activeSlide); } void SlideEventHandler::scaleImage(float s) { _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f)); _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f)); } void SlideEventHandler::offsetImage(float ds,float dt) { _currentSeperationX+=ds; _currentSeperationY+=dt; osg::notify(osg::NOTICE)<<"image offset x = "<<_currentSeperationX<<" y ="<<_currentSeperationY<<std::endl; _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(ds,dt,0.0f)); _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-ds,-dt,0.0f)); } void SlideEventHandler::rotateImage(float rx,float ry) { const float scale = 0.5f; _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f)); _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f)); } void SlideEventHandler::initTexMatrices() { _texmatLeft->setMatrix(osg::Matrix::translate(_initSeperationX,_initSeperationY,0.0f)); _texmatRight->setMatrix(osg::Matrix::translate(-_initSeperationX,-_initSeperationY,0.0f)); } osg::Geode* createSectorForImage(osg::Image* image, osg::TexMat* texmat, float s,float t, float radius, float height, float length) { int numSegments = 20; float Theta = length/radius; float dTheta = Theta/(float)(numSegments-1); float ThetaZero = height*s/(t*radius); // set up the texture. osg::Texture2D* texture = new osg::Texture2D; texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR); texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR); texture->setImage(image); // set up the drawstate. osg::StateSet* dstate = new osg::StateSet; dstate->setMode(GL_CULL_FACE,osg::StateAttribute::OFF); dstate->setMode(GL_LIGHTING,osg::StateAttribute::OFF); dstate->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON); dstate->setTextureAttribute(0, texmat); // set up the geoset. osg::Geometry* geom = new osg::Geometry; geom->setStateSet(dstate); osg::Vec3Array* coords = new osg::Vec3Array(); osg::Vec2Array* tcoords = new osg::Vec2Array(); int i; float angle = -Theta/2.0f; for(i=0; i<numSegments; ++i, angle+=dTheta) { coords->push_back(osg::Vec3(sinf(angle)*radius,cosf(angle)*radius,height*0.5f)); // top coords->push_back(osg::Vec3(sinf(angle)*radius,cosf(angle)*radius,-height*0.5f)); // bottom. tcoords->push_back(osg::Vec2(angle/ThetaZero+0.5f,1.0f)); // top tcoords->push_back(osg::Vec2(angle/ThetaZero+0.5f,0.0f)); // bottom. } osg::Vec4Array* colors = new osg::Vec4Array(); colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); osg::DrawArrays* elements = new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,coords->size()); geom->setVertexArray(coords); geom->setTexCoordArray(0,tcoords); geom->setColorArray(colors); geom->setColorBinding(osg::Geometry::BIND_OVERALL); geom->addPrimitiveSet(elements); // set up the geode. osg::Geode* geode = new osg::Geode; geode->addDrawable(geom); return geode; } // create a switch containing a set of child each containing a // stereo image pair. osg::Switch* createScene(const FileList& fileList, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float radius, float height, float length) { osg::Switch* sw = new osg::Switch; // load the images. for(unsigned int i=0;i+1<fileList.size();i+=2) { osg::ref_ptr<osg::Image> imageLeft = osgDB::readImageFile(fileList[i]); osg::ref_ptr<osg::Image> imageRight = osgDB::readImageFile(fileList[i+1]); if (imageLeft.valid() && imageRight.valid()) { float average_s = (imageLeft->s()+imageRight->s())*0.5f; float average_t = (imageLeft->t()+imageRight->t())*0.5f; osg::Geode* geodeLeft = createSectorForImage(imageLeft.get(),texmatLeft,average_s,average_t, radius, height, length); geodeLeft->setNodeMask(0x01); osg::Geode* geodeRight = createSectorForImage(imageRight.get(),texmatRight,average_s,average_t, radius, height, length); geodeRight->setNodeMask(0x02); osg::ref_ptr<osg::Group> imageGroup = new osg::Group; imageGroup->addChild(geodeLeft); imageGroup->addChild(geodeRight); sw->addChild(imageGroup.get()); } else { std::cout << "Warning: Unable to load both image files, '"<<fileList[i]<<"' & '"<<fileList[i+1]<<"', required for stereo imaging."<<std::endl; } } if (sw->getNumChildren()>0) { // select first child. sw->setSingleChildOn(0); } return sw; } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use node masks to create stereo images."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye"); arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time delay in sceonds between the display of successive image pairs when in auto advance mode."); arguments.getApplicationUsage()->addCommandLineOption("-a","Enter auto advance of image pairs on start up."); arguments.getApplicationUsage()->addCommandLineOption("-x <float>","Horizontal offset of left and right images."); arguments.getApplicationUsage()->addCommandLineOption("-y <float>","Vertical offset of left and right images."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); arguments.getApplicationUsage()->addCommandLineOption("--SingleThreaded","Select SingleThreaded threading model for viewer."); arguments.getApplicationUsage()->addCommandLineOption("--CullDrawThreadPerContext","Select CullDrawThreadPerContext threading model for viewer."); arguments.getApplicationUsage()->addCommandLineOption("--DrawThreadPerContext","Select DrawThreadPerContext threading model for viewer."); arguments.getApplicationUsage()->addCommandLineOption("--CullThreadPerCameraDrawThreadPerContext","Select CullThreadPerCameraDrawThreadPerContext threading model for viewer."); // construct the viewer. osgViewer::Viewer viewer; // register the handler to add keyboard and mosue handling. SlideEventHandler* seh = new SlideEventHandler(); viewer.addEventHandler(seh); // read any time delay argument. float timeDelayBetweenSlides = 5.0f; while (arguments.read("-d",timeDelayBetweenSlides)) {} bool autoSteppingActive = false; while (arguments.read("-a")) autoSteppingActive = true; float offsetX=0.0f; while (arguments.read("-x",offsetX)) {} float offsetY=0.0f; while (arguments.read("-y",offsetY)) {} // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } osgViewer::Viewer::ThreadingModel threading = osgViewer::Viewer::SingleThreaded; while (arguments.read("--SingleThreaded")) threading = osgViewer::Viewer::SingleThreaded; while (arguments.read("--CullDrawThreadPerContext")) threading = osgViewer::Viewer::CullDrawThreadPerContext; while (arguments.read("--DrawThreadPerContext")) threading = osgViewer::Viewer::DrawThreadPerContext; while (arguments.read("--CullThreadPerCameraDrawThreadPerContext")) threading = osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext; viewer.setThreadingModel(threading); // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // extract the filenames from the arguments list. FileList fileList; for(int pos=1;pos<arguments.argc();++pos) { if (arguments.isString(pos)) fileList.push_back(arguments[pos]); } if (fileList.empty()) { fileList.push_back("Images/dog_left_eye.jpg"); fileList.push_back("Images/dog_right_eye.jpg"); } else if (fileList.size()<2) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } // now the windows have been realized we switch off the cursor to prevent it // distracting the people seeing the stereo images. double fovy, aspectRatio, zNear, zFar; viewer.getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar); float radius = 1.0f; float height = 2*radius*tan(osg::DegreesToRadians(fovy)*0.5f); float length = osg::PI*radius; // half a cylinder. // use a texure matrix to control the placement of the image. osg::TexMat* texmatLeft = new osg::TexMat; osg::TexMat* texmatRight = new osg::TexMat; // creat the scene from the file list. osg::ref_ptr<osg::Switch> rootNode = createScene(fileList,texmatLeft,texmatRight,radius,height,length); //osgDB::writeNodeFile(*rootNode,"test.osg"); viewer.getCamera()->setCullMask(0xffffffff); viewer.getCamera()->setCullMaskLeft(0x00000001); viewer.getCamera()->setCullMaskRight(0x00000002); // set up the use of stereo by default. osg::DisplaySettings::instance()->setStereo(true); // set the scene to render viewer.setSceneData(rootNode.get()); // create the windows and run the threads. viewer.realize(); // switch off the cursor osgViewer::Viewer::Windows windows; viewer.getWindows(windows); for(osgViewer::Viewer::Windows::iterator itr = windows.begin(); itr != windows.end(); ++itr) { (*itr)->useCursor(false); } viewer.setFusionDistance(osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE,radius); // set up the SlideEventHandler. seh->set(rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,timeDelayBetweenSlides,autoSteppingActive); osg::Matrix homePosition; homePosition.makeLookAt(osg::Vec3(0.0f,0.0f,0.0f),osg::Vec3(0.0f,1.0f,0.0f),osg::Vec3(0.0f,0.0f,1.0f)); while( !viewer.done() ) { viewer.getCamera()->setViewMatrix(homePosition); // fire off the cull and draw traversals of the scene. viewer.frame(); } return 0; } From Luc Frauciel, "I've done 2 main modifications : 1) added texture->setResizeNonPowerOfTwoHint(false); when loading an image. It speeds up by 10 the loading of large images. 2) added a --disk option : only a filelist is read, images are only loaded when needed. It allows to handle very large set of very large images that would not fit in memory. Nothing change when the option is not set." /* OpenSceneGraph example, osgstereoimage. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <osgViewer/Viewer> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgUtil/Optimizer> #include <osg/Geode> #include <osg/Notify> #include <osg/MatrixTransform> #include <osg/Switch> #include <osg/TexMat> #include <osg/Texture2D> #include <iostream> typedef std::vector<std::string> FileList; osg::Geode* createSectorForImage(osg::Image* image, osg::TexMat* texmat, float s,float t, float radius, float height, float length) { int numSegments = 20; float Theta = length/radius; float dTheta = Theta/(float)(numSegments-1); float ThetaZero = height*s/(t*radius); // set up the texture. osg::Texture2D* texture = new osg::Texture2D; texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR); texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR); texture->setResizeNonPowerOfTwoHint(false); texture->setImage(image); // set up the drawstate. osg::StateSet* dstate = new osg::StateSet; dstate->setMode(GL_CULL_FACE,osg::StateAttribute::OFF); dstate->setMode(GL_LIGHTING,osg::StateAttribute::OFF); dstate->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON); dstate->setTextureAttribute(0, texmat); // set up the geoset. osg::Geometry* geom = new osg::Geometry; geom->setStateSet(dstate); osg::Vec3Array* coords = new osg::Vec3Array(); osg::Vec2Array* tcoords = new osg::Vec2Array(); int i; float angle = -Theta/2.0f; for(i=0; i<numSegments; ++i, angle+=dTheta) { coords->push_back(osg::Vec3(sinf(angle)*radius,cosf(angle)*radius,height*0.5f)); // top coords->push_back(osg::Vec3(sinf(angle)*radius,cosf(angle)*radius,-height*0.5f)); // bottom. tcoords->push_back(osg::Vec2(angle/ThetaZero+0.5f,1.0f)); // top tcoords->push_back(osg::Vec2(angle/ThetaZero+0.5f,0.0f)); // bottom. } osg::Vec4Array* colors = new osg::Vec4Array(); colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); osg::DrawArrays* elements = new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,coords->size()); geom->setVertexArray(coords); geom->setTexCoordArray(0,tcoords); geom->setColorArray(colors); geom->setColorBinding(osg::Geometry::BIND_OVERALL); geom->addPrimitiveSet(elements); // set up the geode. osg::Geode* geode = new osg::Geode; geode->addDrawable(geom); return geode; } osg::Group * loadImages(std::string image1, std::string image2, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float radius, float height, float length) { osg::ref_ptr<osg::Image> imageLeft = osgDB::readImageFile(image1); osg::ref_ptr<osg::Image> imageRight = osgDB::readImageFile(image2); if (imageLeft.valid() && imageRight.valid()) { float average_s = (imageLeft->s()+imageRight->s())*0.5f; float average_t = (imageLeft->t()+imageRight->t())*0.5f; osg::Geode* geodeLeft = createSectorForImage(imageLeft.get(),texmatLeft,average_s,average_t, radius, height, length); geodeLeft->setNodeMask(0x01); osg::Geode* geodeRight = createSectorForImage(imageRight.get(),texmatRight,average_s,average_t, radius, height, length); geodeRight->setNodeMask(0x02); osg::Group * imageGroup = new osg::Group; imageGroup->addChild(geodeLeft); imageGroup->addChild(geodeRight); return imageGroup; } else { std::cout << "Warning: Unable to load both image files, '"<<image1<<"' & '"<<image2<<"', required for stereo imaging."<<std::endl; return 0; } } // create a switch containing a set of child each containing a // stereo image pair. osg::Switch* createScene(FileList fileList, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float radius, float height, float length) { osg::Switch* sw = new osg::Switch; // load the images. for(unsigned int i=0;i+1<fileList.size();i+=2) { osg::Group * imageGroup = loadImages(fileList[i],fileList[i+1],texmatLeft,texmatRight, radius, height, length); if (imageGroup) sw->addChild(imageGroup); } if (sw->getNumChildren()>0) { // select first child. sw->setSingleChildOn(0); } return sw; } class SlideEventHandler : public osgGA::GUIEventHandler { public: SlideEventHandler(); META_Object(osgStereImageApp,SlideEventHandler); void set(osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float timePerSlide, bool autoSteppingActive); void set(FileList fileList, osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float radius, float height, float length, float timePerSlide, bool autoSteppingActive); virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&); virtual void getUsage(osg::ApplicationUsage& usage) const; virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); void nextSlide(); void previousSlide(); void scaleImage(float s); void offsetImage(float ds,float dt); void rotateImage(float rx,float ry); void initTexMatrices(); protected: ~SlideEventHandler() {} SlideEventHandler(const SlideEventHandler&,const osg::CopyOp&) {} osg::ref_ptr<osg::Switch> _switch; osg::ref_ptr<osg::TexMat> _texmatLeft; osg::ref_ptr<osg::TexMat> _texmatRight; float _radius; float _height; float _length; bool _firstTraversal; unsigned int _activeSlide; double _previousTime; double _timePerSlide; bool _autoSteppingActive; float _initSeperationX; float _currentSeperationX; float _initSeperationY; float _currentSeperationY; FileList _fileList; }; SlideEventHandler::SlideEventHandler(): _switch(0), _texmatLeft(0), _texmatRight(0), _firstTraversal(true), _activeSlide(0), _previousTime(-1.0f), _timePerSlide(5.0), _autoSteppingActive(false) { } void SlideEventHandler::set(osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float timePerSlide, bool autoSteppingActive) { _switch = sw; _switch->setUpdateCallback(this); _texmatLeft = texmatLeft; _texmatRight = texmatRight; _timePerSlide = timePerSlide; _autoSteppingActive = autoSteppingActive; _initSeperationX = offsetX; _currentSeperationX = _initSeperationX; _initSeperationY = offsetY; _currentSeperationY = _initSeperationY; initTexMatrices(); } void SlideEventHandler::set(FileList fileList, osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float radius, float height, float length, float timePerSlide, bool autoSteppingActive) { _switch = sw; _switch->setUpdateCallback(this); _fileList=FileList(fileList); osg::ref_ptr<osg::Group> imageGroup = loadImages(fileList[0],fileList[1],texmatLeft,texmatRight, radius, height, length); if (imageGroup.get())_switch->addChild(imageGroup.get()); _texmatLeft = texmatLeft; _texmatRight = texmatRight; _radius=radius; _height=height; _length=length; _timePerSlide = timePerSlide; _autoSteppingActive = autoSteppingActive; _initSeperationX = offsetX; _currentSeperationX = _initSeperationX; _initSeperationY = offsetY; _currentSeperationY = _initSeperationY; initTexMatrices(); } bool SlideEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&) { switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYDOWN): { if (ea.getKey()=='a') { _autoSteppingActive = !_autoSteppingActive; _previousTime = ea.getTime(); return true; } else if (ea.getKey()=='n') { nextSlide(); return true; } else if (ea.getKey()=='p') { previousSlide(); return true; } else if (ea.getKey()=='w') { scaleImage(0.99f); return true; } else if (ea.getKey()=='s') { scaleImage(1.01f); return true; } else if (ea.getKey()=='j') { offsetImage(-0.001f,0.0f); return true; } else if (ea.getKey()=='k') { offsetImage(0.001f,0.0f); return true; } else if (ea.getKey()=='i') { offsetImage(0.0f,-0.001f); return true; } else if (ea.getKey()=='m') { offsetImage(0.0f,0.001f); return true; } else if (ea.getKey()==' ') { initTexMatrices(); return true; } return false; } case(osgGA::GUIEventAdapter::DRAG): case(osgGA::GUIEventAdapter::MOVE): { static float px = ea.getXnormalized(); static float py = ea.getYnormalized(); float dx = ea.getXnormalized()-px; float dy = ea.getYnormalized()-py; px = ea.getXnormalized(); py = ea.getYnormalized(); rotateImage(dx,dy); return true; } default: return false; } } void SlideEventHandler::getUsage(osg::ApplicationUsage& usage) const { usage.addKeyboardMouseBinding("Space","Reset the image position to center"); usage.addKeyboardMouseBinding("a","Toggle on/off the automatic advancement for image to image"); usage.addKeyboardMouseBinding("n","Advance to next image"); usage.addKeyboardMouseBinding("p","Move to previous image"); usage.addKeyboardMouseBinding("q","Zoom into the image"); usage.addKeyboardMouseBinding("a","Zoom out of the image"); usage.addKeyboardMouseBinding("j","Reduce horizontal offset"); usage.addKeyboardMouseBinding("k","Increase horizontal offset"); usage.addKeyboardMouseBinding("m","Reduce vertical offset"); usage.addKeyboardMouseBinding("i","Increase vertical offset"); } void SlideEventHandler::operator()(osg::Node* node, osg::NodeVisitor* nv) { if (_autoSteppingActive && nv->getFrameStamp()) { double time = nv->getFrameStamp()->getSimulationTime(); if (_firstTraversal) { _firstTraversal = false; _previousTime = time; } else if (time-_previousTime>_timePerSlide) { _previousTime = time; nextSlide(); } } traverse(node,nv); } void SlideEventHandler::nextSlide() { if (_switch->getNumChildren()==0) return; ++_activeSlide; if (_fileList.size()>0) { if (_activeSlide>= _fileList.size()/2 ) _activeSlide = 0; osg::ref_ptr<osg::Group> images = loadImages(_fileList[2*_activeSlide],_fileList[2*_activeSlide+1],_texmatLeft.get(),_texmatRight.get(),_radius,_height,_length); if (images.valid()) _switch->replaceChild(_switch->getChild(0),images.get()); } else { if (_activeSlide>=_switch->getNumChildren()) _activeSlide = 0; _switch->setSingleChildOn(_activeSlide); } } void SlideEventHandler::previousSlide() { if (_switch->getNumChildren()==0) return; if (_fileList.size()>0) { if (_activeSlide==0) _activeSlide = _fileList.size()/2-1; else --_activeSlide; osg::ref_ptr<osg::Group> images = loadImages(_fileList[2*_activeSlide],_fileList[2*_activeSlide+1],_texmatLeft.get(),_texmatRight.get(),_radius,_height,_length); if (images.valid()) _switch->replaceChild(_switch->getChild(0),images.get()); } else { if (_activeSlide==0) _activeSlide = _switch->getNumChildren()-1; else --_activeSlide; _switch->setSingleChildOn(_activeSlide); } } void SlideEventHandler::scaleImage(float s) { _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f)); _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f)); } void SlideEventHandler::offsetImage(float ds,float dt) { _currentSeperationX+=ds; _currentSeperationY+=dt; osg::notify(osg::NOTICE)<<"image offset x = "<<_currentSeperationX<<" y ="<<_currentSeperationY<<std::endl; _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(ds,dt,0.0f)); _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-ds,-dt,0.0f)); } void SlideEventHandler::rotateImage(float rx,float ry) { const float scale = 0.5f; _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f)); _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f)); } void SlideEventHandler::initTexMatrices() { _texmatLeft->setMatrix(osg::Matrix::translate(_initSeperationX,_initSeperationY,0.0f)); _texmatRight->setMatrix(osg::Matrix::translate(-_initSeperationX,-_initSeperationY,0.0f)); } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use node masks to create stereo images."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye"); arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time delay in sceonds between the display of successive image pairs when in auto advance mode."); arguments.getApplicationUsage()->addCommandLineOption("-a","Enter auto advance of image pairs on start up."); arguments.getApplicationUsage()->addCommandLineOption("-x <float>","Horizontal offset of left and right images."); arguments.getApplicationUsage()->addCommandLineOption("-y <float>","Vertical offset of left and right images."); arguments.getApplicationUsage()->addCommandLineOption("--disk","Keep images on disk"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); arguments.getApplicationUsage()->addCommandLineOption("--SingleThreaded","Select SingleThreaded threading model for viewer."); arguments.getApplicationUsage()->addCommandLineOption("--CullDrawThreadPerContext","Select CullDrawThreadPerContext threading model for viewer."); arguments.getApplicationUsage()->addCommandLineOption("--DrawThreadPerContext","Select DrawThreadPerContext threading model for viewer."); arguments.getApplicationUsage()->addCommandLineOption("--CullThreadPerCameraDrawThreadPerContext","Select CullThreadPerCameraDrawThreadPerContext threading model for viewer."); // construct the viewer. osgViewer::Viewer viewer; // register the handler to add keyboard and mosue handling. SlideEventHandler* seh = new SlideEventHandler(); viewer.addEventHandler(seh); // read any time delay argument. float timeDelayBetweenSlides = 5.0f; while (arguments.read("-d",timeDelayBetweenSlides)) {} bool autoSteppingActive = false; while (arguments.read("-a")) autoSteppingActive = true; float offsetX=0.0f; while (arguments.read("-x",offsetX)) {} float offsetY=0.0f; while (arguments.read("-y",offsetY)) {} bool onDisk=false; while (arguments.read("--disk")) { onDisk=true;} // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } osgViewer::Viewer::ThreadingModel threading = osgViewer::Viewer::SingleThreaded; while (arguments.read("--SingleThreaded")) threading = osgViewer::Viewer::SingleThreaded; while (arguments.read("--CullDrawThreadPerContext")) threading = osgViewer::Viewer::CullDrawThreadPerContext; while (arguments.read("--DrawThreadPerContext")) threading = osgViewer::Viewer::DrawThreadPerContext; while (arguments.read("--CullThreadPerCameraDrawThreadPerContext")) threading = osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext; viewer.setThreadingModel(threading); // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // extract the filenames from the arguments list. FileList fileList; for(int pos=1;pos<arguments.argc();++pos) { if (arguments.isString(pos)) fileList.push_back(arguments[pos]); } if (fileList.empty()) { fileList.push_back("Images/dog_left_eye.jpg"); fileList.push_back("Images/dog_right_eye.jpg"); } else if (fileList.size()<2) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } // now the windows have been realized we switch off the cursor to prevent it // distracting the people seeing the stereo images. double fovy, aspectRatio, zNear, zFar; viewer.getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar); float radius = 1.0f; float height = 2*radius*tan(osg::DegreesToRadians(fovy)*0.5f); float length = osg::PI*radius; // half a cylinder. // use a texure matrix to control the placement of the image. osg::TexMat* texmatLeft = new osg::TexMat; osg::TexMat* texmatRight = new osg::TexMat; // creat the scene from the file list. osg::ref_ptr<osg::Switch> rootNode; if (!onDisk) rootNode = createScene(fileList,texmatLeft,texmatRight,radius,height,length); else rootNode=new osg::Switch(); //osgDB::writeNodeFile(*rootNode,"test.osg"); viewer.getCamera()->setCullMask(0xffffffff); viewer.getCamera()->setCullMaskLeft(0x00000001); viewer.getCamera()->setCullMaskRight(0x00000002); // set up the use of stereo by default. osg::DisplaySettings::instance()->setStereo(true); // set the scene to render viewer.setSceneData(rootNode.get()); // create the windows and run the threads. viewer.realize(); // switch off the cursor osgViewer::Viewer::Windows windows; viewer.getWindows(windows); for(osgViewer::Viewer::Windows::iterator itr = windows.begin(); itr != windows.end(); ++itr) { (*itr)->useCursor(false); } viewer.setFusionDistance(osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE,radius); // set up the SlideEventHandler. if (onDisk) seh->set(fileList,rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,radius,height,length,timeDelayBetweenSlides,autoSteppingActive); else seh->set(rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,timeDelayBetweenSlides,autoSteppingActive); osg::Matrix homePosition; homePosition.makeLookAt(osg::Vec3(0.0f,0.0f,0.0f),osg::Vec3(0.0f,1.0f,0.0f),osg::Vec3(0.0f,0.0f,1.0f)); while( !viewer.done() ) { viewer.getCamera()->setViewMatrix(homePosition); // fire off the cull and draw traversals of the scene. viewer.frame(); } return 0; }
// ------------------------------------------------------------------------- // @FileName : NFCoroutineModule.cpp // @Author : LvSheng.Huang // @Date : 2017-03-07 // @Module : NFCoroutineModule // @Desc : // ------------------------------------------------------------------------- #include "NFCoroutineManager.h" void ExecuteBody(NFCoroutine* co) { //std::cout << "ExecuteBody " << co->nID << std::endl; co->func(co->arg); co->state = FREE; co->pSchdule->RemoveRunningID(co->nID); //std::cout << "func finished -- swap " << co->nID << " to -1" << std::endl; } NFCoroutineManager::NFCoroutineManager() { std::cout << "threadid " << std::this_thread::get_id() << std::endl; mnMainCoID = -1; mnRunningCoroutineID = -1; mnMaxIndex = 0; for (int i = 0; i < MAX_COROUTINE_CAPACITY; i++) { mxCoroutineList.push_back(new NFCoroutine(this, i)); } std::cout << "created Coroutine number: " << MAX_COROUTINE_CAPACITY <<std::endl; } NFCoroutineManager::~NFCoroutineManager() { for (int i = 0; i < MAX_COROUTINE_CAPACITY; i++) { delete mxCoroutineList[i]; } } void NFCoroutineManager::Resume(int id) { #if NF_PLATFORM != NF_PLATFORM_WIN if (id < 0 || id >= this->mnMaxIndex) { return; } NFCoroutine* t = GetCoroutine(id); if (t->state == SUSPEND) { std::cout << this->mnRunningCoroutineID << " swap to " << id << std::endl; this->mnRunningCoroutineID = id; swapcontext(&(this->mxMainCtx), &(t->ctx)); } #endif } void NFCoroutineManager::YieldCo() { #if NF_PLATFORM != NF_PLATFORM_WIN if (this->mnRunningCoroutineID != -1) { NFCoroutine* t = GetRunningCoroutine(); t->state = SUSPEND; //std::cout << "Yield " << this->mnRunningCoroutineID << " to -1" << std::endl; this->mnRunningCoroutineID = -1; swapcontext(&(t->ctx), &(mxMainCtx)); } #endif } void NFCoroutineManager::Init(CoroutineFunction func) { mxMainFunc = func; mpMainArg = this; NewMainCoroutine(); } void NFCoroutineManager::StartCoroutine() { NewMainCoroutine(); } void NFCoroutineManager::StartCoroutine(CoroutineFunction func) { NewMainCoroutine(); func(this); } void NFCoroutineManager::ScheduleJob() { //std::cout << "threadid " << std::this_thread::get_id() << std::endl; #if NF_PLATFORM != NF_PLATFORM_WIN if (mxRunningList.size() > 0) { int id = mxRunningList.front(); mxRunningList.pop_front(); NFCoroutine* pCoroutine = mxCoroutineList[id]; if (pCoroutine->state == SUSPEND) { mxRunningList.push_back(id); Resume(id); } } else { NewMainCoroutine(); } #else mxMainFunc(this); #endif } int NFCoroutineManager::GetRunningID() { return mnRunningCoroutineID; } void NFCoroutineManager::SetRunningID(int id) { mnRunningCoroutineID = id; } void NFCoroutineManager::RemoveRunningID(int id) { mxRunningList.remove(id); } NFCoroutine* NFCoroutineManager::GetCoroutine(int id) { if (id >= 0 && id < mnMaxIndex) { return mxCoroutineList[id]; } return NULL; } NFCoroutine* NFCoroutineManager::GetRunningCoroutine() { if (mnRunningCoroutineID < 0) { return NULL; } return mxCoroutineList[mnRunningCoroutineID]; } NFCoroutine* NFCoroutineManager::AllotCoroutine() { //std::cout << "threadid " << std::this_thread::get_id() << std::endl; int id = 0; for (; id < mnMaxIndex; ++id) { if (mxCoroutineList[id]->state == FREE) { break; } } if (id == mnMaxIndex) { mnMaxIndex++; } return mxCoroutineList[id]; } void NFCoroutineManager::NewMainCoroutine() { #if NF_PLATFORM != NF_PLATFORM_WIN std::cout << "threadid " << std::this_thread::get_id() << std::endl; NFCoroutine* newCo = AllotCoroutine(); if (newCo == NULL) { return; } mxRunningList.push_back(newCo->nID); //std::cout << "create NewMainCoroutine " << newCo->nID << std::endl; mnMainCoID = newCo->nID; newCo->state = CoroutineState::SUSPEND; newCo->func = mxMainFunc; newCo->arg = mpMainArg; getcontext(&(newCo->ctx)); newCo->ctx.uc_stack.ss_sp = newCo->stack; newCo->ctx.uc_stack.ss_size = MAX_COROUTINE_STACK_SIZE; newCo->ctx.uc_stack.ss_flags = 0; newCo->ctx.uc_link = &(this->mxMainCtx); makecontext(&(newCo->ctx), (void (*)(void)) (ExecuteBody), 1, newCo); #endif } removed log // ------------------------------------------------------------------------- // @FileName : NFCoroutineModule.cpp // @Author : LvSheng.Huang // @Date : 2017-03-07 // @Module : NFCoroutineModule // @Desc : // ------------------------------------------------------------------------- #include "NFCoroutineManager.h" void ExecuteBody(NFCoroutine* co) { //std::cout << "ExecuteBody " << co->nID << std::endl; co->func(co->arg); co->state = FREE; co->pSchdule->RemoveRunningID(co->nID); //std::cout << "func finished -- swap " << co->nID << " to -1" << std::endl; } NFCoroutineManager::NFCoroutineManager() { std::cout << "threadid " << std::this_thread::get_id() << std::endl; mnMainCoID = -1; mnRunningCoroutineID = -1; mnMaxIndex = 0; for (int i = 0; i < MAX_COROUTINE_CAPACITY; i++) { mxCoroutineList.push_back(new NFCoroutine(this, i)); } std::cout << "created Coroutine number: " << MAX_COROUTINE_CAPACITY <<std::endl; } NFCoroutineManager::~NFCoroutineManager() { for (int i = 0; i < MAX_COROUTINE_CAPACITY; i++) { delete mxCoroutineList[i]; } } void NFCoroutineManager::Resume(int id) { #if NF_PLATFORM != NF_PLATFORM_WIN if (id < 0 || id >= this->mnMaxIndex) { return; } NFCoroutine* t = GetCoroutine(id); if (t->state == SUSPEND) { //std::cout << this->mnRunningCoroutineID << " swap to " << id << std::endl; this->mnRunningCoroutineID = id; swapcontext(&(this->mxMainCtx), &(t->ctx)); } #endif } void NFCoroutineManager::YieldCo() { #if NF_PLATFORM != NF_PLATFORM_WIN if (this->mnRunningCoroutineID != -1) { NFCoroutine* t = GetRunningCoroutine(); t->state = SUSPEND; //std::cout << "Yield " << this->mnRunningCoroutineID << " to -1" << std::endl; this->mnRunningCoroutineID = -1; swapcontext(&(t->ctx), &(mxMainCtx)); } #endif } void NFCoroutineManager::Init(CoroutineFunction func) { mxMainFunc = func; mpMainArg = this; NewMainCoroutine(); } void NFCoroutineManager::StartCoroutine() { NewMainCoroutine(); } void NFCoroutineManager::StartCoroutine(CoroutineFunction func) { NewMainCoroutine(); func(this); } void NFCoroutineManager::ScheduleJob() { //std::cout << "threadid " << std::this_thread::get_id() << std::endl; #if NF_PLATFORM != NF_PLATFORM_WIN if (mxRunningList.size() > 0) { int id = mxRunningList.front(); mxRunningList.pop_front(); NFCoroutine* pCoroutine = mxCoroutineList[id]; if (pCoroutine->state == SUSPEND) { mxRunningList.push_back(id); Resume(id); } } else { NewMainCoroutine(); } #else mxMainFunc(this); #endif } int NFCoroutineManager::GetRunningID() { return mnRunningCoroutineID; } void NFCoroutineManager::SetRunningID(int id) { mnRunningCoroutineID = id; } void NFCoroutineManager::RemoveRunningID(int id) { mxRunningList.remove(id); } NFCoroutine* NFCoroutineManager::GetCoroutine(int id) { if (id >= 0 && id < mnMaxIndex) { return mxCoroutineList[id]; } return NULL; } NFCoroutine* NFCoroutineManager::GetRunningCoroutine() { if (mnRunningCoroutineID < 0) { return NULL; } return mxCoroutineList[mnRunningCoroutineID]; } NFCoroutine* NFCoroutineManager::AllotCoroutine() { //std::cout << "threadid " << std::this_thread::get_id() << std::endl; int id = 0; for (; id < mnMaxIndex; ++id) { if (mxCoroutineList[id]->state == FREE) { break; } } if (id == mnMaxIndex) { mnMaxIndex++; } return mxCoroutineList[id]; } void NFCoroutineManager::NewMainCoroutine() { #if NF_PLATFORM != NF_PLATFORM_WIN //std::cout << "threadid " << std::this_thread::get_id() << std::endl; NFCoroutine* newCo = AllotCoroutine(); if (newCo == NULL) { return; } mxRunningList.push_back(newCo->nID); //std::cout << "create NewMainCoroutine " << newCo->nID << std::endl; mnMainCoID = newCo->nID; newCo->state = CoroutineState::SUSPEND; newCo->func = mxMainFunc; newCo->arg = mpMainArg; getcontext(&(newCo->ctx)); newCo->ctx.uc_stack.ss_sp = newCo->stack; newCo->ctx.uc_stack.ss_size = MAX_COROUTINE_STACK_SIZE; newCo->ctx.uc_stack.ss_flags = 0; newCo->ctx.uc_link = &(this->mxMainCtx); makecontext(&(newCo->ctx), (void (*)(void)) (ExecuteBody), 1, newCo); #endif }
/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" namespace watchman { CookieSync::CookieSync(const w_string& dir) { setCookieDir(dir); } void CookieSync::setCookieDir(const w_string& dir) { cookieDir_ = dir; char hostname[256]; gethostname(hostname, sizeof(hostname)); hostname[sizeof(hostname) - 1] = '\0'; cookiePrefix_ = w_string::printf( "%.*s/" WATCHMAN_COOKIE_PREFIX "%s-%d-", int(cookieDir_.size()), cookieDir_.data(), hostname, int(getpid())); } bool CookieSync::syncToNow(std::chrono::milliseconds timeout) { Cookie cookie; int errcode = 0; auto cookie_lock = std::unique_lock<std::mutex>(cookie.mutex); /* generate a cookie name: cookie prefix + id */ auto path_str = w_string::printf( "%.*s%" PRIu32, int(cookiePrefix_.size()), cookiePrefix_.data(), serial_++); /* insert our cookie in the map */ { auto wlock = cookies_.wlock(); auto& map = *wlock; map[path_str] = &cookie; } /* compute deadline */ auto deadline = std::chrono::system_clock::now() + timeout; /* touch the file */ auto file = w_stm_open( path_str.c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC, 0700); if (!file) { errcode = errno; w_log( W_LOG_ERR, "sync_to_now: creat(%s) failed: %s\n", path_str.c_str(), strerror(errcode)); goto out; } file.reset(); w_log(W_LOG_DBG, "sync_to_now [%s] waiting\n", path_str.c_str()); /* timed cond wait (unlocks cookie lock, reacquires) */ if (!cookie.cond.wait_until( cookie_lock, deadline, [&] { return cookie.seen; })) { w_log( W_LOG_ERR, "sync_to_now: %s timedwait failed: %d: istimeout=%d %s\n", path_str.c_str(), errcode, errcode == ETIMEDOUT, strerror(errcode)); goto out; } w_log(W_LOG_DBG, "sync_to_now [%s] done\n", path_str.c_str()); out: cookie_lock.unlock(); // can't unlink the file until after the cookie has been observed because // we don't know which file got changed until we look in the cookie dir unlink(path_str.c_str()); { auto map = cookies_.wlock(); map->erase(path_str); } if (!cookie.seen) { errno = errcode; return false; } return true; } void CookieSync::notifyCookie(const w_string& path) const { auto map = cookies_.rlock(); auto cookie_iter = map->find(path); w_log( W_LOG_DBG, "cookie for %s? %s\n", path.c_str(), cookie_iter != map->end() ? "yes" : "no"); if (cookie_iter != map->end()) { auto cookie = cookie_iter->second; auto cookie_lock = std::unique_lock<std::mutex>(cookie->mutex); cookie->seen = true; cookie->cond.notify_one(); } } } fixup error messaging for timeout in cookie sync Summary: Since refactoring this to use the C++ condition_variable, we've been reporting cookie sync timeouts as unknown errors. Since we're using the predicate form of condition_variable::wait_until, a failure is always a timeout, so let's adjust the how we log it. Reviewed By: simpkins Differential Revision: D5082053 fbshipit-source-id: d64f1a50d520b04a0064cea629072d335c8ced76 /* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" namespace watchman { CookieSync::CookieSync(const w_string& dir) { setCookieDir(dir); } void CookieSync::setCookieDir(const w_string& dir) { cookieDir_ = dir; char hostname[256]; gethostname(hostname, sizeof(hostname)); hostname[sizeof(hostname) - 1] = '\0'; cookiePrefix_ = w_string::printf( "%.*s/" WATCHMAN_COOKIE_PREFIX "%s-%d-", int(cookieDir_.size()), cookieDir_.data(), hostname, int(getpid())); } bool CookieSync::syncToNow(std::chrono::milliseconds timeout) { Cookie cookie; int errcode = 0; auto cookie_lock = std::unique_lock<std::mutex>(cookie.mutex); /* generate a cookie name: cookie prefix + id */ auto path_str = w_string::printf( "%.*s%" PRIu32, int(cookiePrefix_.size()), cookiePrefix_.data(), serial_++); /* insert our cookie in the map */ { auto wlock = cookies_.wlock(); auto& map = *wlock; map[path_str] = &cookie; } /* compute deadline */ auto deadline = std::chrono::system_clock::now() + timeout; /* touch the file */ auto file = w_stm_open( path_str.c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC, 0700); if (!file) { errcode = errno; log(ERR, "syncToNow: creat(", path_str, ") failed: ", strerror(errcode), "\n"); goto out; } file.reset(); log(DBG, "syncToNow [", path_str, "] waiting\n"); /* timed cond wait (unlocks cookie lock, reacquires) */ if (!cookie.cond.wait_until( cookie_lock, deadline, [&] { return cookie.seen; })) { log(ERR, "syncToNow: timed out waiting for cookie file ", path_str, " to be observed by watcher within ", timeout.count(), " milliseconds\n"); errcode = ETIMEDOUT; goto out; } log(DBG, "syncToNow [", path_str, "] done\n"); out: cookie_lock.unlock(); // can't unlink the file until after the cookie has been observed because // we don't know which file got changed until we look in the cookie dir unlink(path_str.c_str()); { auto map = cookies_.wlock(); map->erase(path_str); } if (!cookie.seen) { errno = errcode; return false; } return true; } void CookieSync::notifyCookie(const w_string& path) const { auto map = cookies_.rlock(); auto cookie_iter = map->find(path); w_log( W_LOG_DBG, "cookie for %s? %s\n", path.c_str(), cookie_iter != map->end() ? "yes" : "no"); if (cookie_iter != map->end()) { auto cookie = cookie_iter->second; auto cookie_lock = std::unique_lock<std::mutex>(cookie->mutex); cookie->seen = true; cookie->cond.notify_one(); } } }
/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2009, 2012, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /** @file @brief Sorts a database */ #include "sql_priv.h" #include "filesort.h" #include "unireg.h" // REQUIRED by other includes #ifdef HAVE_STDDEF_H #include <stddef.h> /* for macro offsetof */ #endif #include <m_ctype.h> #include "sql_sort.h" #include "probes_mysql.h" #include "sql_base.h" // update_virtual_fields #include "sql_test.h" // TEST_filesort #include "opt_range.h" // SQL_SELECT #include "bounded_queue.h" #include "filesort_utils.h" #include "sql_select.h" #include "log_slow.h" #include "debug_sync.h" #include "sql_base.h" /// How to write record_ref. #define WRITE_REF(file,from) \ if (my_b_write((file),(uchar*) (from),param->ref_length)) \ DBUG_RETURN(1); /* functions defined in this file */ static uchar *read_buffpek_from_file(IO_CACHE *buffer_file, uint count, uchar *buf); static ha_rows find_all_keys(Sort_param *param,SQL_SELECT *select, Filesort_info *fs_info, IO_CACHE *buffer_file, IO_CACHE *tempfile, Bounded_queue<uchar, uchar> *pq, ha_rows *found_rows); static bool write_keys(Sort_param *param, Filesort_info *fs_info, uint count, IO_CACHE *buffer_file, IO_CACHE *tempfile); static void make_sortkey(Sort_param *param, uchar *to, uchar *ref_pos); static void register_used_fields(Sort_param *param); static bool save_index(Sort_param *param, uint count, Filesort_info *table_sort); static uint suffix_length(ulong string_length); static uint sortlength(THD *thd, SORT_FIELD *sortorder, uint s_length, bool *multi_byte_charset); static SORT_ADDON_FIELD *get_addon_fields(ulong max_length_for_sort_data, Field **ptabfield, uint sortlength, uint *plength); static void unpack_addon_fields(struct st_sort_addon_field *addon_field, uchar *buff, uchar *buff_end); static bool check_if_pq_applicable(Sort_param *param, Filesort_info *info, TABLE *table, ha_rows records, ulong memory_available); void Sort_param::init_for_filesort(uint sortlen, TABLE *table, ulong max_length_for_sort_data, ha_rows maxrows, bool sort_positions) { sort_length= sortlen; ref_length= table->file->ref_length; if (!(table->file->ha_table_flags() & HA_FAST_KEY_READ) && !table->fulltext_searched && !sort_positions) { /* Get the descriptors of all fields whose values are appended to sorted fields and get its total length in addon_length. */ addon_field= get_addon_fields(max_length_for_sort_data, table->field, sort_length, &addon_length); } if (addon_field) res_length= addon_length; else { res_length= ref_length; /* The reference to the record is considered as an additional sorted field */ sort_length+= ref_length; } rec_length= sort_length + addon_length; max_rows= maxrows; } /** Sort a table. Creates a set of pointers that can be used to read the rows in sorted order. This should be done with the functions in records.cc. Before calling filesort, one must have done table->file->info(HA_STATUS_VARIABLE) The result set is stored in table->io_cache or table->record_pointers. @param thd Current thread @param table Table to sort @param sortorder How to sort the table @param s_length Number of elements in sortorder @param select Condition to apply to the rows @param max_rows Return only this many rows @param sort_positions Set to TRUE if we want to force sorting by position (Needed by UPDATE/INSERT or ALTER TABLE or when rowids are required by executor) @param[out] examined_rows Store number of examined rows here @param[out] found_rows Store the number of found rows here @note If we sort by position (like if sort_positions is 1) filesort() will call table->prepare_for_position(). @retval HA_POS_ERROR Error @retval \# Number of rows */ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length, SQL_SELECT *select, ha_rows max_rows, bool sort_positions, ha_rows *examined_rows, ha_rows *found_rows) { int error; size_t memory_available= thd->variables.sortbuff_size; uint maxbuffer; BUFFPEK *buffpek; ha_rows num_rows= HA_POS_ERROR; IO_CACHE tempfile, buffpek_pointers, *outfile; Sort_param param; bool multi_byte_charset; Bounded_queue<uchar, uchar> pq; DBUG_ENTER("filesort"); DBUG_EXECUTE("info",TEST_filesort(sortorder,s_length);); #ifdef SKIP_DBUG_IN_FILESORT DBUG_PUSH(""); /* No DBUG here */ #endif Filesort_info table_sort= table->sort; TABLE_LIST *tab= table->pos_in_table_list; Item_subselect *subselect= tab ? tab->containing_subselect() : 0; MYSQL_FILESORT_START(table->s->db.str, table->s->table_name.str); DEBUG_SYNC(thd, "filesort_start"); /* Release InnoDB's adaptive hash index latch (if holding) before running a sort. */ ha_release_temporary_latches(thd); /* Don't use table->sort in filesort as it is also used by QUICK_INDEX_MERGE_SELECT. Work with a copy and put it back at the end when index_merge select has finished with it. */ table->sort.io_cache= NULL; DBUG_ASSERT(table_sort.record_pointers == NULL); outfile= table_sort.io_cache; my_b_clear(&tempfile); my_b_clear(&buffpek_pointers); buffpek=0; error= 1; param.init_for_filesort(sortlength(thd, sortorder, s_length, &multi_byte_charset), table, thd->variables.max_length_for_sort_data, max_rows, sort_positions); table_sort.addon_buf= 0; table_sort.addon_length= param.addon_length; table_sort.addon_field= param.addon_field; table_sort.unpack= unpack_addon_fields; if (param.addon_field && !(table_sort.addon_buf= (uchar *) my_malloc(param.addon_length, MYF(MY_WME | MY_THREAD_SPECIFIC)))) goto err; if (select && select->quick) thd->inc_status_sort_range(); else thd->inc_status_sort_scan(); thd->query_plan_flags|= QPLAN_FILESORT; // If number of rows is not known, use as much of sort buffer as possible. num_rows= table->file->estimate_rows_upper_bound(); if (multi_byte_charset && !(param.tmp_buffer= (char*) my_malloc(param.sort_length, MYF(MY_WME | MY_THREAD_SPECIFIC)))) goto err; if (check_if_pq_applicable(&param, &table_sort, table, num_rows, memory_available)) { DBUG_PRINT("info", ("filesort PQ is applicable")); const size_t compare_length= param.sort_length; if (pq.init(param.max_rows, true, // max_at_top NULL, // compare_function compare_length, &make_sortkey, &param, table_sort.get_sort_keys())) { /* If we fail to init pq, we have to give up: out of memory means my_malloc() will call my_error(). */ DBUG_PRINT("info", ("failed to allocate PQ")); table_sort.free_sort_buffer(); DBUG_ASSERT(thd->is_error()); goto err; } // For PQ queries (with limit) we initialize all pointers. table_sort.init_record_pointers(); } else { DBUG_PRINT("info", ("filesort PQ is not applicable")); size_t min_sort_memory= MY_MAX(MIN_SORT_MEMORY, param.sort_length*MERGEBUFF2); set_if_bigger(min_sort_memory, sizeof(BUFFPEK*)*MERGEBUFF2); while (memory_available >= min_sort_memory) { ulonglong keys= memory_available / (param.rec_length + sizeof(char*)); param.max_keys_per_buffer= (uint) MY_MIN(num_rows, keys); if (table_sort.get_sort_keys()) { // If we have already allocated a buffer, it better have same size! if (!table_sort.check_sort_buffer_properties(param.max_keys_per_buffer, param.rec_length)) { /* table->sort will still have a pointer to the same buffer, but that will be overwritten by the assignment below. */ table_sort.free_sort_buffer(); } } table_sort.alloc_sort_buffer(param.max_keys_per_buffer, param.rec_length); if (table_sort.get_sort_keys()) break; size_t old_memory_available= memory_available; memory_available= memory_available/4*3; if (memory_available < min_sort_memory && old_memory_available > min_sort_memory) memory_available= min_sort_memory; } if (memory_available < min_sort_memory) { my_error(ER_OUT_OF_SORTMEMORY,MYF(ME_ERROR + ME_FATALERROR)); goto err; } } if (open_cached_file(&buffpek_pointers,mysql_tmpdir,TEMP_PREFIX, DISK_BUFFER_SIZE, MYF(MY_WME))) goto err; param.sort_form= table; param.end=(param.local_sortorder=sortorder)+s_length; num_rows= find_all_keys(&param, select, &table_sort, &buffpek_pointers, &tempfile, pq.is_initialized() ? &pq : NULL, found_rows); if (num_rows == HA_POS_ERROR) goto err; maxbuffer= (uint) (my_b_tell(&buffpek_pointers)/sizeof(*buffpek)); if (maxbuffer == 0) // The whole set is in memory { if (save_index(&param, (uint) num_rows, &table_sort)) goto err; } else { /* filesort cannot handle zero-length records during merge. */ DBUG_ASSERT(param.sort_length != 0); if (table_sort.buffpek && table_sort.buffpek_len < maxbuffer) { my_free(table_sort.buffpek); table_sort.buffpek= 0; } if (!(table_sort.buffpek= (uchar *) read_buffpek_from_file(&buffpek_pointers, maxbuffer, table_sort.buffpek))) goto err; buffpek= (BUFFPEK *) table_sort.buffpek; table_sort.buffpek_len= maxbuffer; close_cached_file(&buffpek_pointers); /* Open cached file if it isn't open */ if (! my_b_inited(outfile) && open_cached_file(outfile,mysql_tmpdir,TEMP_PREFIX,READ_RECORD_BUFFER, MYF(MY_WME))) goto err; if (reinit_io_cache(outfile,WRITE_CACHE,0L,0,0)) goto err; /* Use also the space previously used by string pointers in sort_buffer for temporary key storage. */ param.max_keys_per_buffer=((param.max_keys_per_buffer * (param.rec_length + sizeof(char*))) / param.rec_length - 1); maxbuffer--; // Offset from 0 if (merge_many_buff(&param, (uchar*) table_sort.get_sort_keys(), buffpek,&maxbuffer, &tempfile)) goto err; if (flush_io_cache(&tempfile) || reinit_io_cache(&tempfile,READ_CACHE,0L,0,0)) goto err; if (merge_index(&param, (uchar*) table_sort.get_sort_keys(), buffpek, maxbuffer, &tempfile, outfile)) goto err; } if (num_rows > param.max_rows) { // If find_all_keys() produced more results than the query LIMIT. num_rows= param.max_rows; } error= 0; err: my_free(param.tmp_buffer); if (!subselect || !subselect->is_uncacheable()) { table_sort.free_sort_buffer(); my_free(buffpek); table_sort.buffpek= 0; table_sort.buffpek_len= 0; } close_cached_file(&tempfile); close_cached_file(&buffpek_pointers); if (my_b_inited(outfile)) { if (flush_io_cache(outfile)) error=1; { my_off_t save_pos=outfile->pos_in_file; /* For following reads */ if (reinit_io_cache(outfile,READ_CACHE,0L,0,0)) error=1; outfile->end_of_file=save_pos; } } if (error) { int kill_errno= thd->killed_errno(); DBUG_ASSERT(thd->is_error() || kill_errno || thd->killed == ABORT_QUERY); /* We replace the table->sort at the end. Hence calling free_io_cache to make sure table->sort.io_cache used for QUICK_INDEX_MERGE_SELECT is free. */ free_io_cache(table); my_printf_error(ER_FILSORT_ABORT, "%s: %s", MYF(0), ER_THD(thd, ER_FILSORT_ABORT), kill_errno ? ER(kill_errno) : thd->killed == ABORT_QUERY ? "" : thd->get_stmt_da()->message()); if (global_system_variables.log_warnings > 1) { sql_print_warning("%s, host: %s, user: %s, thread: %lu, query: %-.4096s", ER_THD(thd, ER_FILSORT_ABORT), thd->security_ctx->host_or_ip, &thd->security_ctx->priv_user[0], (ulong) thd->thread_id, thd->query()); } } else thd->inc_status_sort_rows(num_rows); *examined_rows= param.examined_rows; #ifdef SKIP_DBUG_IN_FILESORT DBUG_POP(); /* Ok to DBUG */ #endif /* table->sort.io_cache should be free by this time */ DBUG_ASSERT(NULL == table->sort.io_cache); // Assign the copy back! table->sort= table_sort; DBUG_PRINT("exit", ("num_rows: %ld examined_rows: %ld found_rows: %ld", (long) num_rows, (long) *examined_rows, (long) *found_rows)); MYSQL_FILESORT_DONE(error, num_rows); DBUG_RETURN(error ? HA_POS_ERROR : num_rows); } /* filesort */ void filesort_free_buffers(TABLE *table, bool full) { DBUG_ENTER("filesort_free_buffers"); my_free(table->sort.record_pointers); table->sort.record_pointers= NULL; if (full) { table->sort.free_sort_buffer(); my_free(table->sort.buffpek); table->sort.buffpek= NULL; table->sort.buffpek_len= 0; } my_free(table->sort.addon_buf); my_free(table->sort.addon_field); table->sort.addon_buf= NULL; table->sort.addon_field= NULL; DBUG_VOID_RETURN; } /** Read 'count' number of buffer pointers into memory. */ static uchar *read_buffpek_from_file(IO_CACHE *buffpek_pointers, uint count, uchar *buf) { size_t length= sizeof(BUFFPEK)*count; uchar *tmp= buf; DBUG_ENTER("read_buffpek_from_file"); if (count > UINT_MAX/sizeof(BUFFPEK)) return 0; /* sizeof(BUFFPEK)*count will overflow */ if (!tmp) tmp= (uchar *)my_malloc(length, MYF(MY_WME | MY_THREAD_SPECIFIC)); if (tmp) { if (reinit_io_cache(buffpek_pointers,READ_CACHE,0L,0,0) || my_b_read(buffpek_pointers, (uchar*) tmp, length)) { my_free(tmp); tmp=0; } } DBUG_RETURN(tmp); } #ifndef DBUG_OFF /* Buffer where record is returned */ char dbug_print_row_buff[512]; /* Temporary buffer for printing a column */ char dbug_print_row_buff_tmp[512]; /* Print table's current row into a buffer and return a pointer to it. This is intended to be used from gdb: (gdb) p dbug_print_table_row(table) $33 = "SUBQUERY2_t1(col_int_key,col_varchar_nokey)=(7,c)" (gdb) Only columns in table->read_set are printed */ const char* dbug_print_table_row(TABLE *table) { Field **pfield; String tmp(dbug_print_row_buff_tmp, sizeof(dbug_print_row_buff_tmp),&my_charset_bin); String output(dbug_print_row_buff, sizeof(dbug_print_row_buff), &my_charset_bin); output.length(0); output.append(table->alias); output.append("("); bool first= true; for (pfield= table->field; *pfield ; pfield++) { if (table->read_set && !bitmap_is_set(table->read_set, (*pfield)->field_index)) continue; if (first) first= false; else output.append(","); output.append((*pfield)->field_name? (*pfield)->field_name: "NULL"); } output.append(")=("); first= true; for (pfield= table->field; *pfield ; pfield++) { Field *field= *pfield; if (table->read_set && !bitmap_is_set(table->read_set, (*pfield)->field_index)) continue; if (first) first= false; else output.append(","); if (field->is_null()) output.append("NULL"); else { if (field->type() == MYSQL_TYPE_BIT) (void) field->val_int_as_str(&tmp, 1); else field->val_str(&tmp); output.append(tmp.ptr(), tmp.length()); } } output.append(")"); return output.c_ptr_safe(); } /* Print a text, SQL-like record representation into dbug trace. Note: this function is a work in progress: at the moment - column read bitmap is ignored (can print garbage for unused columns) - there is no quoting */ static void dbug_print_record(TABLE *table, bool print_rowid) { char buff[1024]; Field **pfield; String tmp(buff,sizeof(buff),&my_charset_bin); DBUG_LOCK_FILE; fprintf(DBUG_FILE, "record ("); for (pfield= table->field; *pfield ; pfield++) fprintf(DBUG_FILE, "%s%s", (*pfield)->field_name, (pfield[1])? ", ":""); fprintf(DBUG_FILE, ") = "); fprintf(DBUG_FILE, "("); for (pfield= table->field; *pfield ; pfield++) { Field *field= *pfield; if (field->is_null()) fwrite("NULL", sizeof(char), 4, DBUG_FILE); if (field->type() == MYSQL_TYPE_BIT) (void) field->val_int_as_str(&tmp, 1); else field->val_str(&tmp); fwrite(tmp.ptr(),sizeof(char),tmp.length(),DBUG_FILE); if (pfield[1]) fwrite(", ", sizeof(char), 2, DBUG_FILE); } fprintf(DBUG_FILE, ")"); if (print_rowid) { fprintf(DBUG_FILE, " rowid "); for (uint i=0; i < table->file->ref_length; i++) { fprintf(DBUG_FILE, "%x", (uchar)table->file->ref[i]); } } fprintf(DBUG_FILE, "\n"); DBUG_UNLOCK_FILE; } #endif /** Search after sort_keys, and write them into tempfile (if we run out of space in the sort_keys buffer). All produced sequences are guaranteed to be non-empty. @param param Sorting parameter @param select Use this to get source data @param sort_keys Array of pointers to sort key + addon buffers. @param buffpek_pointers File to write BUFFPEKs describing sorted segments in tempfile. @param tempfile File to write sorted sequences of sortkeys to. @param pq If !NULL, use it for keeping top N elements @param [out] found_rows The number of FOUND_ROWS(). For a query with LIMIT, this value will typically be larger than the function return value. @note Basic idea: @verbatim while (get_next_sortkey()) { if (using priority queue) push sort key into queue else { if (no free space in sort_keys buffers) { sort sort_keys buffer; dump sorted sequence to 'tempfile'; dump BUFFPEK describing sequence location into 'buffpek_pointers'; } put sort key into 'sort_keys'; } } if (sort_keys has some elements && dumped at least once) sort-dump-dump as above; else don't sort, leave sort_keys array to be sorted by caller. @endverbatim @retval Number of records written on success. @retval HA_POS_ERROR on error. */ static ha_rows find_all_keys(Sort_param *param, SQL_SELECT *select, Filesort_info *fs_info, IO_CACHE *buffpek_pointers, IO_CACHE *tempfile, Bounded_queue<uchar, uchar> *pq, ha_rows *found_rows) { int error,flag,quick_select; uint idx,indexpos,ref_length; uchar *ref_pos,*next_pos,ref_buff[MAX_REFLENGTH]; my_off_t record; TABLE *sort_form; THD *thd= current_thd; handler *file; MY_BITMAP *save_read_set, *save_write_set, *save_vcol_set; DBUG_ENTER("find_all_keys"); DBUG_PRINT("info",("using: %s", (select ? select->quick ? "ranges" : "where": "every row"))); idx=indexpos=0; error=quick_select=0; sort_form=param->sort_form; file=sort_form->file; ref_length=param->ref_length; ref_pos= ref_buff; quick_select=select && select->quick; record=0; *found_rows= pq ? 0 : HA_POS_ERROR; // don't count unless pq is used flag= ((file->ha_table_flags() & HA_REC_NOT_IN_SEQ) || quick_select); if (flag) ref_pos= &file->ref[0]; next_pos=ref_pos; DBUG_EXECUTE_IF("show_explain_in_find_all_keys", dbug_serve_apcs(thd, 1); ); if (!quick_select) { next_pos=(uchar*) 0; /* Find records in sequence */ DBUG_EXECUTE_IF("bug14365043_1", DBUG_SET("+d,ha_rnd_init_fail");); if (file->ha_rnd_init_with_error(1)) DBUG_RETURN(HA_POS_ERROR); file->extra_opt(HA_EXTRA_CACHE, current_thd->variables.read_buff_size); } /* Remember original bitmaps */ save_read_set= sort_form->read_set; save_write_set= sort_form->write_set; save_vcol_set= sort_form->vcol_set; /* Set up temporary column read map for columns used by sort */ bitmap_clear_all(&sort_form->tmp_set); /* Temporary set for register_used_fields and register_field_in_read_map */ sort_form->read_set= &sort_form->tmp_set; register_used_fields(param); Item *sort_cond= !select ? 0 : !select->pre_idx_push_select_cond ? select->cond : select->pre_idx_push_select_cond; if (sort_cond) sort_cond->walk(&Item::register_field_in_read_map, 1, (uchar*) sort_form); sort_form->column_bitmaps_set(&sort_form->tmp_set, &sort_form->tmp_set, &sort_form->tmp_set); if (quick_select) { if (select->quick->reset()) DBUG_RETURN(HA_POS_ERROR); } DEBUG_SYNC(thd, "after_index_merge_phase1"); for (;;) { if (quick_select) { if ((error= select->quick->get_next())) break; if (!error && sort_form->vfield) update_virtual_fields(thd, sort_form); file->position(sort_form->record[0]); DBUG_EXECUTE_IF("debug_filesort", dbug_print_record(sort_form, TRUE);); } else /* Not quick-select */ { { error= file->ha_rnd_next(sort_form->record[0]); if (!error && sort_form->vfield) update_virtual_fields(thd, sort_form); if (!flag) { my_store_ptr(ref_pos,ref_length,record); // Position to row record+= sort_form->s->db_record_offset; } else if (!error) file->position(sort_form->record[0]); } if (error && error != HA_ERR_RECORD_DELETED) break; } if (thd->check_killed()) { DBUG_PRINT("info",("Sort killed by user")); if (!quick_select) { (void) file->extra(HA_EXTRA_NO_CACHE); file->ha_rnd_end(); } DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */ } bool write_record= false; if (error == 0) { param->examined_rows++; if (select && select->cond) { /* If the condition 'select->cond' contains a subquery, restore the original read/write sets of the table 'sort_form' because when SQL_SELECT::skip_record evaluates this condition. it may include a correlated subquery predicate, such that some field in the subquery refers to 'sort_form'. PSergey-todo: discuss the above with Timour. */ MY_BITMAP *tmp_read_set= sort_form->read_set; MY_BITMAP *tmp_write_set= sort_form->write_set; MY_BITMAP *tmp_vcol_set= sort_form->vcol_set; if (select->cond->with_subselect) sort_form->column_bitmaps_set(save_read_set, save_write_set, save_vcol_set); write_record= (select->skip_record(thd) > 0); if (select->cond->with_subselect) sort_form->column_bitmaps_set(tmp_read_set, tmp_write_set, tmp_vcol_set); } else write_record= true; } if (write_record) { if (pq) { /* only count rows when pq is used - otherwise there might be other filters *after* the filesort, we don't know the final row count here */ (*found_rows)++; pq->push(ref_pos); idx= pq->num_elements(); } else { if (idx == param->max_keys_per_buffer) { if (write_keys(param, fs_info, idx, buffpek_pointers, tempfile)) DBUG_RETURN(HA_POS_ERROR); idx= 0; indexpos++; } make_sortkey(param, fs_info->get_record_buffer(idx++), ref_pos); } } /* It does not make sense to read more keys in case of a fatal error */ if (thd->is_error()) break; /* We need to this after checking the error as the transaction may have rolled back in case of a deadlock */ if (!write_record) file->unlock_row(); } if (!quick_select) { (void) file->extra(HA_EXTRA_NO_CACHE); /* End cacheing of records */ if (!next_pos) file->ha_rnd_end(); } if (thd->is_error()) DBUG_RETURN(HA_POS_ERROR); /* Signal we should use orignal column read and write maps */ sort_form->column_bitmaps_set(save_read_set, save_write_set, save_vcol_set); DBUG_PRINT("test",("error: %d indexpos: %d",error,indexpos)); if (error != HA_ERR_END_OF_FILE) { file->print_error(error,MYF(ME_ERROR | ME_WAITTANG)); // purecov: inspected DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */ } if (indexpos && idx && write_keys(param, fs_info, idx, buffpek_pointers, tempfile)) DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */ const ha_rows retval= my_b_inited(tempfile) ? (ha_rows) (my_b_tell(tempfile)/param->rec_length) : idx; DBUG_PRINT("info", ("find_all_keys return %u", (uint) retval)); DBUG_RETURN(retval); } /* find_all_keys */ /** @details Sort the buffer and write: -# the sorted sequence to tempfile -# a BUFFPEK describing the sorted sequence position to buffpek_pointers (was: Skriver en buffert med nycklar till filen) @param param Sort parameters @param sort_keys Array of pointers to keys to sort @param count Number of elements in sort_keys array @param buffpek_pointers One 'BUFFPEK' struct will be written into this file. The BUFFPEK::{file_pos, count} will indicate where the sorted data was stored. @param tempfile The sorted sequence will be written into this file. @retval 0 OK @retval 1 Error */ static bool write_keys(Sort_param *param, Filesort_info *fs_info, uint count, IO_CACHE *buffpek_pointers, IO_CACHE *tempfile) { size_t rec_length; uchar **end; BUFFPEK buffpek; DBUG_ENTER("write_keys"); rec_length= param->rec_length; uchar **sort_keys= fs_info->get_sort_keys(); fs_info->sort_buffer(param, count); if (!my_b_inited(tempfile) && open_cached_file(tempfile, mysql_tmpdir, TEMP_PREFIX, DISK_BUFFER_SIZE, MYF(MY_WME))) goto err; /* purecov: inspected */ /* check we won't have more buffpeks than we can possibly keep in memory */ if (my_b_tell(buffpek_pointers) + sizeof(BUFFPEK) > (ulonglong)UINT_MAX) goto err; buffpek.file_pos= my_b_tell(tempfile); if ((ha_rows) count > param->max_rows) count=(uint) param->max_rows; /* purecov: inspected */ buffpek.count=(ha_rows) count; for (end=sort_keys+count ; sort_keys != end ; sort_keys++) if (my_b_write(tempfile, (uchar*) *sort_keys, (uint) rec_length)) goto err; if (my_b_write(buffpek_pointers, (uchar*) &buffpek, sizeof(buffpek))) goto err; DBUG_RETURN(0); err: DBUG_RETURN(1); } /* write_keys */ /** Store length as suffix in high-byte-first order. */ static inline void store_length(uchar *to, uint length, uint pack_length) { switch (pack_length) { case 1: *to= (uchar) length; break; case 2: mi_int2store(to, length); break; case 3: mi_int3store(to, length); break; default: mi_int4store(to, length); break; } } /** Make a sort-key from record. */ static void make_sortkey(register Sort_param *param, register uchar *to, uchar *ref_pos) { reg3 Field *field; reg1 SORT_FIELD *sort_field; reg5 uint length; for (sort_field=param->local_sortorder ; sort_field != param->end ; sort_field++) { bool maybe_null=0; if ((field=sort_field->field)) { // Field field->make_sort_key(to, sort_field->length); if ((maybe_null = field->maybe_null())) to++; } else { // Item Item *item=sort_field->item; maybe_null= item->maybe_null; switch (sort_field->result_type) { case STRING_RESULT: { const CHARSET_INFO *cs=item->collation.collation; char fill_char= ((cs->state & MY_CS_BINSORT) ? (char) 0 : ' '); if (maybe_null) *to++=1; char *tmp_buffer= param->tmp_buffer ? param->tmp_buffer : (char*)to; String tmp(tmp_buffer, param->sort_length, cs); String *res= item->str_result(&tmp); if (!res) { if (maybe_null) memset(to-1, 0, sort_field->length+1); else { /* purecov: begin deadcode */ /* This should only happen during extreme conditions if we run out of memory or have an item marked not null when it can be null. This code is here mainly to avoid a hard crash in this case. */ DBUG_ASSERT(0); DBUG_PRINT("warning", ("Got null on something that shouldn't be null")); memset(to, 0, sort_field->length); // Avoid crash /* purecov: end */ } break; } length= res->length(); if (sort_field->need_strxnfrm) { uint tmp_length __attribute__((unused)); tmp_length= cs->coll->strnxfrm(cs, to, sort_field->length, item->max_char_length() * cs->strxfrm_multiply, (uchar*) res->ptr(), length, MY_STRXFRM_PAD_WITH_SPACE | MY_STRXFRM_PAD_TO_MAXLEN); DBUG_ASSERT(tmp_length == sort_field->length); } else { uint diff; uint sort_field_length= sort_field->length - sort_field->suffix_length; if (sort_field_length < length) { diff= 0; length= sort_field_length; } else diff= sort_field_length - length; if (sort_field->suffix_length) { /* Store length last in result_string */ store_length(to + sort_field_length, length, sort_field->suffix_length); } /* apply cs->sort_order for case-insensitive comparison if needed */ my_strnxfrm(cs,(uchar*)to,length,(const uchar*)res->ptr(),length); cs->cset->fill(cs, (char *)to+length,diff,fill_char); } break; } case INT_RESULT: case TIME_RESULT: { longlong UNINIT_VAR(value); if (sort_field->result_type == INT_RESULT) value= item->val_int_result(); else { MYSQL_TIME buf; if (item->get_date_result(&buf, TIME_INVALID_DATES)) { DBUG_ASSERT(maybe_null); DBUG_ASSERT(item->null_value); } else value= pack_time(&buf); } if (maybe_null) { *to++=1; /* purecov: inspected */ if (item->null_value) { if (maybe_null) memset(to-1, 0, sort_field->length+1); else { DBUG_PRINT("warning", ("Got null on something that shouldn't be null")); memset(to, 0, sort_field->length); } break; } } to[7]= (uchar) value; to[6]= (uchar) (value >> 8); to[5]= (uchar) (value >> 16); to[4]= (uchar) (value >> 24); to[3]= (uchar) (value >> 32); to[2]= (uchar) (value >> 40); to[1]= (uchar) (value >> 48); if (item->unsigned_flag) /* Fix sign */ to[0]= (uchar) (value >> 56); else to[0]= (uchar) (value >> 56) ^ 128; /* Reverse signbit */ break; } case DECIMAL_RESULT: { my_decimal dec_buf, *dec_val= item->val_decimal_result(&dec_buf); if (maybe_null) { if (item->null_value) { memset(to, 0, sort_field->length+1); to++; break; } *to++=1; } my_decimal2binary(E_DEC_FATAL_ERROR, dec_val, to, item->max_length - (item->decimals ? 1:0), item->decimals); break; } case REAL_RESULT: { double value= item->val_result(); if (maybe_null) { if (item->null_value) { memset(to, 0, sort_field->length+1); to++; break; } *to++=1; } change_double_for_sort(value,(uchar*) to); break; } case ROW_RESULT: default: // This case should never be choosen DBUG_ASSERT(0); break; } } if (sort_field->reverse) { /* Revers key */ if (maybe_null && (to[-1]= !to[-1])) { to+= sort_field->length; // don't waste the time reversing all 0's continue; } length=sort_field->length; while (length--) { *to = (uchar) (~ *to); to++; } } else to+= sort_field->length; } if (param->addon_field) { /* Save field values appended to sorted fields. First null bit indicators are appended then field values follow. In this implementation we use fixed layout for field values - the same for all records. */ SORT_ADDON_FIELD *addonf= param->addon_field; uchar *nulls= to; DBUG_ASSERT(addonf != 0); memset(nulls, 0, addonf->offset); to+= addonf->offset; for ( ; (field= addonf->field) ; addonf++) { if (addonf->null_bit && field->is_null()) { nulls[addonf->null_offset]|= addonf->null_bit; #ifdef HAVE_valgrind bzero(to, addonf->length); #endif } else { #ifdef HAVE_valgrind uchar *end= field->pack(to, field->ptr); uint length= (uint) ((to + addonf->length) - end); DBUG_ASSERT((int) length >= 0); if (length) bzero(end, length); #else (void) field->pack(to, field->ptr); #endif } to+= addonf->length; } } else { /* Save filepos last */ memcpy((uchar*) to, ref_pos, (size_t) param->ref_length); } return; } /* Register fields used by sorting in the sorted table's read set */ static void register_used_fields(Sort_param *param) { reg1 SORT_FIELD *sort_field; TABLE *table=param->sort_form; MY_BITMAP *bitmap= table->read_set; for (sort_field= param->local_sortorder ; sort_field != param->end ; sort_field++) { Field *field; if ((field= sort_field->field)) { if (field->table == table) { if (field->vcol_info) { Item *vcol_item= field->vcol_info->expr_item; vcol_item->walk(&Item::register_field_in_read_map, 1, (uchar *) 0); } bitmap_set_bit(bitmap, field->field_index); } } else { // Item sort_field->item->walk(&Item::register_field_in_read_map, 1, (uchar *) table); } } if (param->addon_field) { SORT_ADDON_FIELD *addonf= param->addon_field; Field *field; for ( ; (field= addonf->field) ; addonf++) bitmap_set_bit(bitmap, field->field_index); } else { /* Save filepos last */ table->prepare_for_position(); } } static bool save_index(Sort_param *param, uint count, Filesort_info *table_sort) { uint offset,res_length; uchar *to; DBUG_ENTER("save_index"); table_sort->sort_buffer(param, count); res_length= param->res_length; offset= param->rec_length-res_length; if (!(to= table_sort->record_pointers= (uchar*) my_malloc(res_length*count, MYF(MY_WME | MY_THREAD_SPECIFIC)))) DBUG_RETURN(1); /* purecov: inspected */ uchar **sort_keys= table_sort->get_sort_keys(); for (uchar **end= sort_keys+count ; sort_keys != end ; sort_keys++) { memcpy(to, *sort_keys+offset, res_length); to+= res_length; } DBUG_RETURN(0); } /** Test whether priority queue is worth using to get top elements of an ordered result set. If it is, then allocates buffer for required amount of records @param param Sort parameters. @param filesort_info Filesort information. @param table Table to sort. @param num_rows Estimate of number of rows in source record set. @param memory_available Memory available for sorting. DESCRIPTION Given a query like this: SELECT ... FROM t ORDER BY a1,...,an LIMIT max_rows; This function tests whether a priority queue should be used to keep the result. Necessary conditions are: - estimate that it is actually cheaper than merge-sort - enough memory to store the <max_rows> records. If we don't have space for <max_rows> records, but we *do* have space for <max_rows> keys, we may rewrite 'table' to sort with references to records instead of additional data. (again, based on estimates that it will actually be cheaper). @retval true - if it's ok to use PQ false - PQ will be slower than merge-sort, or there is not enough memory. */ bool check_if_pq_applicable(Sort_param *param, Filesort_info *filesort_info, TABLE *table, ha_rows num_rows, ulong memory_available) { DBUG_ENTER("check_if_pq_applicable"); /* How much Priority Queue sort is slower than qsort. Measurements (see unit test) indicate that PQ is roughly 3 times slower. */ const double PQ_slowness= 3.0; if (param->max_rows == HA_POS_ERROR) { DBUG_PRINT("info", ("No LIMIT")); DBUG_RETURN(false); } if (param->max_rows + 2 >= UINT_MAX) { DBUG_PRINT("info", ("Too large LIMIT")); DBUG_RETURN(false); } ulong num_available_keys= memory_available / (param->rec_length + sizeof(char*)); // We need 1 extra record in the buffer, when using PQ. param->max_keys_per_buffer= (uint) param->max_rows + 1; if (num_rows < num_available_keys) { // The whole source set fits into memory. if (param->max_rows < num_rows/PQ_slowness ) { filesort_info->alloc_sort_buffer(param->max_keys_per_buffer, param->rec_length); DBUG_RETURN(filesort_info->get_sort_keys() != NULL); } else { // PQ will be slower. DBUG_RETURN(false); } } // Do we have space for LIMIT rows in memory? if (param->max_keys_per_buffer < num_available_keys) { filesort_info->alloc_sort_buffer(param->max_keys_per_buffer, param->rec_length); DBUG_RETURN(filesort_info->get_sort_keys() != NULL); } // Try to strip off addon fields. if (param->addon_field) { const ulong row_length= param->sort_length + param->ref_length + sizeof(char*); num_available_keys= memory_available / row_length; // Can we fit all the keys in memory? if (param->max_keys_per_buffer < num_available_keys) { const double sort_merge_cost= get_merge_many_buffs_cost_fast(num_rows, num_available_keys, row_length); /* PQ has cost: (insert + qsort) * log(queue size) / TIME_FOR_COMPARE_ROWID + cost of file lookup afterwards. The lookup cost is a bit pessimistic: we take scan_time and assume that on average we find the row after scanning half of the file. A better estimate would be lookup cost, but note that we are doing random lookups here, rather than sequential scan. */ const double pq_cpu_cost= (PQ_slowness * num_rows + param->max_keys_per_buffer) * log((double) param->max_keys_per_buffer) / TIME_FOR_COMPARE_ROWID; const double pq_io_cost= param->max_rows * table->file->scan_time() / 2.0; const double pq_cost= pq_cpu_cost + pq_io_cost; if (sort_merge_cost < pq_cost) DBUG_RETURN(false); filesort_info->alloc_sort_buffer(param->max_keys_per_buffer, param->sort_length + param->ref_length); if (filesort_info->get_sort_keys()) { // Make attached data to be references instead of fields. my_free(filesort_info->addon_buf); my_free(filesort_info->addon_field); filesort_info->addon_buf= NULL; filesort_info->addon_field= NULL; param->addon_field= NULL; param->addon_length= 0; param->res_length= param->ref_length; param->sort_length+= param->ref_length; param->rec_length= param->sort_length; DBUG_RETURN(true); } } } DBUG_RETURN(false); } /** Merge buffers to make < MERGEBUFF2 buffers. */ int merge_many_buff(Sort_param *param, uchar *sort_buffer, BUFFPEK *buffpek, uint *maxbuffer, IO_CACHE *t_file) { register uint i; IO_CACHE t_file2,*from_file,*to_file,*temp; BUFFPEK *lastbuff; DBUG_ENTER("merge_many_buff"); if (*maxbuffer < MERGEBUFF2) DBUG_RETURN(0); /* purecov: inspected */ if (flush_io_cache(t_file) || open_cached_file(&t_file2,mysql_tmpdir,TEMP_PREFIX,DISK_BUFFER_SIZE, MYF(MY_WME))) DBUG_RETURN(1); /* purecov: inspected */ from_file= t_file ; to_file= &t_file2; while (*maxbuffer >= MERGEBUFF2) { if (reinit_io_cache(from_file,READ_CACHE,0L,0,0)) goto cleanup; if (reinit_io_cache(to_file,WRITE_CACHE,0L,0,0)) goto cleanup; lastbuff=buffpek; for (i=0 ; i <= *maxbuffer-MERGEBUFF*3/2 ; i+=MERGEBUFF) { if (merge_buffers(param,from_file,to_file,sort_buffer,lastbuff++, buffpek+i,buffpek+i+MERGEBUFF-1,0)) goto cleanup; } if (merge_buffers(param,from_file,to_file,sort_buffer,lastbuff++, buffpek+i,buffpek+ *maxbuffer,0)) break; /* purecov: inspected */ if (flush_io_cache(to_file)) break; /* purecov: inspected */ temp=from_file; from_file=to_file; to_file=temp; setup_io_cache(from_file); setup_io_cache(to_file); *maxbuffer= (uint) (lastbuff-buffpek)-1; } cleanup: close_cached_file(to_file); // This holds old result if (to_file == t_file) { *t_file=t_file2; // Copy result file setup_io_cache(t_file); } DBUG_RETURN(*maxbuffer >= MERGEBUFF2); /* Return 1 if interrupted */ } /* merge_many_buff */ /** Read data to buffer. @retval (uint)-1 if something goes wrong */ uint read_to_buffer(IO_CACHE *fromfile, BUFFPEK *buffpek, uint rec_length) { register uint count; uint length; if ((count=(uint) MY_MIN((ha_rows) buffpek->max_keys,buffpek->count))) { if (mysql_file_pread(fromfile->file, (uchar*) buffpek->base, (length= rec_length*count), buffpek->file_pos, MYF_RW)) return((uint) -1); /* purecov: inspected */ buffpek->key=buffpek->base; buffpek->file_pos+= length; /* New filepos */ buffpek->count-= count; buffpek->mem_count= count; } return (count*rec_length); } /* read_to_buffer */ /** Put all room used by freed buffer to use in adjacent buffer. Note, that we can't simply distribute memory evenly between all buffers, because new areas must not overlap with old ones. @param[in] queue list of non-empty buffers, without freed buffer @param[in] reuse empty buffer @param[in] key_length key length */ void reuse_freed_buff(QUEUE *queue, BUFFPEK *reuse, uint key_length) { uchar *reuse_end= reuse->base + reuse->max_keys * key_length; for (uint i= queue_first_element(queue); i <= queue_last_element(queue); i++) { BUFFPEK *bp= (BUFFPEK *) queue_element(queue, i); if (bp->base + bp->max_keys * key_length == reuse->base) { bp->max_keys+= reuse->max_keys; return; } else if (bp->base == reuse_end) { bp->base= reuse->base; bp->max_keys+= reuse->max_keys; return; } } DBUG_ASSERT(0); } /** Merge buffers to one buffer. @param param Sort parameter @param from_file File with source data (BUFFPEKs point to this file) @param to_file File to write the sorted result data. @param sort_buffer Buffer for data to store up to MERGEBUFF2 sort keys. @param lastbuff OUT Store here BUFFPEK describing data written to to_file @param Fb First element in source BUFFPEKs array @param Tb Last element in source BUFFPEKs array @param flag @retval 0 OK @retval other error */ int merge_buffers(Sort_param *param, IO_CACHE *from_file, IO_CACHE *to_file, uchar *sort_buffer, BUFFPEK *lastbuff, BUFFPEK *Fb, BUFFPEK *Tb, int flag) { int error; uint rec_length,res_length,offset; size_t sort_length; ulong maxcount; ha_rows max_rows,org_max_rows; my_off_t to_start_filepos; uchar *strpos; BUFFPEK *buffpek; QUEUE queue; qsort2_cmp cmp; void *first_cmp_arg; element_count dupl_count= 0; uchar *src; uchar *unique_buff= param->unique_buff; const bool killable= !param->not_killable; THD* const thd=current_thd; DBUG_ENTER("merge_buffers"); thd->inc_status_sort_merge_passes(); thd->query_plan_fsort_passes++; error=0; rec_length= param->rec_length; res_length= param->res_length; sort_length= param->sort_length; uint dupl_count_ofs= rec_length-sizeof(element_count); uint min_dupl_count= param->min_dupl_count; bool check_dupl_count= flag && min_dupl_count; offset= (rec_length- (flag && min_dupl_count ? sizeof(dupl_count) : 0)-res_length); uint wr_len= flag ? res_length : rec_length; uint wr_offset= flag ? offset : 0; maxcount= (ulong) (param->max_keys_per_buffer/((uint) (Tb-Fb) +1)); to_start_filepos= my_b_tell(to_file); strpos= sort_buffer; org_max_rows=max_rows= param->max_rows; set_if_bigger(maxcount, 1); if (unique_buff) { cmp= param->compare; first_cmp_arg= (void *) &param->cmp_context; } else { cmp= get_ptr_compare(sort_length); first_cmp_arg= (void*) &sort_length; } if (init_queue(&queue, (uint) (Tb-Fb)+1, offsetof(BUFFPEK,key), 0, (queue_compare) cmp, first_cmp_arg, 0, 0)) DBUG_RETURN(1); /* purecov: inspected */ for (buffpek= Fb ; buffpek <= Tb ; buffpek++) { buffpek->base= strpos; buffpek->max_keys= maxcount; strpos+= (uint) (error= (int) read_to_buffer(from_file, buffpek, rec_length)); if (error == -1) goto err; /* purecov: inspected */ buffpek->max_keys= buffpek->mem_count; // If less data in buffers than expected queue_insert(&queue, (uchar*) buffpek); } if (unique_buff) { /* Called by Unique::get() Copy the first argument to unique_buff for unique removal. Store it also in 'to_file'. */ buffpek= (BUFFPEK*) queue_top(&queue); memcpy(unique_buff, buffpek->key, rec_length); if (min_dupl_count) memcpy(&dupl_count, unique_buff+dupl_count_ofs, sizeof(dupl_count)); buffpek->key+= rec_length; if (! --buffpek->mem_count) { if (!(error= (int) read_to_buffer(from_file, buffpek, rec_length))) { queue_remove(&queue,0); reuse_freed_buff(&queue, buffpek, rec_length); } else if (error == -1) goto err; /* purecov: inspected */ } queue_replace_top(&queue); // Top element has been used } else cmp= 0; // Not unique while (queue.elements > 1) { if (killable && thd->check_killed()) { error= 1; goto err; /* purecov: inspected */ } for (;;) { buffpek= (BUFFPEK*) queue_top(&queue); src= buffpek->key; if (cmp) // Remove duplicates { if (!(*cmp)(first_cmp_arg, &unique_buff, (uchar**) &buffpek->key)) { if (min_dupl_count) { element_count cnt; memcpy(&cnt, (uchar *) buffpek->key+dupl_count_ofs, sizeof(cnt)); dupl_count+= cnt; } goto skip_duplicate; } if (min_dupl_count) { memcpy(unique_buff+dupl_count_ofs, &dupl_count, sizeof(dupl_count)); } src= unique_buff; } /* Do not write into the output file if this is the final merge called for a Unique object used for intersection and dupl_count is less than min_dupl_count. If the Unique object is used to intersect N sets of unique elements then for any element: dupl_count >= N <=> the element is occurred in each of these N sets. */ if (!check_dupl_count || dupl_count >= min_dupl_count) { if (my_b_write(to_file, src+wr_offset, wr_len)) { error=1; goto err; /* purecov: inspected */ } } if (cmp) { memcpy(unique_buff, (uchar*) buffpek->key, rec_length); if (min_dupl_count) memcpy(&dupl_count, unique_buff+dupl_count_ofs, sizeof(dupl_count)); } if (!--max_rows) { error= 0; /* purecov: inspected */ goto end; /* purecov: inspected */ } skip_duplicate: buffpek->key+= rec_length; if (! --buffpek->mem_count) { if (!(error= (int) read_to_buffer(from_file, buffpek, rec_length))) { (void) queue_remove_top(&queue); reuse_freed_buff(&queue, buffpek, rec_length); break; /* One buffer have been removed */ } else if (error == -1) goto err; /* purecov: inspected */ } queue_replace_top(&queue); /* Top element has been replaced */ } } buffpek= (BUFFPEK*) queue_top(&queue); buffpek->base= (uchar*) sort_buffer; buffpek->max_keys= param->max_keys_per_buffer; /* As we know all entries in the buffer are unique, we only have to check if the first one is the same as the last one we wrote */ if (cmp) { if (!(*cmp)(first_cmp_arg, &unique_buff, (uchar**) &buffpek->key)) { if (min_dupl_count) { element_count cnt; memcpy(&cnt, (uchar *) buffpek->key+dupl_count_ofs, sizeof(cnt)); dupl_count+= cnt; } buffpek->key+= rec_length; --buffpek->mem_count; } if (min_dupl_count) memcpy(unique_buff+dupl_count_ofs, &dupl_count, sizeof(dupl_count)); if (!check_dupl_count || dupl_count >= min_dupl_count) { src= unique_buff; if (my_b_write(to_file, src+wr_offset, wr_len)) { error=1; goto err; /* purecov: inspected */ } if (!--max_rows) { error= 0; goto end; } } } do { if ((ha_rows) buffpek->mem_count > max_rows) { /* Don't write too many records */ buffpek->mem_count= (uint) max_rows; buffpek->count= 0; /* Don't read more */ } max_rows-= buffpek->mem_count; if (flag == 0) { if (my_b_write(to_file, (uchar*) buffpek->key, (rec_length*buffpek->mem_count))) { error= 1; goto err; /* purecov: inspected */ } } else { register uchar *end; src= buffpek->key+offset; for (end= src+buffpek->mem_count*rec_length ; src != end ; src+= rec_length) { if (check_dupl_count) { memcpy((uchar *) &dupl_count, src+dupl_count_ofs, sizeof(dupl_count)); if (dupl_count < min_dupl_count) continue; } if (my_b_write(to_file, src, wr_len)) { error=1; goto err; } } } } while ((error=(int) read_to_buffer(from_file, buffpek, rec_length)) != -1 && error != 0); end: lastbuff->count= MY_MIN(org_max_rows-max_rows, param->max_rows); lastbuff->file_pos= to_start_filepos; err: delete_queue(&queue); DBUG_RETURN(error); } /* merge_buffers */ /* Do a merge to output-file (save only positions) */ int merge_index(Sort_param *param, uchar *sort_buffer, BUFFPEK *buffpek, uint maxbuffer, IO_CACHE *tempfile, IO_CACHE *outfile) { DBUG_ENTER("merge_index"); if (merge_buffers(param,tempfile,outfile,sort_buffer,buffpek,buffpek, buffpek+maxbuffer,1)) DBUG_RETURN(1); /* purecov: inspected */ DBUG_RETURN(0); } /* merge_index */ static uint suffix_length(ulong string_length) { if (string_length < 256) return 1; if (string_length < 256L*256L) return 2; if (string_length < 256L*256L*256L) return 3; return 4; // Can't sort longer than 4G } /** Calculate length of sort key. @param thd Thread handler @param sortorder Order of items to sort @param s_length Number of items to sort @param[out] multi_byte_charset Set to 1 if we are using multi-byte charset (In which case we have to use strxnfrm()) @note sortorder->length is updated for each sort item. @n sortorder->need_strxnfrm is set 1 if we have to use strxnfrm @return Total length of sort buffer in bytes */ static uint sortlength(THD *thd, SORT_FIELD *sortorder, uint s_length, bool *multi_byte_charset) { reg2 uint length; const CHARSET_INFO *cs; *multi_byte_charset= 0; length=0; for (; s_length-- ; sortorder++) { sortorder->need_strxnfrm= 0; sortorder->suffix_length= 0; if (sortorder->field) { cs= sortorder->field->sort_charset(); sortorder->length= sortorder->field->sort_length(); if (use_strnxfrm((cs=sortorder->field->sort_charset()))) { sortorder->need_strxnfrm= 1; *multi_byte_charset= 1; sortorder->length= cs->coll->strnxfrmlen(cs, sortorder->length); } if (sortorder->field->maybe_null()) length++; // Place for NULL marker } else { sortorder->result_type= sortorder->item->cmp_type(); switch (sortorder->result_type) { case STRING_RESULT: sortorder->length=sortorder->item->max_length; set_if_smaller(sortorder->length, thd->variables.max_sort_length); if (use_strnxfrm((cs=sortorder->item->collation.collation))) { sortorder->length= cs->coll->strnxfrmlen(cs, sortorder->length); sortorder->need_strxnfrm= 1; *multi_byte_charset= 1; } else if (cs == &my_charset_bin) { /* Store length last to be able to sort blob/varbinary */ sortorder->suffix_length= suffix_length(sortorder->length); sortorder->length+= sortorder->suffix_length; } break; case TIME_RESULT: case INT_RESULT: sortorder->length=8; // Size of intern longlong break; case DECIMAL_RESULT: sortorder->length= my_decimal_get_binary_size(sortorder->item->max_length - (sortorder->item->decimals ? 1 : 0), sortorder->item->decimals); break; case REAL_RESULT: sortorder->length=sizeof(double); break; case ROW_RESULT: default: // This case should never be choosen DBUG_ASSERT(0); break; } if (sortorder->item->maybe_null) length++; // Place for NULL marker } set_if_smaller(sortorder->length, thd->variables.max_sort_length); length+=sortorder->length; } sortorder->field= (Field*) 0; // end marker DBUG_PRINT("info",("sort_length: %d",length)); return length; } /** Get descriptors of fields appended to sorted fields and calculate its total length. The function first finds out what fields are used in the result set. Then it calculates the length of the buffer to store the values of these fields together with the value of sort values. If the calculated length is not greater than max_length_for_sort_data the function allocates memory for an array of descriptors containing layouts for the values of the non-sorted fields in the buffer and fills them. @param thd Current thread @param ptabfield Array of references to the table fields @param sortlength Total length of sorted fields @param[out] plength Total length of appended fields @note The null bits for the appended values are supposed to be put together and stored the buffer just ahead of the value of the first field. @return Pointer to the layout descriptors for the appended fields, if any @retval NULL if we do not store field values with sort data. */ static SORT_ADDON_FIELD * get_addon_fields(ulong max_length_for_sort_data, Field **ptabfield, uint sortlength, uint *plength) { Field **pfield; Field *field; SORT_ADDON_FIELD *addonf; uint length= 0; uint fields= 0; uint null_fields= 0; MY_BITMAP *read_set= (*ptabfield)->table->read_set; /* If there is a reference to a field in the query add it to the the set of appended fields. Note for future refinement: This this a too strong condition. Actually we need only the fields referred in the result set. And for some of them it makes sense to use the values directly from sorted fields. But beware the case when item->cmp_type() != item->result_type() */ *plength= 0; for (pfield= ptabfield; (field= *pfield) ; pfield++) { if (!bitmap_is_set(read_set, field->field_index)) continue; if (field->flags & BLOB_FLAG) return 0; length+= field->max_packed_col_length(field->pack_length()); if (field->maybe_null()) null_fields++; fields++; } if (!fields) return 0; length+= (null_fields+7)/8; if (length+sortlength > max_length_for_sort_data || !(addonf= (SORT_ADDON_FIELD *) my_malloc(sizeof(SORT_ADDON_FIELD)* (fields+1), MYF(MY_WME | MY_THREAD_SPECIFIC)))) return 0; *plength= length; length= (null_fields+7)/8; null_fields= 0; for (pfield= ptabfield; (field= *pfield) ; pfield++) { if (!bitmap_is_set(read_set, field->field_index)) continue; addonf->field= field; addonf->offset= length; if (field->maybe_null()) { addonf->null_offset= null_fields/8; addonf->null_bit= 1<<(null_fields & 7); null_fields++; } else { addonf->null_offset= 0; addonf->null_bit= 0; } addonf->length= field->max_packed_col_length(field->pack_length()); length+= addonf->length; addonf++; } addonf->field= 0; // Put end marker DBUG_PRINT("info",("addon_length: %d",length)); return (addonf-fields); } /** Copy (unpack) values appended to sorted fields from a buffer back to their regular positions specified by the Field::ptr pointers. @param addon_field Array of descriptors for appended fields @param buff Buffer which to unpack the value from @note The function is supposed to be used only as a callback function when getting field values for the sorted result set. @return void. */ static void unpack_addon_fields(struct st_sort_addon_field *addon_field, uchar *buff, uchar *buff_end) { Field *field; SORT_ADDON_FIELD *addonf= addon_field; for ( ; (field= addonf->field) ; addonf++) { if (addonf->null_bit && (addonf->null_bit & buff[addonf->null_offset])) { field->set_null(); continue; } field->set_notnull(); field->unpack(field->ptr, buff + addonf->offset, buff_end, 0); } } /* ** functions to change a double or float to a sortable string ** The following should work for IEEE */ #define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG) void change_double_for_sort(double nr,uchar *to) { uchar *tmp=(uchar*) to; if (nr == 0.0) { /* Change to zero string */ tmp[0]=(uchar) 128; memset(tmp+1, 0, sizeof(nr)-1); } else { #ifdef WORDS_BIGENDIAN memcpy(tmp, &nr, sizeof(nr)); #else { uchar *ptr= (uchar*) &nr; #if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0]; tmp[4]= ptr[7]; tmp[5]=ptr[6]; tmp[6]= ptr[5]; tmp[7]=ptr[4]; #else tmp[0]= ptr[7]; tmp[1]=ptr[6]; tmp[2]= ptr[5]; tmp[3]=ptr[4]; tmp[4]= ptr[3]; tmp[5]=ptr[2]; tmp[6]= ptr[1]; tmp[7]=ptr[0]; #endif } #endif if (tmp[0] & 128) /* Negative */ { /* make complement */ uint i; for (i=0 ; i < sizeof(nr); i++) tmp[i]=tmp[i] ^ (uchar) 255; } else { /* Set high and move exponent one up */ ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] | (ushort) 32768); exp_part+= (ushort) 1 << (16-1-DBL_EXP_DIG); tmp[0]= (uchar) (exp_part >> 8); tmp[1]= (uchar) exp_part; } } } MDEV-5674 Valgrind warnings "Conditional jump or move depends on uninitialised value" in create_sort_index with small sort_buffer_size *found_rows wasn't initialized when filesort() failed (it didn't matter, but valgrind was unhappy) /* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2009, 2012, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /** @file @brief Sorts a database */ #include "sql_priv.h" #include "filesort.h" #include "unireg.h" // REQUIRED by other includes #ifdef HAVE_STDDEF_H #include <stddef.h> /* for macro offsetof */ #endif #include <m_ctype.h> #include "sql_sort.h" #include "probes_mysql.h" #include "sql_base.h" // update_virtual_fields #include "sql_test.h" // TEST_filesort #include "opt_range.h" // SQL_SELECT #include "bounded_queue.h" #include "filesort_utils.h" #include "sql_select.h" #include "log_slow.h" #include "debug_sync.h" #include "sql_base.h" /// How to write record_ref. #define WRITE_REF(file,from) \ if (my_b_write((file),(uchar*) (from),param->ref_length)) \ DBUG_RETURN(1); /* functions defined in this file */ static uchar *read_buffpek_from_file(IO_CACHE *buffer_file, uint count, uchar *buf); static ha_rows find_all_keys(Sort_param *param,SQL_SELECT *select, Filesort_info *fs_info, IO_CACHE *buffer_file, IO_CACHE *tempfile, Bounded_queue<uchar, uchar> *pq, ha_rows *found_rows); static bool write_keys(Sort_param *param, Filesort_info *fs_info, uint count, IO_CACHE *buffer_file, IO_CACHE *tempfile); static void make_sortkey(Sort_param *param, uchar *to, uchar *ref_pos); static void register_used_fields(Sort_param *param); static bool save_index(Sort_param *param, uint count, Filesort_info *table_sort); static uint suffix_length(ulong string_length); static uint sortlength(THD *thd, SORT_FIELD *sortorder, uint s_length, bool *multi_byte_charset); static SORT_ADDON_FIELD *get_addon_fields(ulong max_length_for_sort_data, Field **ptabfield, uint sortlength, uint *plength); static void unpack_addon_fields(struct st_sort_addon_field *addon_field, uchar *buff, uchar *buff_end); static bool check_if_pq_applicable(Sort_param *param, Filesort_info *info, TABLE *table, ha_rows records, ulong memory_available); void Sort_param::init_for_filesort(uint sortlen, TABLE *table, ulong max_length_for_sort_data, ha_rows maxrows, bool sort_positions) { sort_length= sortlen; ref_length= table->file->ref_length; if (!(table->file->ha_table_flags() & HA_FAST_KEY_READ) && !table->fulltext_searched && !sort_positions) { /* Get the descriptors of all fields whose values are appended to sorted fields and get its total length in addon_length. */ addon_field= get_addon_fields(max_length_for_sort_data, table->field, sort_length, &addon_length); } if (addon_field) res_length= addon_length; else { res_length= ref_length; /* The reference to the record is considered as an additional sorted field */ sort_length+= ref_length; } rec_length= sort_length + addon_length; max_rows= maxrows; } /** Sort a table. Creates a set of pointers that can be used to read the rows in sorted order. This should be done with the functions in records.cc. Before calling filesort, one must have done table->file->info(HA_STATUS_VARIABLE) The result set is stored in table->io_cache or table->record_pointers. @param thd Current thread @param table Table to sort @param sortorder How to sort the table @param s_length Number of elements in sortorder @param select Condition to apply to the rows @param max_rows Return only this many rows @param sort_positions Set to TRUE if we want to force sorting by position (Needed by UPDATE/INSERT or ALTER TABLE or when rowids are required by executor) @param[out] examined_rows Store number of examined rows here @param[out] found_rows Store the number of found rows here @note If we sort by position (like if sort_positions is 1) filesort() will call table->prepare_for_position(). @retval HA_POS_ERROR Error @retval \# Number of rows */ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length, SQL_SELECT *select, ha_rows max_rows, bool sort_positions, ha_rows *examined_rows, ha_rows *found_rows) { int error; size_t memory_available= thd->variables.sortbuff_size; uint maxbuffer; BUFFPEK *buffpek; ha_rows num_rows= HA_POS_ERROR; IO_CACHE tempfile, buffpek_pointers, *outfile; Sort_param param; bool multi_byte_charset; Bounded_queue<uchar, uchar> pq; DBUG_ENTER("filesort"); DBUG_EXECUTE("info",TEST_filesort(sortorder,s_length);); #ifdef SKIP_DBUG_IN_FILESORT DBUG_PUSH(""); /* No DBUG here */ #endif Filesort_info table_sort= table->sort; TABLE_LIST *tab= table->pos_in_table_list; Item_subselect *subselect= tab ? tab->containing_subselect() : 0; MYSQL_FILESORT_START(table->s->db.str, table->s->table_name.str); DEBUG_SYNC(thd, "filesort_start"); /* Release InnoDB's adaptive hash index latch (if holding) before running a sort. */ ha_release_temporary_latches(thd); /* Don't use table->sort in filesort as it is also used by QUICK_INDEX_MERGE_SELECT. Work with a copy and put it back at the end when index_merge select has finished with it. */ table->sort.io_cache= NULL; DBUG_ASSERT(table_sort.record_pointers == NULL); outfile= table_sort.io_cache; my_b_clear(&tempfile); my_b_clear(&buffpek_pointers); buffpek=0; error= 1; *found_rows= HA_POS_ERROR; param.init_for_filesort(sortlength(thd, sortorder, s_length, &multi_byte_charset), table, thd->variables.max_length_for_sort_data, max_rows, sort_positions); table_sort.addon_buf= 0; table_sort.addon_length= param.addon_length; table_sort.addon_field= param.addon_field; table_sort.unpack= unpack_addon_fields; if (param.addon_field && !(table_sort.addon_buf= (uchar *) my_malloc(param.addon_length, MYF(MY_WME | MY_THREAD_SPECIFIC)))) goto err; if (select && select->quick) thd->inc_status_sort_range(); else thd->inc_status_sort_scan(); thd->query_plan_flags|= QPLAN_FILESORT; // If number of rows is not known, use as much of sort buffer as possible. num_rows= table->file->estimate_rows_upper_bound(); if (multi_byte_charset && !(param.tmp_buffer= (char*) my_malloc(param.sort_length, MYF(MY_WME | MY_THREAD_SPECIFIC)))) goto err; if (check_if_pq_applicable(&param, &table_sort, table, num_rows, memory_available)) { DBUG_PRINT("info", ("filesort PQ is applicable")); const size_t compare_length= param.sort_length; if (pq.init(param.max_rows, true, // max_at_top NULL, // compare_function compare_length, &make_sortkey, &param, table_sort.get_sort_keys())) { /* If we fail to init pq, we have to give up: out of memory means my_malloc() will call my_error(). */ DBUG_PRINT("info", ("failed to allocate PQ")); table_sort.free_sort_buffer(); DBUG_ASSERT(thd->is_error()); goto err; } // For PQ queries (with limit) we initialize all pointers. table_sort.init_record_pointers(); } else { DBUG_PRINT("info", ("filesort PQ is not applicable")); size_t min_sort_memory= MY_MAX(MIN_SORT_MEMORY, param.sort_length*MERGEBUFF2); set_if_bigger(min_sort_memory, sizeof(BUFFPEK*)*MERGEBUFF2); while (memory_available >= min_sort_memory) { ulonglong keys= memory_available / (param.rec_length + sizeof(char*)); param.max_keys_per_buffer= (uint) MY_MIN(num_rows, keys); if (table_sort.get_sort_keys()) { // If we have already allocated a buffer, it better have same size! if (!table_sort.check_sort_buffer_properties(param.max_keys_per_buffer, param.rec_length)) { /* table->sort will still have a pointer to the same buffer, but that will be overwritten by the assignment below. */ table_sort.free_sort_buffer(); } } table_sort.alloc_sort_buffer(param.max_keys_per_buffer, param.rec_length); if (table_sort.get_sort_keys()) break; size_t old_memory_available= memory_available; memory_available= memory_available/4*3; if (memory_available < min_sort_memory && old_memory_available > min_sort_memory) memory_available= min_sort_memory; } if (memory_available < min_sort_memory) { my_error(ER_OUT_OF_SORTMEMORY,MYF(ME_ERROR + ME_FATALERROR)); goto err; } } if (open_cached_file(&buffpek_pointers,mysql_tmpdir,TEMP_PREFIX, DISK_BUFFER_SIZE, MYF(MY_WME))) goto err; param.sort_form= table; param.end=(param.local_sortorder=sortorder)+s_length; num_rows= find_all_keys(&param, select, &table_sort, &buffpek_pointers, &tempfile, pq.is_initialized() ? &pq : NULL, found_rows); if (num_rows == HA_POS_ERROR) goto err; maxbuffer= (uint) (my_b_tell(&buffpek_pointers)/sizeof(*buffpek)); if (maxbuffer == 0) // The whole set is in memory { if (save_index(&param, (uint) num_rows, &table_sort)) goto err; } else { /* filesort cannot handle zero-length records during merge. */ DBUG_ASSERT(param.sort_length != 0); if (table_sort.buffpek && table_sort.buffpek_len < maxbuffer) { my_free(table_sort.buffpek); table_sort.buffpek= 0; } if (!(table_sort.buffpek= (uchar *) read_buffpek_from_file(&buffpek_pointers, maxbuffer, table_sort.buffpek))) goto err; buffpek= (BUFFPEK *) table_sort.buffpek; table_sort.buffpek_len= maxbuffer; close_cached_file(&buffpek_pointers); /* Open cached file if it isn't open */ if (! my_b_inited(outfile) && open_cached_file(outfile,mysql_tmpdir,TEMP_PREFIX,READ_RECORD_BUFFER, MYF(MY_WME))) goto err; if (reinit_io_cache(outfile,WRITE_CACHE,0L,0,0)) goto err; /* Use also the space previously used by string pointers in sort_buffer for temporary key storage. */ param.max_keys_per_buffer=((param.max_keys_per_buffer * (param.rec_length + sizeof(char*))) / param.rec_length - 1); maxbuffer--; // Offset from 0 if (merge_many_buff(&param, (uchar*) table_sort.get_sort_keys(), buffpek,&maxbuffer, &tempfile)) goto err; if (flush_io_cache(&tempfile) || reinit_io_cache(&tempfile,READ_CACHE,0L,0,0)) goto err; if (merge_index(&param, (uchar*) table_sort.get_sort_keys(), buffpek, maxbuffer, &tempfile, outfile)) goto err; } if (num_rows > param.max_rows) { // If find_all_keys() produced more results than the query LIMIT. num_rows= param.max_rows; } error= 0; err: my_free(param.tmp_buffer); if (!subselect || !subselect->is_uncacheable()) { table_sort.free_sort_buffer(); my_free(buffpek); table_sort.buffpek= 0; table_sort.buffpek_len= 0; } close_cached_file(&tempfile); close_cached_file(&buffpek_pointers); if (my_b_inited(outfile)) { if (flush_io_cache(outfile)) error=1; { my_off_t save_pos=outfile->pos_in_file; /* For following reads */ if (reinit_io_cache(outfile,READ_CACHE,0L,0,0)) error=1; outfile->end_of_file=save_pos; } } if (error) { int kill_errno= thd->killed_errno(); DBUG_ASSERT(thd->is_error() || kill_errno || thd->killed == ABORT_QUERY); /* We replace the table->sort at the end. Hence calling free_io_cache to make sure table->sort.io_cache used for QUICK_INDEX_MERGE_SELECT is free. */ free_io_cache(table); my_printf_error(ER_FILSORT_ABORT, "%s: %s", MYF(0), ER_THD(thd, ER_FILSORT_ABORT), kill_errno ? ER(kill_errno) : thd->killed == ABORT_QUERY ? "" : thd->get_stmt_da()->message()); if (global_system_variables.log_warnings > 1) { sql_print_warning("%s, host: %s, user: %s, thread: %lu, query: %-.4096s", ER_THD(thd, ER_FILSORT_ABORT), thd->security_ctx->host_or_ip, &thd->security_ctx->priv_user[0], (ulong) thd->thread_id, thd->query()); } } else thd->inc_status_sort_rows(num_rows); *examined_rows= param.examined_rows; #ifdef SKIP_DBUG_IN_FILESORT DBUG_POP(); /* Ok to DBUG */ #endif /* table->sort.io_cache should be free by this time */ DBUG_ASSERT(NULL == table->sort.io_cache); // Assign the copy back! table->sort= table_sort; DBUG_PRINT("exit", ("num_rows: %ld examined_rows: %ld found_rows: %ld", (long) num_rows, (long) *examined_rows, (long) *found_rows)); MYSQL_FILESORT_DONE(error, num_rows); DBUG_RETURN(error ? HA_POS_ERROR : num_rows); } /* filesort */ void filesort_free_buffers(TABLE *table, bool full) { DBUG_ENTER("filesort_free_buffers"); my_free(table->sort.record_pointers); table->sort.record_pointers= NULL; if (full) { table->sort.free_sort_buffer(); my_free(table->sort.buffpek); table->sort.buffpek= NULL; table->sort.buffpek_len= 0; } my_free(table->sort.addon_buf); my_free(table->sort.addon_field); table->sort.addon_buf= NULL; table->sort.addon_field= NULL; DBUG_VOID_RETURN; } /** Read 'count' number of buffer pointers into memory. */ static uchar *read_buffpek_from_file(IO_CACHE *buffpek_pointers, uint count, uchar *buf) { size_t length= sizeof(BUFFPEK)*count; uchar *tmp= buf; DBUG_ENTER("read_buffpek_from_file"); if (count > UINT_MAX/sizeof(BUFFPEK)) return 0; /* sizeof(BUFFPEK)*count will overflow */ if (!tmp) tmp= (uchar *)my_malloc(length, MYF(MY_WME | MY_THREAD_SPECIFIC)); if (tmp) { if (reinit_io_cache(buffpek_pointers,READ_CACHE,0L,0,0) || my_b_read(buffpek_pointers, (uchar*) tmp, length)) { my_free(tmp); tmp=0; } } DBUG_RETURN(tmp); } #ifndef DBUG_OFF /* Buffer where record is returned */ char dbug_print_row_buff[512]; /* Temporary buffer for printing a column */ char dbug_print_row_buff_tmp[512]; /* Print table's current row into a buffer and return a pointer to it. This is intended to be used from gdb: (gdb) p dbug_print_table_row(table) $33 = "SUBQUERY2_t1(col_int_key,col_varchar_nokey)=(7,c)" (gdb) Only columns in table->read_set are printed */ const char* dbug_print_table_row(TABLE *table) { Field **pfield; String tmp(dbug_print_row_buff_tmp, sizeof(dbug_print_row_buff_tmp),&my_charset_bin); String output(dbug_print_row_buff, sizeof(dbug_print_row_buff), &my_charset_bin); output.length(0); output.append(table->alias); output.append("("); bool first= true; for (pfield= table->field; *pfield ; pfield++) { if (table->read_set && !bitmap_is_set(table->read_set, (*pfield)->field_index)) continue; if (first) first= false; else output.append(","); output.append((*pfield)->field_name? (*pfield)->field_name: "NULL"); } output.append(")=("); first= true; for (pfield= table->field; *pfield ; pfield++) { Field *field= *pfield; if (table->read_set && !bitmap_is_set(table->read_set, (*pfield)->field_index)) continue; if (first) first= false; else output.append(","); if (field->is_null()) output.append("NULL"); else { if (field->type() == MYSQL_TYPE_BIT) (void) field->val_int_as_str(&tmp, 1); else field->val_str(&tmp); output.append(tmp.ptr(), tmp.length()); } } output.append(")"); return output.c_ptr_safe(); } /* Print a text, SQL-like record representation into dbug trace. Note: this function is a work in progress: at the moment - column read bitmap is ignored (can print garbage for unused columns) - there is no quoting */ static void dbug_print_record(TABLE *table, bool print_rowid) { char buff[1024]; Field **pfield; String tmp(buff,sizeof(buff),&my_charset_bin); DBUG_LOCK_FILE; fprintf(DBUG_FILE, "record ("); for (pfield= table->field; *pfield ; pfield++) fprintf(DBUG_FILE, "%s%s", (*pfield)->field_name, (pfield[1])? ", ":""); fprintf(DBUG_FILE, ") = "); fprintf(DBUG_FILE, "("); for (pfield= table->field; *pfield ; pfield++) { Field *field= *pfield; if (field->is_null()) fwrite("NULL", sizeof(char), 4, DBUG_FILE); if (field->type() == MYSQL_TYPE_BIT) (void) field->val_int_as_str(&tmp, 1); else field->val_str(&tmp); fwrite(tmp.ptr(),sizeof(char),tmp.length(),DBUG_FILE); if (pfield[1]) fwrite(", ", sizeof(char), 2, DBUG_FILE); } fprintf(DBUG_FILE, ")"); if (print_rowid) { fprintf(DBUG_FILE, " rowid "); for (uint i=0; i < table->file->ref_length; i++) { fprintf(DBUG_FILE, "%x", (uchar)table->file->ref[i]); } } fprintf(DBUG_FILE, "\n"); DBUG_UNLOCK_FILE; } #endif /** Search after sort_keys, and write them into tempfile (if we run out of space in the sort_keys buffer). All produced sequences are guaranteed to be non-empty. @param param Sorting parameter @param select Use this to get source data @param sort_keys Array of pointers to sort key + addon buffers. @param buffpek_pointers File to write BUFFPEKs describing sorted segments in tempfile. @param tempfile File to write sorted sequences of sortkeys to. @param pq If !NULL, use it for keeping top N elements @param [out] found_rows The number of FOUND_ROWS(). For a query with LIMIT, this value will typically be larger than the function return value. @note Basic idea: @verbatim while (get_next_sortkey()) { if (using priority queue) push sort key into queue else { if (no free space in sort_keys buffers) { sort sort_keys buffer; dump sorted sequence to 'tempfile'; dump BUFFPEK describing sequence location into 'buffpek_pointers'; } put sort key into 'sort_keys'; } } if (sort_keys has some elements && dumped at least once) sort-dump-dump as above; else don't sort, leave sort_keys array to be sorted by caller. @endverbatim @retval Number of records written on success. @retval HA_POS_ERROR on error. */ static ha_rows find_all_keys(Sort_param *param, SQL_SELECT *select, Filesort_info *fs_info, IO_CACHE *buffpek_pointers, IO_CACHE *tempfile, Bounded_queue<uchar, uchar> *pq, ha_rows *found_rows) { int error,flag,quick_select; uint idx,indexpos,ref_length; uchar *ref_pos,*next_pos,ref_buff[MAX_REFLENGTH]; my_off_t record; TABLE *sort_form; THD *thd= current_thd; handler *file; MY_BITMAP *save_read_set, *save_write_set, *save_vcol_set; DBUG_ENTER("find_all_keys"); DBUG_PRINT("info",("using: %s", (select ? select->quick ? "ranges" : "where": "every row"))); idx=indexpos=0; error=quick_select=0; sort_form=param->sort_form; file=sort_form->file; ref_length=param->ref_length; ref_pos= ref_buff; quick_select=select && select->quick; record=0; *found_rows= pq ? 0 : HA_POS_ERROR; // don't count unless pq is used flag= ((file->ha_table_flags() & HA_REC_NOT_IN_SEQ) || quick_select); if (flag) ref_pos= &file->ref[0]; next_pos=ref_pos; DBUG_EXECUTE_IF("show_explain_in_find_all_keys", dbug_serve_apcs(thd, 1); ); if (!quick_select) { next_pos=(uchar*) 0; /* Find records in sequence */ DBUG_EXECUTE_IF("bug14365043_1", DBUG_SET("+d,ha_rnd_init_fail");); if (file->ha_rnd_init_with_error(1)) DBUG_RETURN(HA_POS_ERROR); file->extra_opt(HA_EXTRA_CACHE, current_thd->variables.read_buff_size); } /* Remember original bitmaps */ save_read_set= sort_form->read_set; save_write_set= sort_form->write_set; save_vcol_set= sort_form->vcol_set; /* Set up temporary column read map for columns used by sort */ bitmap_clear_all(&sort_form->tmp_set); /* Temporary set for register_used_fields and register_field_in_read_map */ sort_form->read_set= &sort_form->tmp_set; register_used_fields(param); Item *sort_cond= !select ? 0 : !select->pre_idx_push_select_cond ? select->cond : select->pre_idx_push_select_cond; if (sort_cond) sort_cond->walk(&Item::register_field_in_read_map, 1, (uchar*) sort_form); sort_form->column_bitmaps_set(&sort_form->tmp_set, &sort_form->tmp_set, &sort_form->tmp_set); if (quick_select) { if (select->quick->reset()) DBUG_RETURN(HA_POS_ERROR); } DEBUG_SYNC(thd, "after_index_merge_phase1"); for (;;) { if (quick_select) { if ((error= select->quick->get_next())) break; if (!error && sort_form->vfield) update_virtual_fields(thd, sort_form); file->position(sort_form->record[0]); DBUG_EXECUTE_IF("debug_filesort", dbug_print_record(sort_form, TRUE);); } else /* Not quick-select */ { { error= file->ha_rnd_next(sort_form->record[0]); if (!error && sort_form->vfield) update_virtual_fields(thd, sort_form); if (!flag) { my_store_ptr(ref_pos,ref_length,record); // Position to row record+= sort_form->s->db_record_offset; } else if (!error) file->position(sort_form->record[0]); } if (error && error != HA_ERR_RECORD_DELETED) break; } if (thd->check_killed()) { DBUG_PRINT("info",("Sort killed by user")); if (!quick_select) { (void) file->extra(HA_EXTRA_NO_CACHE); file->ha_rnd_end(); } DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */ } bool write_record= false; if (error == 0) { param->examined_rows++; if (select && select->cond) { /* If the condition 'select->cond' contains a subquery, restore the original read/write sets of the table 'sort_form' because when SQL_SELECT::skip_record evaluates this condition. it may include a correlated subquery predicate, such that some field in the subquery refers to 'sort_form'. PSergey-todo: discuss the above with Timour. */ MY_BITMAP *tmp_read_set= sort_form->read_set; MY_BITMAP *tmp_write_set= sort_form->write_set; MY_BITMAP *tmp_vcol_set= sort_form->vcol_set; if (select->cond->with_subselect) sort_form->column_bitmaps_set(save_read_set, save_write_set, save_vcol_set); write_record= (select->skip_record(thd) > 0); if (select->cond->with_subselect) sort_form->column_bitmaps_set(tmp_read_set, tmp_write_set, tmp_vcol_set); } else write_record= true; } if (write_record) { if (pq) { /* only count rows when pq is used - otherwise there might be other filters *after* the filesort, we don't know the final row count here */ (*found_rows)++; pq->push(ref_pos); idx= pq->num_elements(); } else { if (idx == param->max_keys_per_buffer) { if (write_keys(param, fs_info, idx, buffpek_pointers, tempfile)) DBUG_RETURN(HA_POS_ERROR); idx= 0; indexpos++; } make_sortkey(param, fs_info->get_record_buffer(idx++), ref_pos); } } /* It does not make sense to read more keys in case of a fatal error */ if (thd->is_error()) break; /* We need to this after checking the error as the transaction may have rolled back in case of a deadlock */ if (!write_record) file->unlock_row(); } if (!quick_select) { (void) file->extra(HA_EXTRA_NO_CACHE); /* End cacheing of records */ if (!next_pos) file->ha_rnd_end(); } if (thd->is_error()) DBUG_RETURN(HA_POS_ERROR); /* Signal we should use orignal column read and write maps */ sort_form->column_bitmaps_set(save_read_set, save_write_set, save_vcol_set); DBUG_PRINT("test",("error: %d indexpos: %d",error,indexpos)); if (error != HA_ERR_END_OF_FILE) { file->print_error(error,MYF(ME_ERROR | ME_WAITTANG)); // purecov: inspected DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */ } if (indexpos && idx && write_keys(param, fs_info, idx, buffpek_pointers, tempfile)) DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */ const ha_rows retval= my_b_inited(tempfile) ? (ha_rows) (my_b_tell(tempfile)/param->rec_length) : idx; DBUG_PRINT("info", ("find_all_keys return %u", (uint) retval)); DBUG_RETURN(retval); } /* find_all_keys */ /** @details Sort the buffer and write: -# the sorted sequence to tempfile -# a BUFFPEK describing the sorted sequence position to buffpek_pointers (was: Skriver en buffert med nycklar till filen) @param param Sort parameters @param sort_keys Array of pointers to keys to sort @param count Number of elements in sort_keys array @param buffpek_pointers One 'BUFFPEK' struct will be written into this file. The BUFFPEK::{file_pos, count} will indicate where the sorted data was stored. @param tempfile The sorted sequence will be written into this file. @retval 0 OK @retval 1 Error */ static bool write_keys(Sort_param *param, Filesort_info *fs_info, uint count, IO_CACHE *buffpek_pointers, IO_CACHE *tempfile) { size_t rec_length; uchar **end; BUFFPEK buffpek; DBUG_ENTER("write_keys"); rec_length= param->rec_length; uchar **sort_keys= fs_info->get_sort_keys(); fs_info->sort_buffer(param, count); if (!my_b_inited(tempfile) && open_cached_file(tempfile, mysql_tmpdir, TEMP_PREFIX, DISK_BUFFER_SIZE, MYF(MY_WME))) goto err; /* purecov: inspected */ /* check we won't have more buffpeks than we can possibly keep in memory */ if (my_b_tell(buffpek_pointers) + sizeof(BUFFPEK) > (ulonglong)UINT_MAX) goto err; buffpek.file_pos= my_b_tell(tempfile); if ((ha_rows) count > param->max_rows) count=(uint) param->max_rows; /* purecov: inspected */ buffpek.count=(ha_rows) count; for (end=sort_keys+count ; sort_keys != end ; sort_keys++) if (my_b_write(tempfile, (uchar*) *sort_keys, (uint) rec_length)) goto err; if (my_b_write(buffpek_pointers, (uchar*) &buffpek, sizeof(buffpek))) goto err; DBUG_RETURN(0); err: DBUG_RETURN(1); } /* write_keys */ /** Store length as suffix in high-byte-first order. */ static inline void store_length(uchar *to, uint length, uint pack_length) { switch (pack_length) { case 1: *to= (uchar) length; break; case 2: mi_int2store(to, length); break; case 3: mi_int3store(to, length); break; default: mi_int4store(to, length); break; } } /** Make a sort-key from record. */ static void make_sortkey(register Sort_param *param, register uchar *to, uchar *ref_pos) { reg3 Field *field; reg1 SORT_FIELD *sort_field; reg5 uint length; for (sort_field=param->local_sortorder ; sort_field != param->end ; sort_field++) { bool maybe_null=0; if ((field=sort_field->field)) { // Field field->make_sort_key(to, sort_field->length); if ((maybe_null = field->maybe_null())) to++; } else { // Item Item *item=sort_field->item; maybe_null= item->maybe_null; switch (sort_field->result_type) { case STRING_RESULT: { const CHARSET_INFO *cs=item->collation.collation; char fill_char= ((cs->state & MY_CS_BINSORT) ? (char) 0 : ' '); if (maybe_null) *to++=1; char *tmp_buffer= param->tmp_buffer ? param->tmp_buffer : (char*)to; String tmp(tmp_buffer, param->sort_length, cs); String *res= item->str_result(&tmp); if (!res) { if (maybe_null) memset(to-1, 0, sort_field->length+1); else { /* purecov: begin deadcode */ /* This should only happen during extreme conditions if we run out of memory or have an item marked not null when it can be null. This code is here mainly to avoid a hard crash in this case. */ DBUG_ASSERT(0); DBUG_PRINT("warning", ("Got null on something that shouldn't be null")); memset(to, 0, sort_field->length); // Avoid crash /* purecov: end */ } break; } length= res->length(); if (sort_field->need_strxnfrm) { uint tmp_length __attribute__((unused)); tmp_length= cs->coll->strnxfrm(cs, to, sort_field->length, item->max_char_length() * cs->strxfrm_multiply, (uchar*) res->ptr(), length, MY_STRXFRM_PAD_WITH_SPACE | MY_STRXFRM_PAD_TO_MAXLEN); DBUG_ASSERT(tmp_length == sort_field->length); } else { uint diff; uint sort_field_length= sort_field->length - sort_field->suffix_length; if (sort_field_length < length) { diff= 0; length= sort_field_length; } else diff= sort_field_length - length; if (sort_field->suffix_length) { /* Store length last in result_string */ store_length(to + sort_field_length, length, sort_field->suffix_length); } /* apply cs->sort_order for case-insensitive comparison if needed */ my_strnxfrm(cs,(uchar*)to,length,(const uchar*)res->ptr(),length); cs->cset->fill(cs, (char *)to+length,diff,fill_char); } break; } case INT_RESULT: case TIME_RESULT: { longlong UNINIT_VAR(value); if (sort_field->result_type == INT_RESULT) value= item->val_int_result(); else { MYSQL_TIME buf; if (item->get_date_result(&buf, TIME_INVALID_DATES)) { DBUG_ASSERT(maybe_null); DBUG_ASSERT(item->null_value); } else value= pack_time(&buf); } if (maybe_null) { *to++=1; /* purecov: inspected */ if (item->null_value) { if (maybe_null) memset(to-1, 0, sort_field->length+1); else { DBUG_PRINT("warning", ("Got null on something that shouldn't be null")); memset(to, 0, sort_field->length); } break; } } to[7]= (uchar) value; to[6]= (uchar) (value >> 8); to[5]= (uchar) (value >> 16); to[4]= (uchar) (value >> 24); to[3]= (uchar) (value >> 32); to[2]= (uchar) (value >> 40); to[1]= (uchar) (value >> 48); if (item->unsigned_flag) /* Fix sign */ to[0]= (uchar) (value >> 56); else to[0]= (uchar) (value >> 56) ^ 128; /* Reverse signbit */ break; } case DECIMAL_RESULT: { my_decimal dec_buf, *dec_val= item->val_decimal_result(&dec_buf); if (maybe_null) { if (item->null_value) { memset(to, 0, sort_field->length+1); to++; break; } *to++=1; } my_decimal2binary(E_DEC_FATAL_ERROR, dec_val, to, item->max_length - (item->decimals ? 1:0), item->decimals); break; } case REAL_RESULT: { double value= item->val_result(); if (maybe_null) { if (item->null_value) { memset(to, 0, sort_field->length+1); to++; break; } *to++=1; } change_double_for_sort(value,(uchar*) to); break; } case ROW_RESULT: default: // This case should never be choosen DBUG_ASSERT(0); break; } } if (sort_field->reverse) { /* Revers key */ if (maybe_null && (to[-1]= !to[-1])) { to+= sort_field->length; // don't waste the time reversing all 0's continue; } length=sort_field->length; while (length--) { *to = (uchar) (~ *to); to++; } } else to+= sort_field->length; } if (param->addon_field) { /* Save field values appended to sorted fields. First null bit indicators are appended then field values follow. In this implementation we use fixed layout for field values - the same for all records. */ SORT_ADDON_FIELD *addonf= param->addon_field; uchar *nulls= to; DBUG_ASSERT(addonf != 0); memset(nulls, 0, addonf->offset); to+= addonf->offset; for ( ; (field= addonf->field) ; addonf++) { if (addonf->null_bit && field->is_null()) { nulls[addonf->null_offset]|= addonf->null_bit; #ifdef HAVE_valgrind bzero(to, addonf->length); #endif } else { #ifdef HAVE_valgrind uchar *end= field->pack(to, field->ptr); uint length= (uint) ((to + addonf->length) - end); DBUG_ASSERT((int) length >= 0); if (length) bzero(end, length); #else (void) field->pack(to, field->ptr); #endif } to+= addonf->length; } } else { /* Save filepos last */ memcpy((uchar*) to, ref_pos, (size_t) param->ref_length); } return; } /* Register fields used by sorting in the sorted table's read set */ static void register_used_fields(Sort_param *param) { reg1 SORT_FIELD *sort_field; TABLE *table=param->sort_form; MY_BITMAP *bitmap= table->read_set; for (sort_field= param->local_sortorder ; sort_field != param->end ; sort_field++) { Field *field; if ((field= sort_field->field)) { if (field->table == table) { if (field->vcol_info) { Item *vcol_item= field->vcol_info->expr_item; vcol_item->walk(&Item::register_field_in_read_map, 1, (uchar *) 0); } bitmap_set_bit(bitmap, field->field_index); } } else { // Item sort_field->item->walk(&Item::register_field_in_read_map, 1, (uchar *) table); } } if (param->addon_field) { SORT_ADDON_FIELD *addonf= param->addon_field; Field *field; for ( ; (field= addonf->field) ; addonf++) bitmap_set_bit(bitmap, field->field_index); } else { /* Save filepos last */ table->prepare_for_position(); } } static bool save_index(Sort_param *param, uint count, Filesort_info *table_sort) { uint offset,res_length; uchar *to; DBUG_ENTER("save_index"); table_sort->sort_buffer(param, count); res_length= param->res_length; offset= param->rec_length-res_length; if (!(to= table_sort->record_pointers= (uchar*) my_malloc(res_length*count, MYF(MY_WME | MY_THREAD_SPECIFIC)))) DBUG_RETURN(1); /* purecov: inspected */ uchar **sort_keys= table_sort->get_sort_keys(); for (uchar **end= sort_keys+count ; sort_keys != end ; sort_keys++) { memcpy(to, *sort_keys+offset, res_length); to+= res_length; } DBUG_RETURN(0); } /** Test whether priority queue is worth using to get top elements of an ordered result set. If it is, then allocates buffer for required amount of records @param param Sort parameters. @param filesort_info Filesort information. @param table Table to sort. @param num_rows Estimate of number of rows in source record set. @param memory_available Memory available for sorting. DESCRIPTION Given a query like this: SELECT ... FROM t ORDER BY a1,...,an LIMIT max_rows; This function tests whether a priority queue should be used to keep the result. Necessary conditions are: - estimate that it is actually cheaper than merge-sort - enough memory to store the <max_rows> records. If we don't have space for <max_rows> records, but we *do* have space for <max_rows> keys, we may rewrite 'table' to sort with references to records instead of additional data. (again, based on estimates that it will actually be cheaper). @retval true - if it's ok to use PQ false - PQ will be slower than merge-sort, or there is not enough memory. */ bool check_if_pq_applicable(Sort_param *param, Filesort_info *filesort_info, TABLE *table, ha_rows num_rows, ulong memory_available) { DBUG_ENTER("check_if_pq_applicable"); /* How much Priority Queue sort is slower than qsort. Measurements (see unit test) indicate that PQ is roughly 3 times slower. */ const double PQ_slowness= 3.0; if (param->max_rows == HA_POS_ERROR) { DBUG_PRINT("info", ("No LIMIT")); DBUG_RETURN(false); } if (param->max_rows + 2 >= UINT_MAX) { DBUG_PRINT("info", ("Too large LIMIT")); DBUG_RETURN(false); } ulong num_available_keys= memory_available / (param->rec_length + sizeof(char*)); // We need 1 extra record in the buffer, when using PQ. param->max_keys_per_buffer= (uint) param->max_rows + 1; if (num_rows < num_available_keys) { // The whole source set fits into memory. if (param->max_rows < num_rows/PQ_slowness ) { filesort_info->alloc_sort_buffer(param->max_keys_per_buffer, param->rec_length); DBUG_RETURN(filesort_info->get_sort_keys() != NULL); } else { // PQ will be slower. DBUG_RETURN(false); } } // Do we have space for LIMIT rows in memory? if (param->max_keys_per_buffer < num_available_keys) { filesort_info->alloc_sort_buffer(param->max_keys_per_buffer, param->rec_length); DBUG_RETURN(filesort_info->get_sort_keys() != NULL); } // Try to strip off addon fields. if (param->addon_field) { const ulong row_length= param->sort_length + param->ref_length + sizeof(char*); num_available_keys= memory_available / row_length; // Can we fit all the keys in memory? if (param->max_keys_per_buffer < num_available_keys) { const double sort_merge_cost= get_merge_many_buffs_cost_fast(num_rows, num_available_keys, row_length); /* PQ has cost: (insert + qsort) * log(queue size) / TIME_FOR_COMPARE_ROWID + cost of file lookup afterwards. The lookup cost is a bit pessimistic: we take scan_time and assume that on average we find the row after scanning half of the file. A better estimate would be lookup cost, but note that we are doing random lookups here, rather than sequential scan. */ const double pq_cpu_cost= (PQ_slowness * num_rows + param->max_keys_per_buffer) * log((double) param->max_keys_per_buffer) / TIME_FOR_COMPARE_ROWID; const double pq_io_cost= param->max_rows * table->file->scan_time() / 2.0; const double pq_cost= pq_cpu_cost + pq_io_cost; if (sort_merge_cost < pq_cost) DBUG_RETURN(false); filesort_info->alloc_sort_buffer(param->max_keys_per_buffer, param->sort_length + param->ref_length); if (filesort_info->get_sort_keys()) { // Make attached data to be references instead of fields. my_free(filesort_info->addon_buf); my_free(filesort_info->addon_field); filesort_info->addon_buf= NULL; filesort_info->addon_field= NULL; param->addon_field= NULL; param->addon_length= 0; param->res_length= param->ref_length; param->sort_length+= param->ref_length; param->rec_length= param->sort_length; DBUG_RETURN(true); } } } DBUG_RETURN(false); } /** Merge buffers to make < MERGEBUFF2 buffers. */ int merge_many_buff(Sort_param *param, uchar *sort_buffer, BUFFPEK *buffpek, uint *maxbuffer, IO_CACHE *t_file) { register uint i; IO_CACHE t_file2,*from_file,*to_file,*temp; BUFFPEK *lastbuff; DBUG_ENTER("merge_many_buff"); if (*maxbuffer < MERGEBUFF2) DBUG_RETURN(0); /* purecov: inspected */ if (flush_io_cache(t_file) || open_cached_file(&t_file2,mysql_tmpdir,TEMP_PREFIX,DISK_BUFFER_SIZE, MYF(MY_WME))) DBUG_RETURN(1); /* purecov: inspected */ from_file= t_file ; to_file= &t_file2; while (*maxbuffer >= MERGEBUFF2) { if (reinit_io_cache(from_file,READ_CACHE,0L,0,0)) goto cleanup; if (reinit_io_cache(to_file,WRITE_CACHE,0L,0,0)) goto cleanup; lastbuff=buffpek; for (i=0 ; i <= *maxbuffer-MERGEBUFF*3/2 ; i+=MERGEBUFF) { if (merge_buffers(param,from_file,to_file,sort_buffer,lastbuff++, buffpek+i,buffpek+i+MERGEBUFF-1,0)) goto cleanup; } if (merge_buffers(param,from_file,to_file,sort_buffer,lastbuff++, buffpek+i,buffpek+ *maxbuffer,0)) break; /* purecov: inspected */ if (flush_io_cache(to_file)) break; /* purecov: inspected */ temp=from_file; from_file=to_file; to_file=temp; setup_io_cache(from_file); setup_io_cache(to_file); *maxbuffer= (uint) (lastbuff-buffpek)-1; } cleanup: close_cached_file(to_file); // This holds old result if (to_file == t_file) { *t_file=t_file2; // Copy result file setup_io_cache(t_file); } DBUG_RETURN(*maxbuffer >= MERGEBUFF2); /* Return 1 if interrupted */ } /* merge_many_buff */ /** Read data to buffer. @retval (uint)-1 if something goes wrong */ uint read_to_buffer(IO_CACHE *fromfile, BUFFPEK *buffpek, uint rec_length) { register uint count; uint length; if ((count=(uint) MY_MIN((ha_rows) buffpek->max_keys,buffpek->count))) { if (mysql_file_pread(fromfile->file, (uchar*) buffpek->base, (length= rec_length*count), buffpek->file_pos, MYF_RW)) return((uint) -1); /* purecov: inspected */ buffpek->key=buffpek->base; buffpek->file_pos+= length; /* New filepos */ buffpek->count-= count; buffpek->mem_count= count; } return (count*rec_length); } /* read_to_buffer */ /** Put all room used by freed buffer to use in adjacent buffer. Note, that we can't simply distribute memory evenly between all buffers, because new areas must not overlap with old ones. @param[in] queue list of non-empty buffers, without freed buffer @param[in] reuse empty buffer @param[in] key_length key length */ void reuse_freed_buff(QUEUE *queue, BUFFPEK *reuse, uint key_length) { uchar *reuse_end= reuse->base + reuse->max_keys * key_length; for (uint i= queue_first_element(queue); i <= queue_last_element(queue); i++) { BUFFPEK *bp= (BUFFPEK *) queue_element(queue, i); if (bp->base + bp->max_keys * key_length == reuse->base) { bp->max_keys+= reuse->max_keys; return; } else if (bp->base == reuse_end) { bp->base= reuse->base; bp->max_keys+= reuse->max_keys; return; } } DBUG_ASSERT(0); } /** Merge buffers to one buffer. @param param Sort parameter @param from_file File with source data (BUFFPEKs point to this file) @param to_file File to write the sorted result data. @param sort_buffer Buffer for data to store up to MERGEBUFF2 sort keys. @param lastbuff OUT Store here BUFFPEK describing data written to to_file @param Fb First element in source BUFFPEKs array @param Tb Last element in source BUFFPEKs array @param flag @retval 0 OK @retval other error */ int merge_buffers(Sort_param *param, IO_CACHE *from_file, IO_CACHE *to_file, uchar *sort_buffer, BUFFPEK *lastbuff, BUFFPEK *Fb, BUFFPEK *Tb, int flag) { int error; uint rec_length,res_length,offset; size_t sort_length; ulong maxcount; ha_rows max_rows,org_max_rows; my_off_t to_start_filepos; uchar *strpos; BUFFPEK *buffpek; QUEUE queue; qsort2_cmp cmp; void *first_cmp_arg; element_count dupl_count= 0; uchar *src; uchar *unique_buff= param->unique_buff; const bool killable= !param->not_killable; THD* const thd=current_thd; DBUG_ENTER("merge_buffers"); thd->inc_status_sort_merge_passes(); thd->query_plan_fsort_passes++; error=0; rec_length= param->rec_length; res_length= param->res_length; sort_length= param->sort_length; uint dupl_count_ofs= rec_length-sizeof(element_count); uint min_dupl_count= param->min_dupl_count; bool check_dupl_count= flag && min_dupl_count; offset= (rec_length- (flag && min_dupl_count ? sizeof(dupl_count) : 0)-res_length); uint wr_len= flag ? res_length : rec_length; uint wr_offset= flag ? offset : 0; maxcount= (ulong) (param->max_keys_per_buffer/((uint) (Tb-Fb) +1)); to_start_filepos= my_b_tell(to_file); strpos= sort_buffer; org_max_rows=max_rows= param->max_rows; set_if_bigger(maxcount, 1); if (unique_buff) { cmp= param->compare; first_cmp_arg= (void *) &param->cmp_context; } else { cmp= get_ptr_compare(sort_length); first_cmp_arg= (void*) &sort_length; } if (init_queue(&queue, (uint) (Tb-Fb)+1, offsetof(BUFFPEK,key), 0, (queue_compare) cmp, first_cmp_arg, 0, 0)) DBUG_RETURN(1); /* purecov: inspected */ for (buffpek= Fb ; buffpek <= Tb ; buffpek++) { buffpek->base= strpos; buffpek->max_keys= maxcount; strpos+= (uint) (error= (int) read_to_buffer(from_file, buffpek, rec_length)); if (error == -1) goto err; /* purecov: inspected */ buffpek->max_keys= buffpek->mem_count; // If less data in buffers than expected queue_insert(&queue, (uchar*) buffpek); } if (unique_buff) { /* Called by Unique::get() Copy the first argument to unique_buff for unique removal. Store it also in 'to_file'. */ buffpek= (BUFFPEK*) queue_top(&queue); memcpy(unique_buff, buffpek->key, rec_length); if (min_dupl_count) memcpy(&dupl_count, unique_buff+dupl_count_ofs, sizeof(dupl_count)); buffpek->key+= rec_length; if (! --buffpek->mem_count) { if (!(error= (int) read_to_buffer(from_file, buffpek, rec_length))) { queue_remove(&queue,0); reuse_freed_buff(&queue, buffpek, rec_length); } else if (error == -1) goto err; /* purecov: inspected */ } queue_replace_top(&queue); // Top element has been used } else cmp= 0; // Not unique while (queue.elements > 1) { if (killable && thd->check_killed()) { error= 1; goto err; /* purecov: inspected */ } for (;;) { buffpek= (BUFFPEK*) queue_top(&queue); src= buffpek->key; if (cmp) // Remove duplicates { if (!(*cmp)(first_cmp_arg, &unique_buff, (uchar**) &buffpek->key)) { if (min_dupl_count) { element_count cnt; memcpy(&cnt, (uchar *) buffpek->key+dupl_count_ofs, sizeof(cnt)); dupl_count+= cnt; } goto skip_duplicate; } if (min_dupl_count) { memcpy(unique_buff+dupl_count_ofs, &dupl_count, sizeof(dupl_count)); } src= unique_buff; } /* Do not write into the output file if this is the final merge called for a Unique object used for intersection and dupl_count is less than min_dupl_count. If the Unique object is used to intersect N sets of unique elements then for any element: dupl_count >= N <=> the element is occurred in each of these N sets. */ if (!check_dupl_count || dupl_count >= min_dupl_count) { if (my_b_write(to_file, src+wr_offset, wr_len)) { error=1; goto err; /* purecov: inspected */ } } if (cmp) { memcpy(unique_buff, (uchar*) buffpek->key, rec_length); if (min_dupl_count) memcpy(&dupl_count, unique_buff+dupl_count_ofs, sizeof(dupl_count)); } if (!--max_rows) { error= 0; /* purecov: inspected */ goto end; /* purecov: inspected */ } skip_duplicate: buffpek->key+= rec_length; if (! --buffpek->mem_count) { if (!(error= (int) read_to_buffer(from_file, buffpek, rec_length))) { (void) queue_remove_top(&queue); reuse_freed_buff(&queue, buffpek, rec_length); break; /* One buffer have been removed */ } else if (error == -1) goto err; /* purecov: inspected */ } queue_replace_top(&queue); /* Top element has been replaced */ } } buffpek= (BUFFPEK*) queue_top(&queue); buffpek->base= (uchar*) sort_buffer; buffpek->max_keys= param->max_keys_per_buffer; /* As we know all entries in the buffer are unique, we only have to check if the first one is the same as the last one we wrote */ if (cmp) { if (!(*cmp)(first_cmp_arg, &unique_buff, (uchar**) &buffpek->key)) { if (min_dupl_count) { element_count cnt; memcpy(&cnt, (uchar *) buffpek->key+dupl_count_ofs, sizeof(cnt)); dupl_count+= cnt; } buffpek->key+= rec_length; --buffpek->mem_count; } if (min_dupl_count) memcpy(unique_buff+dupl_count_ofs, &dupl_count, sizeof(dupl_count)); if (!check_dupl_count || dupl_count >= min_dupl_count) { src= unique_buff; if (my_b_write(to_file, src+wr_offset, wr_len)) { error=1; goto err; /* purecov: inspected */ } if (!--max_rows) { error= 0; goto end; } } } do { if ((ha_rows) buffpek->mem_count > max_rows) { /* Don't write too many records */ buffpek->mem_count= (uint) max_rows; buffpek->count= 0; /* Don't read more */ } max_rows-= buffpek->mem_count; if (flag == 0) { if (my_b_write(to_file, (uchar*) buffpek->key, (rec_length*buffpek->mem_count))) { error= 1; goto err; /* purecov: inspected */ } } else { register uchar *end; src= buffpek->key+offset; for (end= src+buffpek->mem_count*rec_length ; src != end ; src+= rec_length) { if (check_dupl_count) { memcpy((uchar *) &dupl_count, src+dupl_count_ofs, sizeof(dupl_count)); if (dupl_count < min_dupl_count) continue; } if (my_b_write(to_file, src, wr_len)) { error=1; goto err; } } } } while ((error=(int) read_to_buffer(from_file, buffpek, rec_length)) != -1 && error != 0); end: lastbuff->count= MY_MIN(org_max_rows-max_rows, param->max_rows); lastbuff->file_pos= to_start_filepos; err: delete_queue(&queue); DBUG_RETURN(error); } /* merge_buffers */ /* Do a merge to output-file (save only positions) */ int merge_index(Sort_param *param, uchar *sort_buffer, BUFFPEK *buffpek, uint maxbuffer, IO_CACHE *tempfile, IO_CACHE *outfile) { DBUG_ENTER("merge_index"); if (merge_buffers(param,tempfile,outfile,sort_buffer,buffpek,buffpek, buffpek+maxbuffer,1)) DBUG_RETURN(1); /* purecov: inspected */ DBUG_RETURN(0); } /* merge_index */ static uint suffix_length(ulong string_length) { if (string_length < 256) return 1; if (string_length < 256L*256L) return 2; if (string_length < 256L*256L*256L) return 3; return 4; // Can't sort longer than 4G } /** Calculate length of sort key. @param thd Thread handler @param sortorder Order of items to sort @param s_length Number of items to sort @param[out] multi_byte_charset Set to 1 if we are using multi-byte charset (In which case we have to use strxnfrm()) @note sortorder->length is updated for each sort item. @n sortorder->need_strxnfrm is set 1 if we have to use strxnfrm @return Total length of sort buffer in bytes */ static uint sortlength(THD *thd, SORT_FIELD *sortorder, uint s_length, bool *multi_byte_charset) { reg2 uint length; const CHARSET_INFO *cs; *multi_byte_charset= 0; length=0; for (; s_length-- ; sortorder++) { sortorder->need_strxnfrm= 0; sortorder->suffix_length= 0; if (sortorder->field) { cs= sortorder->field->sort_charset(); sortorder->length= sortorder->field->sort_length(); if (use_strnxfrm((cs=sortorder->field->sort_charset()))) { sortorder->need_strxnfrm= 1; *multi_byte_charset= 1; sortorder->length= cs->coll->strnxfrmlen(cs, sortorder->length); } if (sortorder->field->maybe_null()) length++; // Place for NULL marker } else { sortorder->result_type= sortorder->item->cmp_type(); switch (sortorder->result_type) { case STRING_RESULT: sortorder->length=sortorder->item->max_length; set_if_smaller(sortorder->length, thd->variables.max_sort_length); if (use_strnxfrm((cs=sortorder->item->collation.collation))) { sortorder->length= cs->coll->strnxfrmlen(cs, sortorder->length); sortorder->need_strxnfrm= 1; *multi_byte_charset= 1; } else if (cs == &my_charset_bin) { /* Store length last to be able to sort blob/varbinary */ sortorder->suffix_length= suffix_length(sortorder->length); sortorder->length+= sortorder->suffix_length; } break; case TIME_RESULT: case INT_RESULT: sortorder->length=8; // Size of intern longlong break; case DECIMAL_RESULT: sortorder->length= my_decimal_get_binary_size(sortorder->item->max_length - (sortorder->item->decimals ? 1 : 0), sortorder->item->decimals); break; case REAL_RESULT: sortorder->length=sizeof(double); break; case ROW_RESULT: default: // This case should never be choosen DBUG_ASSERT(0); break; } if (sortorder->item->maybe_null) length++; // Place for NULL marker } set_if_smaller(sortorder->length, thd->variables.max_sort_length); length+=sortorder->length; } sortorder->field= (Field*) 0; // end marker DBUG_PRINT("info",("sort_length: %d",length)); return length; } /** Get descriptors of fields appended to sorted fields and calculate its total length. The function first finds out what fields are used in the result set. Then it calculates the length of the buffer to store the values of these fields together with the value of sort values. If the calculated length is not greater than max_length_for_sort_data the function allocates memory for an array of descriptors containing layouts for the values of the non-sorted fields in the buffer and fills them. @param thd Current thread @param ptabfield Array of references to the table fields @param sortlength Total length of sorted fields @param[out] plength Total length of appended fields @note The null bits for the appended values are supposed to be put together and stored the buffer just ahead of the value of the first field. @return Pointer to the layout descriptors for the appended fields, if any @retval NULL if we do not store field values with sort data. */ static SORT_ADDON_FIELD * get_addon_fields(ulong max_length_for_sort_data, Field **ptabfield, uint sortlength, uint *plength) { Field **pfield; Field *field; SORT_ADDON_FIELD *addonf; uint length= 0; uint fields= 0; uint null_fields= 0; MY_BITMAP *read_set= (*ptabfield)->table->read_set; /* If there is a reference to a field in the query add it to the the set of appended fields. Note for future refinement: This this a too strong condition. Actually we need only the fields referred in the result set. And for some of them it makes sense to use the values directly from sorted fields. But beware the case when item->cmp_type() != item->result_type() */ *plength= 0; for (pfield= ptabfield; (field= *pfield) ; pfield++) { if (!bitmap_is_set(read_set, field->field_index)) continue; if (field->flags & BLOB_FLAG) return 0; length+= field->max_packed_col_length(field->pack_length()); if (field->maybe_null()) null_fields++; fields++; } if (!fields) return 0; length+= (null_fields+7)/8; if (length+sortlength > max_length_for_sort_data || !(addonf= (SORT_ADDON_FIELD *) my_malloc(sizeof(SORT_ADDON_FIELD)* (fields+1), MYF(MY_WME | MY_THREAD_SPECIFIC)))) return 0; *plength= length; length= (null_fields+7)/8; null_fields= 0; for (pfield= ptabfield; (field= *pfield) ; pfield++) { if (!bitmap_is_set(read_set, field->field_index)) continue; addonf->field= field; addonf->offset= length; if (field->maybe_null()) { addonf->null_offset= null_fields/8; addonf->null_bit= 1<<(null_fields & 7); null_fields++; } else { addonf->null_offset= 0; addonf->null_bit= 0; } addonf->length= field->max_packed_col_length(field->pack_length()); length+= addonf->length; addonf++; } addonf->field= 0; // Put end marker DBUG_PRINT("info",("addon_length: %d",length)); return (addonf-fields); } /** Copy (unpack) values appended to sorted fields from a buffer back to their regular positions specified by the Field::ptr pointers. @param addon_field Array of descriptors for appended fields @param buff Buffer which to unpack the value from @note The function is supposed to be used only as a callback function when getting field values for the sorted result set. @return void. */ static void unpack_addon_fields(struct st_sort_addon_field *addon_field, uchar *buff, uchar *buff_end) { Field *field; SORT_ADDON_FIELD *addonf= addon_field; for ( ; (field= addonf->field) ; addonf++) { if (addonf->null_bit && (addonf->null_bit & buff[addonf->null_offset])) { field->set_null(); continue; } field->set_notnull(); field->unpack(field->ptr, buff + addonf->offset, buff_end, 0); } } /* ** functions to change a double or float to a sortable string ** The following should work for IEEE */ #define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG) void change_double_for_sort(double nr,uchar *to) { uchar *tmp=(uchar*) to; if (nr == 0.0) { /* Change to zero string */ tmp[0]=(uchar) 128; memset(tmp+1, 0, sizeof(nr)-1); } else { #ifdef WORDS_BIGENDIAN memcpy(tmp, &nr, sizeof(nr)); #else { uchar *ptr= (uchar*) &nr; #if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0]; tmp[4]= ptr[7]; tmp[5]=ptr[6]; tmp[6]= ptr[5]; tmp[7]=ptr[4]; #else tmp[0]= ptr[7]; tmp[1]=ptr[6]; tmp[2]= ptr[5]; tmp[3]=ptr[4]; tmp[4]= ptr[3]; tmp[5]=ptr[2]; tmp[6]= ptr[1]; tmp[7]=ptr[0]; #endif } #endif if (tmp[0] & 128) /* Negative */ { /* make complement */ uint i; for (i=0 ; i < sizeof(nr); i++) tmp[i]=tmp[i] ^ (uchar) 255; } else { /* Set high and move exponent one up */ ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] | (ushort) 32768); exp_part+= (ushort) 1 << (16-1-DBL_EXP_DIG); tmp[0]= (uchar) (exp_part >> 8); tmp[1]= (uchar) exp_part; } } }
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sql_priv.h" #include "unireg.h" #include "sql_parse.h" // check_access #ifdef HAVE_REPLICATION #include "rpl_mi.h" #include "sql_repl.h" #include "sql_acl.h" // SUPER_ACL #include "log_event.h" #include "rpl_filter.h" #include <my_dir.h> #include "rpl_handler.h" #include "debug_sync.h" int max_binlog_dump_events = 0; // unlimited my_bool opt_sporadic_binlog_dump_fail = 0; #ifndef DBUG_OFF static int binlog_dump_count = 0; #endif /** a copy of active_mi->rli->slave_skip_counter, for showing in SHOW VARIABLES, INFORMATION_SCHEMA.GLOBAL_VARIABLES and @@sql_slave_skip_counter without taking all the mutexes needed to access active_mi->rli->slave_skip_counter properly. */ uint sql_slave_skip_counter; /* fake_rotate_event() builds a fake (=which does not exist physically in any binlog) Rotate event, which contains the name of the binlog we are going to send to the slave (because the slave may not know it if it just asked for MASTER_LOG_FILE='', MASTER_LOG_POS=4). < 4.0.14, fake_rotate_event() was called only if the requested pos was 4. After this version we always call it, so that a 3.23.58 slave can rely on it to detect if the master is 4.0 (and stop) (the _fake_ Rotate event has zeros in the good positions which, by chance, make it possible for the 3.23 slave to detect that this event is unexpected) (this is luck which happens because the master and slave disagree on the size of the header of Log_event). Relying on the event length of the Rotate event instead of these well-placed zeros was not possible as Rotate events have a variable-length part. */ static int fake_rotate_event(NET* net, String* packet, char* log_file_name, ulonglong position, const char** errmsg) { DBUG_ENTER("fake_rotate_event"); char header[LOG_EVENT_HEADER_LEN], buf[ROTATE_HEADER_LEN+100]; /* 'when' (the timestamp) is set to 0 so that slave could distinguish between real and fake Rotate events (if necessary) */ memset(header, 0, 4); header[EVENT_TYPE_OFFSET] = ROTATE_EVENT; char* p = log_file_name+dirname_length(log_file_name); uint ident_len = (uint) strlen(p); ulong event_len = ident_len + LOG_EVENT_HEADER_LEN + ROTATE_HEADER_LEN; int4store(header + SERVER_ID_OFFSET, server_id); int4store(header + EVENT_LEN_OFFSET, event_len); int2store(header + FLAGS_OFFSET, LOG_EVENT_ARTIFICIAL_F); // TODO: check what problems this may cause and fix them int4store(header + LOG_POS_OFFSET, 0); packet->append(header, sizeof(header)); int8store(buf+R_POS_OFFSET,position); packet->append(buf, ROTATE_HEADER_LEN); packet->append(p,ident_len); if (my_net_write(net, (uchar*) packet->ptr(), packet->length())) { *errmsg = "failed on my_net_write()"; DBUG_RETURN(-1); } DBUG_RETURN(0); } /* Reset thread transmit packet buffer for event sending This function allocates header bytes for event transmission, and should be called before store the event data to the packet buffer. */ static int reset_transmit_packet(THD *thd, ushort flags, ulong *ev_offset, const char **errmsg) { int ret= 0; String *packet= &thd->packet; /* reserve and set default header */ packet->length(0); packet->set("\0", 1, &my_charset_bin); if (RUN_HOOK(binlog_transmit, reserve_header, (thd, flags, packet))) { *errmsg= "Failed to run hook 'reserve_header'"; my_errno= ER_UNKNOWN_ERROR; ret= 1; } *ev_offset= packet->length(); return ret; } static int send_file(THD *thd) { NET* net = &thd->net; int fd = -1, error = 1; size_t bytes; char fname[FN_REFLEN+1]; const char *errmsg = 0; int old_timeout; unsigned long packet_len; uchar buf[IO_SIZE]; // It's safe to alloc this DBUG_ENTER("send_file"); /* The client might be slow loading the data, give him wait_timeout to do the job */ old_timeout= net->read_timeout; my_net_set_read_timeout(net, thd->variables.net_wait_timeout); /* We need net_flush here because the client will not know it needs to send us the file name until it has processed the load event entry */ if (net_flush(net) || (packet_len = my_net_read(net)) == packet_error) { errmsg = "while reading file name"; goto err; } // terminate with \0 for fn_format *((char*)net->read_pos + packet_len) = 0; fn_format(fname, (char*) net->read_pos + 1, "", "", 4); // this is needed to make replicate-ignore-db if (!strcmp(fname,"/dev/null")) goto end; if ((fd= mysql_file_open(key_file_send_file, fname, O_RDONLY, MYF(0))) < 0) { errmsg = "on open of file"; goto err; } while ((long) (bytes= mysql_file_read(fd, buf, IO_SIZE, MYF(0))) > 0) { if (my_net_write(net, buf, bytes)) { errmsg = "while writing data to client"; goto err; } } end: if (my_net_write(net, (uchar*) "", 0) || net_flush(net) || (my_net_read(net) == packet_error)) { errmsg = "while negotiating file transfer close"; goto err; } error = 0; err: my_net_set_read_timeout(net, old_timeout); if (fd >= 0) mysql_file_close(fd, MYF(0)); if (errmsg) { sql_print_error("Failed in send_file() %s", errmsg); DBUG_PRINT("error", ("%s", errmsg)); } DBUG_RETURN(error); } /* Adjust the position pointer in the binary log file for all running slaves SYNOPSIS adjust_linfo_offsets() purge_offset Number of bytes removed from start of log index file NOTES - This is called when doing a PURGE when we delete lines from the index log file REQUIREMENTS - Before calling this function, we have to ensure that no threads are using any binary log file before purge_offset.a TODO - Inform the slave threads that they should sync the position in the binary log file with flush_relay_log_info. Now they sync is done for next read. */ void adjust_linfo_offsets(my_off_t purge_offset) { THD *tmp; mysql_mutex_lock(&LOCK_thread_count); I_List_iterator<THD> it(threads); while ((tmp=it++)) { LOG_INFO* linfo; if ((linfo = tmp->current_linfo)) { mysql_mutex_lock(&linfo->lock); /* Index file offset can be less that purge offset only if we just started reading the index file. In that case we have nothing to adjust */ if (linfo->index_file_offset < purge_offset) linfo->fatal = (linfo->index_file_offset != 0); else linfo->index_file_offset -= purge_offset; mysql_mutex_unlock(&linfo->lock); } } mysql_mutex_unlock(&LOCK_thread_count); } bool log_in_use(const char* log_name) { size_t log_name_len = strlen(log_name) + 1; THD *tmp; bool result = 0; mysql_mutex_lock(&LOCK_thread_count); I_List_iterator<THD> it(threads); while ((tmp=it++)) { LOG_INFO* linfo; if ((linfo = tmp->current_linfo)) { mysql_mutex_lock(&linfo->lock); result = !memcmp(log_name, linfo->log_file_name, log_name_len); mysql_mutex_unlock(&linfo->lock); if (result) break; } } mysql_mutex_unlock(&LOCK_thread_count); return result; } bool purge_error_message(THD* thd, int res) { uint errcode; if ((errcode= purge_log_get_error_code(res)) != 0) { my_message(errcode, ER(errcode), MYF(0)); return TRUE; } my_ok(thd); return FALSE; } /** Execute a PURGE BINARY LOGS TO <log> command. @param thd Pointer to THD object for the client thread executing the statement. @param to_log Name of the last log to purge. @retval FALSE success @retval TRUE failure */ bool purge_master_logs(THD* thd, const char* to_log) { char search_file_name[FN_REFLEN]; if (!mysql_bin_log.is_open()) { my_ok(thd); return FALSE; } mysql_bin_log.make_log_name(search_file_name, to_log); return purge_error_message(thd, mysql_bin_log.purge_logs(search_file_name, 0, 1, 1, NULL)); } /** Execute a PURGE BINARY LOGS BEFORE <date> command. @param thd Pointer to THD object for the client thread executing the statement. @param purge_time Date before which logs should be purged. @retval FALSE success @retval TRUE failure */ bool purge_master_logs_before_date(THD* thd, time_t purge_time) { if (!mysql_bin_log.is_open()) { my_ok(thd); return 0; } return purge_error_message(thd, mysql_bin_log.purge_logs_before_date(purge_time)); } int test_for_non_eof_log_read_errors(int error, const char **errmsg) { if (error == LOG_READ_EOF) return 0; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; switch (error) { case LOG_READ_BOGUS: *errmsg = "bogus data in log event"; break; case LOG_READ_TOO_LARGE: *errmsg = "log event entry exceeded max_allowed_packet; \ Increase max_allowed_packet on master"; break; case LOG_READ_IO: *errmsg = "I/O error reading log event"; break; case LOG_READ_MEM: *errmsg = "memory allocation failed reading log event"; break; case LOG_READ_TRUNC: *errmsg = "binlog truncated in the middle of event; consider out of disk space on master"; break; default: *errmsg = "unknown error reading log event on the master"; break; } return error; } /** An auxiliary function for calling in mysql_binlog_send to initialize the heartbeat timeout in waiting for a binlogged event. @param[in] thd THD to access a user variable @return heartbeat period an ulonglong of nanoseconds or zero if heartbeat was not demanded by slave */ static ulonglong get_heartbeat_period(THD * thd) { my_bool null_value; LEX_STRING name= { C_STRING_WITH_LEN("master_heartbeat_period")}; user_var_entry *entry= (user_var_entry*) my_hash_search(&thd->user_vars, (uchar*) name.str, name.length); return entry? entry->val_int(&null_value) : 0; } /* Function prepares and sends repliation heartbeat event. @param net net object of THD @param packet buffer to store the heartbeat instance @param event_coordinates binlog file name and position of the last real event master sent from binlog @note Among three essential pieces of heartbeat data Log_event::when is computed locally. The error to send is serious and should force terminating the dump thread. */ static int send_heartbeat_event(NET* net, String* packet, const struct event_coordinates *coord) { DBUG_ENTER("send_heartbeat_event"); char header[LOG_EVENT_HEADER_LEN]; /* 'when' (the timestamp) is set to 0 so that slave could distinguish between real and fake Rotate events (if necessary) */ memset(header, 0, 4); // when header[EVENT_TYPE_OFFSET] = HEARTBEAT_LOG_EVENT; char* p= coord->file_name + dirname_length(coord->file_name); uint ident_len = strlen(p); ulong event_len = ident_len + LOG_EVENT_HEADER_LEN; int4store(header + SERVER_ID_OFFSET, server_id); int4store(header + EVENT_LEN_OFFSET, event_len); int2store(header + FLAGS_OFFSET, 0); int4store(header + LOG_POS_OFFSET, coord->pos); // log_pos packet->append(header, sizeof(header)); packet->append(p, ident_len); // log_file_name if (my_net_write(net, (uchar*) packet->ptr(), packet->length()) || net_flush(net)) { DBUG_RETURN(-1); } DBUG_RETURN(0); } /* TODO: Clean up loop to only have one call to send_file() */ void mysql_binlog_send(THD* thd, char* log_ident, my_off_t pos, ushort flags) { LOG_INFO linfo; char *log_file_name = linfo.log_file_name; char search_file_name[FN_REFLEN], *name; ulong ev_offset; IO_CACHE log; File file = -1; String* packet = &thd->packet; int error; const char *errmsg = "Unknown error"; char error_text[MAX_SLAVE_ERRMSG]; // to be send to slave via my_message() NET* net = &thd->net; mysql_mutex_t *log_lock; mysql_cond_t *log_cond; #ifndef DBUG_OFF int left_events = max_binlog_dump_events; #endif int old_max_allowed_packet= thd->variables.max_allowed_packet; DBUG_ENTER("mysql_binlog_send"); DBUG_PRINT("enter",("log_ident: '%s' pos: %ld", log_ident, (long) pos)); bzero((char*) &log,sizeof(log)); /* heartbeat_period from @master_heartbeat_period user variable */ ulonglong heartbeat_period= get_heartbeat_period(thd); struct timespec heartbeat_buf; struct timespec *heartbeat_ts= NULL; const LOG_POS_COORD start_coord= { log_ident, pos }, *p_start_coord= &start_coord; LOG_POS_COORD coord_buf= { log_file_name, BIN_LOG_HEADER_SIZE }, *p_coord= &coord_buf; if (heartbeat_period != LL(0)) { heartbeat_ts= &heartbeat_buf; set_timespec_nsec(*heartbeat_ts, 0); } if (global_system_variables.log_warnings > 1) sql_print_information("Start binlog_dump to slave_server(%d), pos(%s, %lu)", thd->server_id, log_ident, (ulong)pos); if (RUN_HOOK(binlog_transmit, transmit_start, (thd, flags, log_ident, pos))) { errmsg= "Failed to run hook 'transmit_start'"; my_errno= ER_UNKNOWN_ERROR; goto err; } #ifndef DBUG_OFF if (opt_sporadic_binlog_dump_fail && (binlog_dump_count++ % 2)) { errmsg = "Master failed COM_BINLOG_DUMP to test if slave can recover"; my_errno= ER_UNKNOWN_ERROR; goto err; } #endif if (!mysql_bin_log.is_open()) { errmsg = "Binary log is not open"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } if (!server_id_supplied) { errmsg = "Misconfigured master - server id was not set"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } name=search_file_name; if (log_ident[0]) mysql_bin_log.make_log_name(search_file_name, log_ident); else name=0; // Find first log linfo.index_file_offset = 0; if (mysql_bin_log.find_log_pos(&linfo, name, 1)) { errmsg = "Could not find first log file name in binary log index file"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = &linfo; mysql_mutex_unlock(&LOCK_thread_count); if ((file=open_binlog(&log, log_file_name, &errmsg)) < 0) { my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } if (pos < BIN_LOG_HEADER_SIZE || pos > my_b_filelength(&log)) { errmsg= "Client requested master to start replication from \ impossible position"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } /* reset transmit packet for the fake rotate event below */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; /* Tell the client about the log name with a fake Rotate event; this is needed even if we also send a Format_description_log_event just after, because that event does not contain the binlog's name. Note that as this Rotate event is sent before Format_description_log_event, the slave cannot have any info to understand this event's format, so the header len of Rotate_log_event is FROZEN (so in 5.0 it will have a header shorter than other events except FORMAT_DESCRIPTION_EVENT). Before 4.0.14 we called fake_rotate_event below only if (pos == BIN_LOG_HEADER_SIZE), because if this is false then the slave already knows the binlog's name. Since, we always call fake_rotate_event; if the slave already knew the log's name (ex: CHANGE MASTER TO MASTER_LOG_FILE=...) this is useless but does not harm much. It is nice for 3.23 (>=.58) slaves which test Rotate events to see if the master is 4.0 (then they choose to stop because they can't replicate 4.0); by always calling fake_rotate_event we are sure that 3.23.58 and newer will detect the problem as soon as replication starts (BUG#198). Always calling fake_rotate_event makes sending of normal (=from-binlog) Rotate events a priori unneeded, but it is not so simple: the 2 Rotate events are not equivalent, the normal one is before the Stop event, the fake one is after. If we don't send the normal one, then the Stop event will be interpreted (by existing 4.0 slaves) as "the master stopped", which is wrong. So for safety, given that we want minimum modification of 4.0, we send the normal and fake Rotates. */ if (fake_rotate_event(net, packet, log_file_name, pos, &errmsg)) { /* This error code is not perfect, as fake_rotate_event() does not read anything from the binlog; if it fails it's because of an error in my_net_write(), fortunately it will say so in errmsg. */ my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } /* Adding MAX_LOG_EVENT_HEADER_LEN, since a binlog event can become this larger than the corresponding packet (query) sent from client to master. */ thd->variables.max_allowed_packet= MAX_MAX_ALLOWED_PACKET; /* We can set log_lock now, it does not move (it's a member of mysql_bin_log, and it's already inited, and it will be destroyed only at shutdown). */ p_coord->pos= pos; // the first hb matches the slave's last seen value log_lock= mysql_bin_log.get_log_lock(); log_cond= mysql_bin_log.get_log_cond(); if (pos > BIN_LOG_HEADER_SIZE) { /* reset transmit packet for the event read from binary log file */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; /* Try to find a Format_description_log_event at the beginning of the binlog */ if (!(error = Log_event::read_log_event(&log, packet, log_lock))) { /* The packet has offsets equal to the normal offsets in a binlog event + ev_offset (the first ev_offset characters are the header (default \0)). */ DBUG_PRINT("info", ("Looked for a Format_description_log_event, found event type %d", (*packet)[EVENT_TYPE_OFFSET+ev_offset])); if ((*packet)[EVENT_TYPE_OFFSET+ev_offset] == FORMAT_DESCRIPTION_EVENT) { (*packet)[FLAGS_OFFSET+ev_offset] &= ~LOG_EVENT_BINLOG_IN_USE_F; /* mark that this event with "log_pos=0", so the slave should not increment master's binlog position (rli->group_master_log_pos) */ int4store((char*) packet->ptr()+LOG_POS_OFFSET+ev_offset, 0); /* if reconnect master sends FD event with `created' as 0 to avoid destroying temp tables. */ int4store((char*) packet->ptr()+LOG_EVENT_MINIMAL_HEADER_LEN+ ST_CREATED_OFFSET+ev_offset, (ulong) 0); /* send it */ if (my_net_write(net, (uchar*) packet->ptr(), packet->length())) { errmsg = "Failed on my_net_write()"; my_errno= ER_UNKNOWN_ERROR; goto err; } /* No need to save this event. We are only doing simple reads (no real parsing of the events) so we don't need it. And so we don't need the artificial Format_description_log_event of 3.23&4.x. */ } } else { if (test_for_non_eof_log_read_errors(error, &errmsg)) goto err; /* It's EOF, nothing to do, go on reading next events, the Format_description_log_event will be found naturally if it is written. */ } } /* end of if (pos > BIN_LOG_HEADER_SIZE); */ else { /* The Format_description_log_event event will be found naturally. */ } /* seek to the requested position, to start the requested dump */ my_b_seek(&log, pos); // Seek will done on next read while (!net->error && net->vio != 0 && !thd->killed) { Log_event_type event_type= UNKNOWN_EVENT; /* reset the transmit packet for the event read from binary log file */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; bool is_active_binlog= false; while (!(error= Log_event::read_log_event(&log, packet, log_lock, log_file_name, &is_active_binlog))) { #ifndef DBUG_OFF if (max_binlog_dump_events && !left_events--) { net_flush(net); errmsg = "Debugging binlog dump abort"; my_errno= ER_UNKNOWN_ERROR; goto err; } #endif /* log's filename does not change while it's active */ p_coord->pos= uint4korr(packet->ptr() + ev_offset + LOG_POS_OFFSET); event_type= (Log_event_type)((*packet)[LOG_EVENT_OFFSET+ev_offset]); DBUG_EXECUTE_IF("dump_thread_wait_before_send_xid", { if (event_type == XID_EVENT) { net_flush(net); const char act[]= "now " "wait_for signal.continue"; DBUG_ASSERT(opt_debug_sync_timeout > 0); DBUG_ASSERT(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act))); } }); if (event_type == FORMAT_DESCRIPTION_EVENT) { (*packet)[FLAGS_OFFSET+ev_offset] &= ~LOG_EVENT_BINLOG_IN_USE_F; } pos = my_b_tell(&log); if (RUN_HOOK(binlog_transmit, before_send_event, (thd, flags, packet, log_file_name, pos))) { my_errno= ER_UNKNOWN_ERROR; errmsg= "run 'before_send_event' hook failed"; goto err; } if (my_net_write(net, (uchar*) packet->ptr(), packet->length())) { errmsg = "Failed on my_net_write()"; my_errno= ER_UNKNOWN_ERROR; goto err; } DBUG_EXECUTE_IF("dump_thread_wait_before_send_xid", { if (event_type == XID_EVENT) { net_flush(net); } }); DBUG_PRINT("info", ("log event code %d", event_type)); if (event_type == LOAD_EVENT) { if (send_file(thd)) { errmsg = "failed in send_file()"; my_errno= ER_UNKNOWN_ERROR; goto err; } } if (RUN_HOOK(binlog_transmit, after_send_event, (thd, flags, packet))) { errmsg= "Failed to run hook 'after_send_event'"; my_errno= ER_UNKNOWN_ERROR; goto err; } /* reset transmit packet for next loop */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; } DBUG_EXECUTE_IF("wait_after_binlog_EOF", { const char act[]= "now wait_for signal.rotate_finished"; DBUG_ASSERT(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act))); };); /* TODO: now that we are logging the offset, check to make sure the recorded offset and the actual match. Guilhem 2003-06: this is not true if this master is a slave <4.0.15 running with --log-slave-updates, because then log_pos may be the offset in the-master-of-this-master's binlog. */ if (test_for_non_eof_log_read_errors(error, &errmsg)) goto err; /* We should only move to the next binlog when the last read event came from a already deactivated binlog. */ if (!(flags & BINLOG_DUMP_NON_BLOCK) && is_active_binlog) { /* Block until there is more data in the log */ if (net_flush(net)) { errmsg = "failed on net_flush()"; my_errno= ER_UNKNOWN_ERROR; goto err; } /* We may have missed the update broadcast from the log that has just happened, let's try to catch it if it did. If we did not miss anything, we just wait for other threads to signal us. */ { log.error=0; bool read_packet = 0; #ifndef DBUG_OFF if (max_binlog_dump_events && !left_events--) { errmsg = "Debugging binlog dump abort"; my_errno= ER_UNKNOWN_ERROR; goto err; } #endif /* reset the transmit packet for the event read from binary log file */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; /* No one will update the log while we are reading now, but we'll be quick and just read one record TODO: Add an counter that is incremented for each time we update the binary log. We can avoid the following read if the counter has not been updated since last read. */ mysql_mutex_lock(log_lock); switch (error= Log_event::read_log_event(&log, packet, (mysql_mutex_t*) 0)) { case 0: /* we read successfully, so we'll need to send it to the slave */ mysql_mutex_unlock(log_lock); read_packet = 1; p_coord->pos= uint4korr(packet->ptr() + ev_offset + LOG_POS_OFFSET); event_type= (Log_event_type)((*packet)[LOG_EVENT_OFFSET+ev_offset]); break; case LOG_READ_EOF: { int ret; ulong signal_cnt; DBUG_PRINT("wait",("waiting for data in binary log")); if (thd->server_id==0) // for mysqlbinlog (mysqlbinlog.server_id==0) { mysql_mutex_unlock(log_lock); goto end; } #ifndef DBUG_OFF ulong hb_info_counter= 0; #endif const char* old_msg= thd->proc_info; signal_cnt= mysql_bin_log.signal_cnt; do { if (heartbeat_period != 0) { DBUG_ASSERT(heartbeat_ts); set_timespec_nsec(*heartbeat_ts, heartbeat_period); } thd->enter_cond(log_cond, log_lock, "Master has sent all binlog to slave; " "waiting for binlog to be updated"); ret= mysql_bin_log.wait_for_update_bin_log(thd, heartbeat_ts); DBUG_ASSERT(ret == 0 || (heartbeat_period != 0)); if (ret == ETIMEDOUT || ret == ETIME) { #ifndef DBUG_OFF if (hb_info_counter < 3) { sql_print_information("master sends heartbeat message"); hb_info_counter++; if (hb_info_counter == 3) sql_print_information("the rest of heartbeat info skipped ..."); } #endif /* reset transmit packet for the heartbeat event */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) { thd->exit_cond(old_msg); goto err; } if (send_heartbeat_event(net, packet, p_coord)) { errmsg = "Failed on my_net_write()"; my_errno= ER_UNKNOWN_ERROR; thd->exit_cond(old_msg); goto err; } } else { DBUG_PRINT("wait",("binary log received update or a broadcast signal caught")); } } while (signal_cnt == mysql_bin_log.signal_cnt && !thd->killed); thd->exit_cond(old_msg); } break; default: mysql_mutex_unlock(log_lock); test_for_non_eof_log_read_errors(error, &errmsg); goto err; } if (read_packet) { thd_proc_info(thd, "Sending binlog event to slave"); pos = my_b_tell(&log); if (RUN_HOOK(binlog_transmit, before_send_event, (thd, flags, packet, log_file_name, pos))) { my_errno= ER_UNKNOWN_ERROR; errmsg= "run 'before_send_event' hook failed"; goto err; } if (my_net_write(net, (uchar*) packet->ptr(), packet->length()) ) { errmsg = "Failed on my_net_write()"; my_errno= ER_UNKNOWN_ERROR; goto err; } if (event_type == LOAD_EVENT) { if (send_file(thd)) { errmsg = "failed in send_file()"; my_errno= ER_UNKNOWN_ERROR; goto err; } } if (RUN_HOOK(binlog_transmit, after_send_event, (thd, flags, packet))) { my_errno= ER_UNKNOWN_ERROR; errmsg= "Failed to run hook 'after_send_event'"; goto err; } } log.error=0; } } else { bool loop_breaker = 0; /* need this to break out of the for loop from switch */ thd_proc_info(thd, "Finished reading one binlog; switching to next binlog"); switch (mysql_bin_log.find_next_log(&linfo, 1)) { case 0: break; case LOG_INFO_EOF: if (mysql_bin_log.is_active(log_file_name)) { loop_breaker = (flags & BINLOG_DUMP_NON_BLOCK); break; } default: errmsg = "could not find next log"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } if (loop_breaker) break; end_io_cache(&log); mysql_file_close(file, MYF(MY_WME)); /* reset transmit packet for the possible fake rotate event */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; /* Call fake_rotate_event() in case the previous log (the one which we have just finished reading) did not contain a Rotate event (for example (I don't know any other example) the previous log was the last one before the master was shutdown & restarted). This way we tell the slave about the new log's name and position. If the binlog is 5.0, the next event we are going to read and send is Format_description_log_event. */ if ((file=open_binlog(&log, log_file_name, &errmsg)) < 0 || fake_rotate_event(net, packet, log_file_name, BIN_LOG_HEADER_SIZE, &errmsg)) { my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } p_coord->file_name= log_file_name; // reset to the next } } end: end_io_cache(&log); mysql_file_close(file, MYF(MY_WME)); RUN_HOOK(binlog_transmit, transmit_stop, (thd, flags)); my_eof(thd); thd_proc_info(thd, "Waiting to finalize termination"); mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = 0; mysql_mutex_unlock(&LOCK_thread_count); thd->variables.max_allowed_packet= old_max_allowed_packet; DBUG_VOID_RETURN; err: thd_proc_info(thd, "Waiting to finalize termination"); if (my_errno == ER_MASTER_FATAL_ERROR_READING_BINLOG && my_b_inited(&log)) { /* detailing the fatal error message with coordinates of the last position read. */ my_snprintf(error_text, sizeof(error_text), "%s; the first event '%s' at %lld, " "the last event read from '%s' at %lld, " "the last byte read from '%s' at %lld.", errmsg, p_start_coord->file_name, p_start_coord->pos, p_coord->file_name, p_coord->pos, log_file_name, my_b_tell(&log)); } else strcpy(error_text, errmsg); end_io_cache(&log); RUN_HOOK(binlog_transmit, transmit_stop, (thd, flags)); /* Exclude iteration through thread list this is needed for purge_logs() - it will iterate through thread list and update thd->current_linfo->index_file_offset this mutex will make sure that it never tried to update our linfo after we return from this stack frame */ mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = 0; mysql_mutex_unlock(&LOCK_thread_count); if (file >= 0) mysql_file_close(file, MYF(MY_WME)); thd->variables.max_allowed_packet= old_max_allowed_packet; my_message(my_errno, error_text, MYF(0)); DBUG_VOID_RETURN; } /** Execute a START SLAVE statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object for the slave's IO thread. @param net_report If true, saves the exit status into thd->stmt_da. @retval 0 success @retval 1 error */ int start_slave(THD* thd , Master_info* mi, bool net_report) { int slave_errno= 0; int thread_mask; DBUG_ENTER("start_slave"); if (check_access(thd, SUPER_ACL, any_db, NULL, NULL, 0, 0)) DBUG_RETURN(1); lock_slave_threads(mi); // this allows us to cleanly read slave_running // Get a mask of _stopped_ threads init_thread_mask(&thread_mask,mi,1 /* inverse */); /* Below we will start all stopped threads. But if the user wants to start only one thread, do as if the other thread was running (as we don't wan't to touch the other thread), so set the bit to 0 for the other thread */ if (thd->lex->slave_thd_opt) thread_mask&= thd->lex->slave_thd_opt; if (thread_mask) //some threads are stopped, start them { if (init_master_info(mi,master_info_file,relay_log_info_file, 0, thread_mask)) slave_errno=ER_MASTER_INFO; else if (server_id_supplied && *mi->host) { /* If we will start SQL thread we will care about UNTIL options If not and they are specified we will ignore them and warn user about this fact. */ if (thread_mask & SLAVE_SQL) { mysql_mutex_lock(&mi->rli.data_lock); if (thd->lex->mi.pos) { if (thd->lex->mi.relay_log_pos) slave_errno=ER_BAD_SLAVE_UNTIL_COND; mi->rli.until_condition= Relay_log_info::UNTIL_MASTER_POS; mi->rli.until_log_pos= thd->lex->mi.pos; /* We don't check thd->lex->mi.log_file_name for NULL here since it is checked in sql_yacc.yy */ strmake(mi->rli.until_log_name, thd->lex->mi.log_file_name, sizeof(mi->rli.until_log_name)-1); } else if (thd->lex->mi.relay_log_pos) { if (thd->lex->mi.pos) slave_errno=ER_BAD_SLAVE_UNTIL_COND; mi->rli.until_condition= Relay_log_info::UNTIL_RELAY_POS; mi->rli.until_log_pos= thd->lex->mi.relay_log_pos; strmake(mi->rli.until_log_name, thd->lex->mi.relay_log_name, sizeof(mi->rli.until_log_name)-1); } else mi->rli.clear_until_condition(); if (mi->rli.until_condition != Relay_log_info::UNTIL_NONE) { /* Preparing members for effective until condition checking */ const char *p= fn_ext(mi->rli.until_log_name); char *p_end; if (*p) { //p points to '.' mi->rli.until_log_name_extension= strtoul(++p,&p_end, 10); /* p_end points to the first invalid character. If it equals to p, no digits were found, error. If it contains '\0' it means conversion went ok. */ if (p_end==p || *p_end) slave_errno=ER_BAD_SLAVE_UNTIL_COND; } else slave_errno=ER_BAD_SLAVE_UNTIL_COND; /* mark the cached result of the UNTIL comparison as "undefined" */ mi->rli.until_log_names_cmp_result= Relay_log_info::UNTIL_LOG_NAMES_CMP_UNKNOWN; /* Issuing warning then started without --skip-slave-start */ if (!opt_skip_slave_start) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_MISSING_SKIP_SLAVE, ER(ER_MISSING_SKIP_SLAVE)); } mysql_mutex_unlock(&mi->rli.data_lock); } else if (thd->lex->mi.pos || thd->lex->mi.relay_log_pos) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_UNTIL_COND_IGNORED, ER(ER_UNTIL_COND_IGNORED)); if (!slave_errno) slave_errno = start_slave_threads(0 /*no mutex */, 1 /* wait for start */, mi, master_info_file,relay_log_info_file, thread_mask); } else slave_errno = ER_BAD_SLAVE; } else { /* no error if all threads are already started, only a warning */ push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_SLAVE_WAS_RUNNING, ER(ER_SLAVE_WAS_RUNNING)); } unlock_slave_threads(mi); if (slave_errno) { if (net_report) my_message(slave_errno, ER(slave_errno), MYF(0)); DBUG_RETURN(1); } else if (net_report) my_ok(thd); DBUG_RETURN(0); } /** Execute a STOP SLAVE statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object for the slave's IO thread. @param net_report If true, saves the exit status into thd->stmt_da. @retval 0 success @retval 1 error */ int stop_slave(THD* thd, Master_info* mi, bool net_report ) { DBUG_ENTER("stop_slave"); int slave_errno; if (!thd) thd = current_thd; if (check_access(thd, SUPER_ACL, any_db, NULL, NULL, 0, 0)) DBUG_RETURN(1); thd_proc_info(thd, "Killing slave"); int thread_mask; lock_slave_threads(mi); // Get a mask of _running_ threads init_thread_mask(&thread_mask,mi,0 /* not inverse*/); /* Below we will stop all running threads. But if the user wants to stop only one thread, do as if the other thread was stopped (as we don't wan't to touch the other thread), so set the bit to 0 for the other thread */ if (thd->lex->slave_thd_opt) thread_mask &= thd->lex->slave_thd_opt; if (thread_mask) { slave_errno= terminate_slave_threads(mi,thread_mask, 1 /*skip lock */); } else { //no error if both threads are already stopped, only a warning slave_errno= 0; push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_SLAVE_WAS_NOT_RUNNING, ER(ER_SLAVE_WAS_NOT_RUNNING)); } unlock_slave_threads(mi); thd_proc_info(thd, 0); if (slave_errno) { if (net_report) my_message(slave_errno, ER(slave_errno), MYF(0)); DBUG_RETURN(1); } else if (net_report) my_ok(thd); DBUG_RETURN(0); } /** Execute a RESET SLAVE statement. @param thd Pointer to THD object of the client thread executing the statement. @param mi Pointer to Master_info object for the slave. @retval 0 success @retval 1 error */ int reset_slave(THD *thd, Master_info* mi) { MY_STAT stat_area; char fname[FN_REFLEN]; int thread_mask= 0, error= 0; uint sql_errno=ER_UNKNOWN_ERROR; const char* errmsg= "Unknown error occured while reseting slave"; DBUG_ENTER("reset_slave"); lock_slave_threads(mi); init_thread_mask(&thread_mask,mi,0 /* not inverse */); if (thread_mask) // We refuse if any slave thread is running { sql_errno= ER_SLAVE_MUST_STOP; error=1; goto err; } ha_reset_slave(thd); // delete relay logs, clear relay log coordinates if ((error= purge_relay_logs(&mi->rli, thd, 1 /* just reset */, &errmsg))) { sql_errno= ER_RELAY_LOG_FAIL; goto err; } /* Clear master's log coordinates and associated information */ mi->clear_in_memory_info(thd->lex->reset_slave_info.all); /* Reset errors (the idea is that we forget about the old master). */ mi->clear_error(); mi->rli.clear_error(); mi->rli.clear_until_condition(); // close master_info_file, relay_log_info_file, set mi->inited=rli->inited=0 end_master_info(mi); // and delete these two files fn_format(fname, master_info_file, mysql_data_home, "", 4+32); if (mysql_file_stat(key_file_master_info, fname, &stat_area, MYF(0)) && mysql_file_delete(key_file_master_info, fname, MYF(MY_WME))) { error=1; goto err; } // delete relay_log_info_file fn_format(fname, relay_log_info_file, mysql_data_home, "", 4+32); if (mysql_file_stat(key_file_relay_log_info, fname, &stat_area, MYF(0)) && mysql_file_delete(key_file_relay_log_info, fname, MYF(MY_WME))) { error=1; goto err; } RUN_HOOK(binlog_relay_io, after_reset_slave, (thd, mi)); err: unlock_slave_threads(mi); if (error) my_error(sql_errno, MYF(0), errmsg); DBUG_RETURN(error); } /* Kill all Binlog_dump threads which previously talked to the same slave ("same" means with the same server id). Indeed, if the slave stops, if the Binlog_dump thread is waiting (mysql_cond_wait) for binlog update, then it will keep existing until a query is written to the binlog. If the master is idle, then this could last long, and if the slave reconnects, we could have 2 Binlog_dump threads in SHOW PROCESSLIST, until a query is written to the binlog. To avoid this, when the slave reconnects and sends COM_BINLOG_DUMP, the master kills any existing thread with the slave's server id (if this id is not zero; it will be true for real slaves, but false for mysqlbinlog when it sends COM_BINLOG_DUMP to get a remote binlog dump). SYNOPSIS kill_zombie_dump_threads() slave_server_id the slave's server id */ void kill_zombie_dump_threads(uint32 slave_server_id) { mysql_mutex_lock(&LOCK_thread_count); I_List_iterator<THD> it(threads); THD *tmp; while ((tmp=it++)) { if (tmp->command == COM_BINLOG_DUMP && tmp->server_id == slave_server_id) { mysql_mutex_lock(&tmp->LOCK_thd_data); // Lock from delete break; } } mysql_mutex_unlock(&LOCK_thread_count); if (tmp) { /* Here we do not call kill_one_thread() as it will be slow because it will iterate through the list again. We just to do kill the thread ourselves. */ tmp->awake(THD::KILL_QUERY); mysql_mutex_unlock(&tmp->LOCK_thd_data); } } /** Execute a CHANGE MASTER statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object belonging to the slave's IO thread. @retval FALSE success @retval TRUE error */ bool change_master(THD* thd, Master_info* mi) { int thread_mask; const char* errmsg= 0; bool need_relay_log_purge= 1; bool ret= FALSE; char saved_host[HOSTNAME_LENGTH + 1]; uint saved_port; char saved_log_name[FN_REFLEN]; my_off_t saved_log_pos; DBUG_ENTER("change_master"); lock_slave_threads(mi); init_thread_mask(&thread_mask,mi,0 /*not inverse*/); LEX_MASTER_INFO* lex_mi= &thd->lex->mi; if (thread_mask) // We refuse if any slave thread is running { my_message(ER_SLAVE_MUST_STOP, ER(ER_SLAVE_MUST_STOP), MYF(0)); ret= TRUE; goto err; } thd_proc_info(thd, "Changing master"); /* We need to check if there is an empty master_host. Otherwise change master succeeds, a master.info file is created containing empty master_host string and when issuing: start slave; an error is thrown stating that the server is not configured as slave. (See BUG#28796). */ if(lex_mi->host && !*lex_mi->host) { my_error(ER_WRONG_ARGUMENTS, MYF(0), "MASTER_HOST"); unlock_slave_threads(mi); DBUG_RETURN(TRUE); } // TODO: see if needs re-write if (init_master_info(mi, master_info_file, relay_log_info_file, 0, thread_mask)) { my_message(ER_MASTER_INFO, ER(ER_MASTER_INFO), MYF(0)); ret= TRUE; goto err; } /* Data lock not needed since we have already stopped the running threads, and we have the hold on the run locks which will keep all threads that could possibly modify the data structures from running */ /* Before processing the command, save the previous state. */ strmake(saved_host, mi->host, HOSTNAME_LENGTH); saved_port= mi->port; strmake(saved_log_name, mi->master_log_name, FN_REFLEN - 1); saved_log_pos= mi->master_log_pos; /* If the user specified host or port without binlog or position, reset binlog's name to FIRST and position to 4. */ if ((lex_mi->host || lex_mi->port) && !lex_mi->log_file_name && !lex_mi->pos) { mi->master_log_name[0] = 0; mi->master_log_pos= BIN_LOG_HEADER_SIZE; } if (lex_mi->log_file_name) strmake(mi->master_log_name, lex_mi->log_file_name, sizeof(mi->master_log_name)-1); if (lex_mi->pos) { mi->master_log_pos= lex_mi->pos; } DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->master_log_pos)); if (lex_mi->host) strmake(mi->host, lex_mi->host, sizeof(mi->host)-1); if (lex_mi->user) strmake(mi->user, lex_mi->user, sizeof(mi->user)-1); if (lex_mi->password) strmake(mi->password, lex_mi->password, sizeof(mi->password)-1); if (lex_mi->port) mi->port = lex_mi->port; if (lex_mi->connect_retry) mi->connect_retry = lex_mi->connect_retry; if (lex_mi->heartbeat_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->heartbeat_period = lex_mi->heartbeat_period; else mi->heartbeat_period= (float) min(SLAVE_MAX_HEARTBEAT_PERIOD, (slave_net_timeout/2.0)); mi->received_heartbeats= LL(0); // counter lives until master is CHANGEd /* reset the last time server_id list if the current CHANGE MASTER is mentioning IGNORE_SERVER_IDS= (...) */ if (lex_mi->repl_ignore_server_ids_opt == LEX_MASTER_INFO::LEX_MI_ENABLE) reset_dynamic(&mi->ignore_server_ids); for (uint i= 0; i < lex_mi->repl_ignore_server_ids.elements; i++) { ulong s_id; get_dynamic(&lex_mi->repl_ignore_server_ids, (uchar*) &s_id, i); if (s_id == ::server_id && replicate_same_server_id) { my_error(ER_SLAVE_IGNORE_SERVER_IDS, MYF(0), static_cast<int>(s_id)); ret= TRUE; goto err; } else { if (bsearch((const ulong *) &s_id, mi->ignore_server_ids.buffer, mi->ignore_server_ids.elements, sizeof(ulong), (int (*) (const void*, const void*)) change_master_server_id_cmp) == NULL) insert_dynamic(&mi->ignore_server_ids, (uchar*) &s_id); } } sort_dynamic(&mi->ignore_server_ids, (qsort_cmp) change_master_server_id_cmp); if (lex_mi->ssl != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->ssl= (lex_mi->ssl == LEX_MASTER_INFO::LEX_MI_ENABLE); if (lex_mi->ssl_verify_server_cert != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->ssl_verify_server_cert= (lex_mi->ssl_verify_server_cert == LEX_MASTER_INFO::LEX_MI_ENABLE); if (lex_mi->ssl_ca) strmake(mi->ssl_ca, lex_mi->ssl_ca, sizeof(mi->ssl_ca)-1); if (lex_mi->ssl_capath) strmake(mi->ssl_capath, lex_mi->ssl_capath, sizeof(mi->ssl_capath)-1); if (lex_mi->ssl_cert) strmake(mi->ssl_cert, lex_mi->ssl_cert, sizeof(mi->ssl_cert)-1); if (lex_mi->ssl_cipher) strmake(mi->ssl_cipher, lex_mi->ssl_cipher, sizeof(mi->ssl_cipher)-1); if (lex_mi->ssl_key) strmake(mi->ssl_key, lex_mi->ssl_key, sizeof(mi->ssl_key)-1); #ifndef HAVE_OPENSSL if (lex_mi->ssl || lex_mi->ssl_ca || lex_mi->ssl_capath || lex_mi->ssl_cert || lex_mi->ssl_cipher || lex_mi->ssl_key || lex_mi->ssl_verify_server_cert ) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_SLAVE_IGNORED_SSL_PARAMS, ER(ER_SLAVE_IGNORED_SSL_PARAMS)); #endif if (lex_mi->relay_log_name) { need_relay_log_purge= 0; char relay_log_name[FN_REFLEN]; mi->rli.relay_log.make_log_name(relay_log_name, lex_mi->relay_log_name); strmake(mi->rli.group_relay_log_name, relay_log_name, sizeof(mi->rli.group_relay_log_name)-1); strmake(mi->rli.event_relay_log_name, relay_log_name, sizeof(mi->rli.event_relay_log_name)-1); } if (lex_mi->relay_log_pos) { need_relay_log_purge= 0; mi->rli.group_relay_log_pos= mi->rli.event_relay_log_pos= lex_mi->relay_log_pos; } /* If user did specify neither host nor port nor any log name nor any log pos, i.e. he specified only user/password/master_connect_retry, he probably wants replication to resume from where it had left, i.e. from the coordinates of the **SQL** thread (imagine the case where the I/O is ahead of the SQL; restarting from the coordinates of the I/O would lose some events which is probably unwanted when you are just doing minor changes like changing master_connect_retry). A side-effect is that if only the I/O thread was started, this thread may restart from ''/4 after the CHANGE MASTER. That's a minor problem (it is a much more unlikely situation than the one we are fixing here). Note: coordinates of the SQL thread must be read here, before the 'if (need_relay_log_purge)' block which resets them. */ if (!lex_mi->host && !lex_mi->port && !lex_mi->log_file_name && !lex_mi->pos && need_relay_log_purge) { /* Sometimes mi->rli.master_log_pos == 0 (it happens when the SQL thread is not initialized), so we use a max(). What happens to mi->rli.master_log_pos during the initialization stages of replication is not 100% clear, so we guard against problems using max(). */ mi->master_log_pos = max(BIN_LOG_HEADER_SIZE, mi->rli.group_master_log_pos); strmake(mi->master_log_name, mi->rli.group_master_log_name, sizeof(mi->master_log_name)-1); } /* Relay log's IO_CACHE may not be inited, if rli->inited==0 (server was never a slave before). */ if (flush_master_info(mi, FALSE, FALSE)) { my_error(ER_RELAY_LOG_INIT, MYF(0), "Failed to flush master info file"); ret= TRUE; goto err; } if (need_relay_log_purge) { relay_log_purge= 1; thd_proc_info(thd, "Purging old relay logs"); if (purge_relay_logs(&mi->rli, thd, 0 /* not only reset, but also reinit */, &errmsg)) { my_error(ER_RELAY_LOG_FAIL, MYF(0), errmsg); ret= TRUE; goto err; } } else { const char* msg; relay_log_purge= 0; /* Relay log is already initialized */ if (init_relay_log_pos(&mi->rli, mi->rli.group_relay_log_name, mi->rli.group_relay_log_pos, 0 /*no data lock*/, &msg, 0)) { my_error(ER_RELAY_LOG_INIT, MYF(0), msg); ret= TRUE; goto err; } } /* Coordinates in rli were spoilt by the 'if (need_relay_log_purge)' block, so restore them to good values. If we left them to ''/0, that would work; but that would fail in the case of 2 successive CHANGE MASTER (without a START SLAVE in between): because first one would set the coords in mi to the good values of those in rli, the set those in rli to ''/0, then second CHANGE MASTER would set the coords in mi to those of rli, i.e. to ''/0: we have lost all copies of the original good coordinates. That's why we always save good coords in rli. */ mi->rli.group_master_log_pos= mi->master_log_pos; DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->master_log_pos)); strmake(mi->rli.group_master_log_name,mi->master_log_name, sizeof(mi->rli.group_master_log_name)-1); if (!mi->rli.group_master_log_name[0]) // uninitialized case mi->rli.group_master_log_pos=0; mysql_mutex_lock(&mi->rli.data_lock); mi->rli.abort_pos_wait++; /* for MASTER_POS_WAIT() to abort */ /* Clear the errors, for a clean start */ mi->rli.clear_error(); mi->rli.clear_until_condition(); sql_print_information("'CHANGE MASTER TO executed'. " "Previous state master_host='%s', master_port='%u', master_log_file='%s', " "master_log_pos='%ld'. " "New state master_host='%s', master_port='%u', master_log_file='%s', " "master_log_pos='%ld'.", saved_host, saved_port, saved_log_name, (ulong) saved_log_pos, mi->host, mi->port, mi->master_log_name, (ulong) mi->master_log_pos); /* If we don't write new coordinates to disk now, then old will remain in relay-log.info until START SLAVE is issued; but if mysqld is shutdown before START SLAVE, then old will remain in relay-log.info, and will be the in-memory value at restart (thus causing errors, as the old relay log does not exist anymore). */ flush_relay_log_info(&mi->rli); mysql_cond_broadcast(&mi->data_cond); mysql_mutex_unlock(&mi->rli.data_lock); err: unlock_slave_threads(mi); thd_proc_info(thd, 0); if (ret == FALSE) my_ok(thd); DBUG_RETURN(ret); } /** Execute a RESET MASTER statement. @param thd Pointer to THD object of the client thread executing the statement. @retval 0 success @retval 1 error */ int reset_master(THD* thd) { if (!mysql_bin_log.is_open()) { my_message(ER_FLUSH_MASTER_BINLOG_CLOSED, ER(ER_FLUSH_MASTER_BINLOG_CLOSED), MYF(ME_BELL+ME_WAITTANG)); return 1; } if (mysql_bin_log.reset_logs(thd)) return 1; RUN_HOOK(binlog_transmit, after_reset_master, (thd, 0 /* flags */)); return 0; } /** Execute a SHOW BINLOG EVENTS statement. @param thd Pointer to THD object for the client thread executing the statement. @retval FALSE success @retval TRUE failure */ bool mysql_show_binlog_events(THD* thd) { Protocol *protocol= thd->protocol; List<Item> field_list; const char *errmsg = 0; bool ret = TRUE; IO_CACHE log; File file = -1; MYSQL_BIN_LOG *binary_log= NULL; int old_max_allowed_packet= thd->variables.max_allowed_packet; LOG_INFO linfo; DBUG_ENTER("mysql_show_binlog_events"); Log_event::init_show_field_list(&field_list); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); Format_description_log_event *description_event= new Format_description_log_event(3); /* MySQL 4.0 by default */ DBUG_ASSERT(thd->lex->sql_command == SQLCOM_SHOW_BINLOG_EVENTS || thd->lex->sql_command == SQLCOM_SHOW_RELAYLOG_EVENTS); /* select wich binary log to use: binlog or relay */ if ( thd->lex->sql_command == SQLCOM_SHOW_BINLOG_EVENTS ) { /* Wait for handlers to insert any pending information into the binlog. For e.g. ndb which updates the binlog asynchronously this is needed so that the uses sees all its own commands in the binlog */ ha_binlog_wait(thd); binary_log= &mysql_bin_log; } else /* showing relay log contents */ { if (!active_mi) DBUG_RETURN(TRUE); binary_log= &(active_mi->rli.relay_log); } if (binary_log->is_open()) { LEX_MASTER_INFO *lex_mi= &thd->lex->mi; SELECT_LEX_UNIT *unit= &thd->lex->unit; ha_rows event_count, limit_start, limit_end; my_off_t pos = max(BIN_LOG_HEADER_SIZE, lex_mi->pos); // user-friendly char search_file_name[FN_REFLEN], *name; const char *log_file_name = lex_mi->log_file_name; mysql_mutex_t *log_lock = binary_log->get_log_lock(); Log_event* ev; unit->set_limit(thd->lex->current_select); limit_start= unit->offset_limit_cnt; limit_end= unit->select_limit_cnt; name= search_file_name; if (log_file_name) binary_log->make_log_name(search_file_name, log_file_name); else name=0; // Find first log linfo.index_file_offset = 0; if (binary_log->find_log_pos(&linfo, name, 1)) { errmsg = "Could not find target log"; goto err; } mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = &linfo; mysql_mutex_unlock(&LOCK_thread_count); if ((file=open_binlog(&log, linfo.log_file_name, &errmsg)) < 0) goto err; /* to account binlog event header size */ thd->variables.max_allowed_packet += MAX_LOG_EVENT_HEADER; mysql_mutex_lock(log_lock); /* open_binlog() sought to position 4. Read the first event in case it's a Format_description_log_event, to know the format. If there's no such event, we are 3.23 or 4.x. This code, like before, can't read 3.23 binlogs. This code will fail on a mixed relay log (one which has Format_desc then Rotate then Format_desc). */ ev= Log_event::read_log_event(&log, (mysql_mutex_t*)0, description_event); if (ev) { if (ev->get_type_code() == FORMAT_DESCRIPTION_EVENT) { delete description_event; description_event= (Format_description_log_event*) ev; } else delete ev; } my_b_seek(&log, pos); if (!description_event->is_valid()) { errmsg="Invalid Format_description event; could be out of memory"; goto err; } for (event_count = 0; (ev = Log_event::read_log_event(&log, (mysql_mutex_t*) 0, description_event)); ) { if (event_count >= limit_start && ev->net_send(protocol, linfo.log_file_name, pos)) { errmsg = "Net error"; delete ev; mysql_mutex_unlock(log_lock); goto err; } pos = my_b_tell(&log); delete ev; if (++event_count >= limit_end) break; } if (event_count < limit_end && log.error) { errmsg = "Wrong offset or I/O error"; mysql_mutex_unlock(log_lock); goto err; } mysql_mutex_unlock(log_lock); } // Check that linfo is still on the function scope. DEBUG_SYNC(thd, "after_show_binlog_events"); ret= FALSE; err: delete description_event; if (file >= 0) { end_io_cache(&log); mysql_file_close(file, MYF(MY_WME)); } if (errmsg) my_error(ER_ERROR_WHEN_EXECUTING_COMMAND, MYF(0), "SHOW BINLOG EVENTS", errmsg); else my_eof(thd); mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = 0; mysql_mutex_unlock(&LOCK_thread_count); thd->variables.max_allowed_packet= old_max_allowed_packet; DBUG_RETURN(ret); } /** Execute a SHOW MASTER STATUS statement. @param thd Pointer to THD object for the client thread executing the statement. @retval FALSE success @retval TRUE failure */ bool show_binlog_info(THD* thd) { Protocol *protocol= thd->protocol; DBUG_ENTER("show_binlog_info"); List<Item> field_list; field_list.push_back(new Item_empty_string("File", FN_REFLEN)); field_list.push_back(new Item_return_int("Position",20, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_empty_string("Binlog_Do_DB",255)); field_list.push_back(new Item_empty_string("Binlog_Ignore_DB",255)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); protocol->prepare_for_resend(); if (mysql_bin_log.is_open()) { LOG_INFO li; mysql_bin_log.get_current_log(&li); int dir_len = dirname_length(li.log_file_name); protocol->store(li.log_file_name + dir_len, &my_charset_bin); protocol->store((ulonglong) li.pos); protocol->store(binlog_filter->get_do_db()); protocol->store(binlog_filter->get_ignore_db()); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); } /** Execute a SHOW BINARY LOGS statement. @param thd Pointer to THD object for the client thread executing the statement. @retval FALSE success @retval TRUE failure */ bool show_binlogs(THD* thd) { IO_CACHE *index_file; LOG_INFO cur; File file; char fname[FN_REFLEN]; List<Item> field_list; uint length; int cur_dir_len; Protocol *protocol= thd->protocol; DBUG_ENTER("show_binlogs"); if (!mysql_bin_log.is_open()) { my_error(ER_NO_BINARY_LOGGING, MYF(0)); DBUG_RETURN(TRUE); } field_list.push_back(new Item_empty_string("Log_name", 255)); field_list.push_back(new Item_return_int("File_size", 20, MYSQL_TYPE_LONGLONG)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); mysql_mutex_lock(mysql_bin_log.get_log_lock()); mysql_bin_log.lock_index(); index_file=mysql_bin_log.get_index_file(); mysql_bin_log.raw_get_current_log(&cur); // dont take mutex mysql_mutex_unlock(mysql_bin_log.get_log_lock()); // lockdep, OK cur_dir_len= dirname_length(cur.log_file_name); reinit_io_cache(index_file, READ_CACHE, (my_off_t) 0, 0, 0); /* The file ends with EOF or empty line */ while ((length=my_b_gets(index_file, fname, sizeof(fname))) > 1) { int dir_len; ulonglong file_length= 0; // Length if open fails fname[--length] = '\0'; // remove the newline protocol->prepare_for_resend(); dir_len= dirname_length(fname); length-= dir_len; protocol->store(fname + dir_len, length, &my_charset_bin); if (!(strncmp(fname+dir_len, cur.log_file_name+cur_dir_len, length))) file_length= cur.pos; /* The active log, use the active position */ else { /* this is an old log, open it and find the size */ if ((file= mysql_file_open(key_file_binlog, fname, O_RDONLY | O_SHARE | O_BINARY, MYF(0))) >= 0) { file_length= (ulonglong) mysql_file_seek(file, 0L, MY_SEEK_END, MYF(0)); mysql_file_close(file, MYF(0)); } } protocol->store(file_length); if (protocol->write()) goto err; } if(index_file->error == -1) goto err; mysql_bin_log.unlock_index(); my_eof(thd); DBUG_RETURN(FALSE); err: mysql_bin_log.unlock_index(); DBUG_RETURN(TRUE); } /** Load data's io cache specific hook to be executed before a chunk of data is being read into the cache's buffer The fuction instantianates and writes into the binlog replication events along LOAD DATA processing. @param file pointer to io-cache @retval 0 success @retval 1 failure */ int log_loaded_block(IO_CACHE* file) { DBUG_ENTER("log_loaded_block"); LOAD_FILE_INFO *lf_info; uint block_len; /* buffer contains position where we started last read */ uchar* buffer= (uchar*) my_b_get_buffer_start(file); uint max_event_size= current_thd->variables.max_allowed_packet; lf_info= (LOAD_FILE_INFO*) file->arg; if (lf_info->thd->is_current_stmt_binlog_format_row()) DBUG_RETURN(0); if (lf_info->last_pos_in_file != HA_POS_ERROR && lf_info->last_pos_in_file >= my_b_get_pos_in_file(file)) DBUG_RETURN(0); for (block_len= (uint) (my_b_get_bytes_in_buffer(file)); block_len > 0; buffer += min(block_len, max_event_size), block_len -= min(block_len, max_event_size)) { lf_info->last_pos_in_file= my_b_get_pos_in_file(file); if (lf_info->wrote_create_file) { Append_block_log_event a(lf_info->thd, lf_info->thd->db, buffer, min(block_len, max_event_size), lf_info->log_delayed); if (mysql_bin_log.write(&a)) DBUG_RETURN(1); } else { Begin_load_query_log_event b(lf_info->thd, lf_info->thd->db, buffer, min(block_len, max_event_size), lf_info->log_delayed); if (mysql_bin_log.write(&b)) DBUG_RETURN(1); lf_info->wrote_create_file= 1; } } DBUG_RETURN(0); } #endif /* HAVE_REPLICATION */ Bug#17641586 INCORRECTLY PRINTED BINLOG DUMP INFORMATION Problem: When log_warnings is greater than 1, master prints binlog dump thread information in mysqld.1.err file. The information contains slave server id, binlog file and binlog position. The slave server id is uint32 and the print format was wrongly specifified (%d instead of %u). Hence a server id which is more than 2 billion is getting printed with a negative value. Eg: Start binlog_dump to slave_server(-1340259414), pos(mysql-bin.001663, 325187493) Fix: Changed the uint32 format to %u. /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sql_priv.h" #include "unireg.h" #include "sql_parse.h" // check_access #ifdef HAVE_REPLICATION #include "rpl_mi.h" #include "sql_repl.h" #include "sql_acl.h" // SUPER_ACL #include "log_event.h" #include "rpl_filter.h" #include <my_dir.h> #include "rpl_handler.h" #include "debug_sync.h" int max_binlog_dump_events = 0; // unlimited my_bool opt_sporadic_binlog_dump_fail = 0; #ifndef DBUG_OFF static int binlog_dump_count = 0; #endif /** a copy of active_mi->rli->slave_skip_counter, for showing in SHOW VARIABLES, INFORMATION_SCHEMA.GLOBAL_VARIABLES and @@sql_slave_skip_counter without taking all the mutexes needed to access active_mi->rli->slave_skip_counter properly. */ uint sql_slave_skip_counter; /* fake_rotate_event() builds a fake (=which does not exist physically in any binlog) Rotate event, which contains the name of the binlog we are going to send to the slave (because the slave may not know it if it just asked for MASTER_LOG_FILE='', MASTER_LOG_POS=4). < 4.0.14, fake_rotate_event() was called only if the requested pos was 4. After this version we always call it, so that a 3.23.58 slave can rely on it to detect if the master is 4.0 (and stop) (the _fake_ Rotate event has zeros in the good positions which, by chance, make it possible for the 3.23 slave to detect that this event is unexpected) (this is luck which happens because the master and slave disagree on the size of the header of Log_event). Relying on the event length of the Rotate event instead of these well-placed zeros was not possible as Rotate events have a variable-length part. */ static int fake_rotate_event(NET* net, String* packet, char* log_file_name, ulonglong position, const char** errmsg) { DBUG_ENTER("fake_rotate_event"); char header[LOG_EVENT_HEADER_LEN], buf[ROTATE_HEADER_LEN+100]; /* 'when' (the timestamp) is set to 0 so that slave could distinguish between real and fake Rotate events (if necessary) */ memset(header, 0, 4); header[EVENT_TYPE_OFFSET] = ROTATE_EVENT; char* p = log_file_name+dirname_length(log_file_name); uint ident_len = (uint) strlen(p); ulong event_len = ident_len + LOG_EVENT_HEADER_LEN + ROTATE_HEADER_LEN; int4store(header + SERVER_ID_OFFSET, server_id); int4store(header + EVENT_LEN_OFFSET, event_len); int2store(header + FLAGS_OFFSET, LOG_EVENT_ARTIFICIAL_F); // TODO: check what problems this may cause and fix them int4store(header + LOG_POS_OFFSET, 0); packet->append(header, sizeof(header)); int8store(buf+R_POS_OFFSET,position); packet->append(buf, ROTATE_HEADER_LEN); packet->append(p,ident_len); if (my_net_write(net, (uchar*) packet->ptr(), packet->length())) { *errmsg = "failed on my_net_write()"; DBUG_RETURN(-1); } DBUG_RETURN(0); } /* Reset thread transmit packet buffer for event sending This function allocates header bytes for event transmission, and should be called before store the event data to the packet buffer. */ static int reset_transmit_packet(THD *thd, ushort flags, ulong *ev_offset, const char **errmsg) { int ret= 0; String *packet= &thd->packet; /* reserve and set default header */ packet->length(0); packet->set("\0", 1, &my_charset_bin); if (RUN_HOOK(binlog_transmit, reserve_header, (thd, flags, packet))) { *errmsg= "Failed to run hook 'reserve_header'"; my_errno= ER_UNKNOWN_ERROR; ret= 1; } *ev_offset= packet->length(); return ret; } static int send_file(THD *thd) { NET* net = &thd->net; int fd = -1, error = 1; size_t bytes; char fname[FN_REFLEN+1]; const char *errmsg = 0; int old_timeout; unsigned long packet_len; uchar buf[IO_SIZE]; // It's safe to alloc this DBUG_ENTER("send_file"); /* The client might be slow loading the data, give him wait_timeout to do the job */ old_timeout= net->read_timeout; my_net_set_read_timeout(net, thd->variables.net_wait_timeout); /* We need net_flush here because the client will not know it needs to send us the file name until it has processed the load event entry */ if (net_flush(net) || (packet_len = my_net_read(net)) == packet_error) { errmsg = "while reading file name"; goto err; } // terminate with \0 for fn_format *((char*)net->read_pos + packet_len) = 0; fn_format(fname, (char*) net->read_pos + 1, "", "", 4); // this is needed to make replicate-ignore-db if (!strcmp(fname,"/dev/null")) goto end; if ((fd= mysql_file_open(key_file_send_file, fname, O_RDONLY, MYF(0))) < 0) { errmsg = "on open of file"; goto err; } while ((long) (bytes= mysql_file_read(fd, buf, IO_SIZE, MYF(0))) > 0) { if (my_net_write(net, buf, bytes)) { errmsg = "while writing data to client"; goto err; } } end: if (my_net_write(net, (uchar*) "", 0) || net_flush(net) || (my_net_read(net) == packet_error)) { errmsg = "while negotiating file transfer close"; goto err; } error = 0; err: my_net_set_read_timeout(net, old_timeout); if (fd >= 0) mysql_file_close(fd, MYF(0)); if (errmsg) { sql_print_error("Failed in send_file() %s", errmsg); DBUG_PRINT("error", ("%s", errmsg)); } DBUG_RETURN(error); } /* Adjust the position pointer in the binary log file for all running slaves SYNOPSIS adjust_linfo_offsets() purge_offset Number of bytes removed from start of log index file NOTES - This is called when doing a PURGE when we delete lines from the index log file REQUIREMENTS - Before calling this function, we have to ensure that no threads are using any binary log file before purge_offset.a TODO - Inform the slave threads that they should sync the position in the binary log file with flush_relay_log_info. Now they sync is done for next read. */ void adjust_linfo_offsets(my_off_t purge_offset) { THD *tmp; mysql_mutex_lock(&LOCK_thread_count); I_List_iterator<THD> it(threads); while ((tmp=it++)) { LOG_INFO* linfo; if ((linfo = tmp->current_linfo)) { mysql_mutex_lock(&linfo->lock); /* Index file offset can be less that purge offset only if we just started reading the index file. In that case we have nothing to adjust */ if (linfo->index_file_offset < purge_offset) linfo->fatal = (linfo->index_file_offset != 0); else linfo->index_file_offset -= purge_offset; mysql_mutex_unlock(&linfo->lock); } } mysql_mutex_unlock(&LOCK_thread_count); } bool log_in_use(const char* log_name) { size_t log_name_len = strlen(log_name) + 1; THD *tmp; bool result = 0; mysql_mutex_lock(&LOCK_thread_count); I_List_iterator<THD> it(threads); while ((tmp=it++)) { LOG_INFO* linfo; if ((linfo = tmp->current_linfo)) { mysql_mutex_lock(&linfo->lock); result = !memcmp(log_name, linfo->log_file_name, log_name_len); mysql_mutex_unlock(&linfo->lock); if (result) break; } } mysql_mutex_unlock(&LOCK_thread_count); return result; } bool purge_error_message(THD* thd, int res) { uint errcode; if ((errcode= purge_log_get_error_code(res)) != 0) { my_message(errcode, ER(errcode), MYF(0)); return TRUE; } my_ok(thd); return FALSE; } /** Execute a PURGE BINARY LOGS TO <log> command. @param thd Pointer to THD object for the client thread executing the statement. @param to_log Name of the last log to purge. @retval FALSE success @retval TRUE failure */ bool purge_master_logs(THD* thd, const char* to_log) { char search_file_name[FN_REFLEN]; if (!mysql_bin_log.is_open()) { my_ok(thd); return FALSE; } mysql_bin_log.make_log_name(search_file_name, to_log); return purge_error_message(thd, mysql_bin_log.purge_logs(search_file_name, 0, 1, 1, NULL)); } /** Execute a PURGE BINARY LOGS BEFORE <date> command. @param thd Pointer to THD object for the client thread executing the statement. @param purge_time Date before which logs should be purged. @retval FALSE success @retval TRUE failure */ bool purge_master_logs_before_date(THD* thd, time_t purge_time) { if (!mysql_bin_log.is_open()) { my_ok(thd); return 0; } return purge_error_message(thd, mysql_bin_log.purge_logs_before_date(purge_time)); } int test_for_non_eof_log_read_errors(int error, const char **errmsg) { if (error == LOG_READ_EOF) return 0; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; switch (error) { case LOG_READ_BOGUS: *errmsg = "bogus data in log event"; break; case LOG_READ_TOO_LARGE: *errmsg = "log event entry exceeded max_allowed_packet; \ Increase max_allowed_packet on master"; break; case LOG_READ_IO: *errmsg = "I/O error reading log event"; break; case LOG_READ_MEM: *errmsg = "memory allocation failed reading log event"; break; case LOG_READ_TRUNC: *errmsg = "binlog truncated in the middle of event; consider out of disk space on master"; break; default: *errmsg = "unknown error reading log event on the master"; break; } return error; } /** An auxiliary function for calling in mysql_binlog_send to initialize the heartbeat timeout in waiting for a binlogged event. @param[in] thd THD to access a user variable @return heartbeat period an ulonglong of nanoseconds or zero if heartbeat was not demanded by slave */ static ulonglong get_heartbeat_period(THD * thd) { my_bool null_value; LEX_STRING name= { C_STRING_WITH_LEN("master_heartbeat_period")}; user_var_entry *entry= (user_var_entry*) my_hash_search(&thd->user_vars, (uchar*) name.str, name.length); return entry? entry->val_int(&null_value) : 0; } /* Function prepares and sends repliation heartbeat event. @param net net object of THD @param packet buffer to store the heartbeat instance @param event_coordinates binlog file name and position of the last real event master sent from binlog @note Among three essential pieces of heartbeat data Log_event::when is computed locally. The error to send is serious and should force terminating the dump thread. */ static int send_heartbeat_event(NET* net, String* packet, const struct event_coordinates *coord) { DBUG_ENTER("send_heartbeat_event"); char header[LOG_EVENT_HEADER_LEN]; /* 'when' (the timestamp) is set to 0 so that slave could distinguish between real and fake Rotate events (if necessary) */ memset(header, 0, 4); // when header[EVENT_TYPE_OFFSET] = HEARTBEAT_LOG_EVENT; char* p= coord->file_name + dirname_length(coord->file_name); uint ident_len = strlen(p); ulong event_len = ident_len + LOG_EVENT_HEADER_LEN; int4store(header + SERVER_ID_OFFSET, server_id); int4store(header + EVENT_LEN_OFFSET, event_len); int2store(header + FLAGS_OFFSET, 0); int4store(header + LOG_POS_OFFSET, coord->pos); // log_pos packet->append(header, sizeof(header)); packet->append(p, ident_len); // log_file_name if (my_net_write(net, (uchar*) packet->ptr(), packet->length()) || net_flush(net)) { DBUG_RETURN(-1); } DBUG_RETURN(0); } /* TODO: Clean up loop to only have one call to send_file() */ void mysql_binlog_send(THD* thd, char* log_ident, my_off_t pos, ushort flags) { LOG_INFO linfo; char *log_file_name = linfo.log_file_name; char search_file_name[FN_REFLEN], *name; ulong ev_offset; IO_CACHE log; File file = -1; String* packet = &thd->packet; int error; const char *errmsg = "Unknown error"; char error_text[MAX_SLAVE_ERRMSG]; // to be send to slave via my_message() NET* net = &thd->net; mysql_mutex_t *log_lock; mysql_cond_t *log_cond; #ifndef DBUG_OFF int left_events = max_binlog_dump_events; #endif int old_max_allowed_packet= thd->variables.max_allowed_packet; DBUG_ENTER("mysql_binlog_send"); DBUG_PRINT("enter",("log_ident: '%s' pos: %ld", log_ident, (long) pos)); bzero((char*) &log,sizeof(log)); /* heartbeat_period from @master_heartbeat_period user variable */ ulonglong heartbeat_period= get_heartbeat_period(thd); struct timespec heartbeat_buf; struct timespec *heartbeat_ts= NULL; const LOG_POS_COORD start_coord= { log_ident, pos }, *p_start_coord= &start_coord; LOG_POS_COORD coord_buf= { log_file_name, BIN_LOG_HEADER_SIZE }, *p_coord= &coord_buf; if (heartbeat_period != LL(0)) { heartbeat_ts= &heartbeat_buf; set_timespec_nsec(*heartbeat_ts, 0); } if (global_system_variables.log_warnings > 1) sql_print_information("Start binlog_dump to slave_server(%u), pos(%s, %lu)", thd->server_id, log_ident, (ulong)pos); if (RUN_HOOK(binlog_transmit, transmit_start, (thd, flags, log_ident, pos))) { errmsg= "Failed to run hook 'transmit_start'"; my_errno= ER_UNKNOWN_ERROR; goto err; } #ifndef DBUG_OFF if (opt_sporadic_binlog_dump_fail && (binlog_dump_count++ % 2)) { errmsg = "Master failed COM_BINLOG_DUMP to test if slave can recover"; my_errno= ER_UNKNOWN_ERROR; goto err; } #endif if (!mysql_bin_log.is_open()) { errmsg = "Binary log is not open"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } if (!server_id_supplied) { errmsg = "Misconfigured master - server id was not set"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } name=search_file_name; if (log_ident[0]) mysql_bin_log.make_log_name(search_file_name, log_ident); else name=0; // Find first log linfo.index_file_offset = 0; if (mysql_bin_log.find_log_pos(&linfo, name, 1)) { errmsg = "Could not find first log file name in binary log index file"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = &linfo; mysql_mutex_unlock(&LOCK_thread_count); if ((file=open_binlog(&log, log_file_name, &errmsg)) < 0) { my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } if (pos < BIN_LOG_HEADER_SIZE || pos > my_b_filelength(&log)) { errmsg= "Client requested master to start replication from \ impossible position"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } /* reset transmit packet for the fake rotate event below */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; /* Tell the client about the log name with a fake Rotate event; this is needed even if we also send a Format_description_log_event just after, because that event does not contain the binlog's name. Note that as this Rotate event is sent before Format_description_log_event, the slave cannot have any info to understand this event's format, so the header len of Rotate_log_event is FROZEN (so in 5.0 it will have a header shorter than other events except FORMAT_DESCRIPTION_EVENT). Before 4.0.14 we called fake_rotate_event below only if (pos == BIN_LOG_HEADER_SIZE), because if this is false then the slave already knows the binlog's name. Since, we always call fake_rotate_event; if the slave already knew the log's name (ex: CHANGE MASTER TO MASTER_LOG_FILE=...) this is useless but does not harm much. It is nice for 3.23 (>=.58) slaves which test Rotate events to see if the master is 4.0 (then they choose to stop because they can't replicate 4.0); by always calling fake_rotate_event we are sure that 3.23.58 and newer will detect the problem as soon as replication starts (BUG#198). Always calling fake_rotate_event makes sending of normal (=from-binlog) Rotate events a priori unneeded, but it is not so simple: the 2 Rotate events are not equivalent, the normal one is before the Stop event, the fake one is after. If we don't send the normal one, then the Stop event will be interpreted (by existing 4.0 slaves) as "the master stopped", which is wrong. So for safety, given that we want minimum modification of 4.0, we send the normal and fake Rotates. */ if (fake_rotate_event(net, packet, log_file_name, pos, &errmsg)) { /* This error code is not perfect, as fake_rotate_event() does not read anything from the binlog; if it fails it's because of an error in my_net_write(), fortunately it will say so in errmsg. */ my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } /* Adding MAX_LOG_EVENT_HEADER_LEN, since a binlog event can become this larger than the corresponding packet (query) sent from client to master. */ thd->variables.max_allowed_packet= MAX_MAX_ALLOWED_PACKET; /* We can set log_lock now, it does not move (it's a member of mysql_bin_log, and it's already inited, and it will be destroyed only at shutdown). */ p_coord->pos= pos; // the first hb matches the slave's last seen value log_lock= mysql_bin_log.get_log_lock(); log_cond= mysql_bin_log.get_log_cond(); if (pos > BIN_LOG_HEADER_SIZE) { /* reset transmit packet for the event read from binary log file */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; /* Try to find a Format_description_log_event at the beginning of the binlog */ if (!(error = Log_event::read_log_event(&log, packet, log_lock))) { /* The packet has offsets equal to the normal offsets in a binlog event + ev_offset (the first ev_offset characters are the header (default \0)). */ DBUG_PRINT("info", ("Looked for a Format_description_log_event, found event type %d", (*packet)[EVENT_TYPE_OFFSET+ev_offset])); if ((*packet)[EVENT_TYPE_OFFSET+ev_offset] == FORMAT_DESCRIPTION_EVENT) { (*packet)[FLAGS_OFFSET+ev_offset] &= ~LOG_EVENT_BINLOG_IN_USE_F; /* mark that this event with "log_pos=0", so the slave should not increment master's binlog position (rli->group_master_log_pos) */ int4store((char*) packet->ptr()+LOG_POS_OFFSET+ev_offset, 0); /* if reconnect master sends FD event with `created' as 0 to avoid destroying temp tables. */ int4store((char*) packet->ptr()+LOG_EVENT_MINIMAL_HEADER_LEN+ ST_CREATED_OFFSET+ev_offset, (ulong) 0); /* send it */ if (my_net_write(net, (uchar*) packet->ptr(), packet->length())) { errmsg = "Failed on my_net_write()"; my_errno= ER_UNKNOWN_ERROR; goto err; } /* No need to save this event. We are only doing simple reads (no real parsing of the events) so we don't need it. And so we don't need the artificial Format_description_log_event of 3.23&4.x. */ } } else { if (test_for_non_eof_log_read_errors(error, &errmsg)) goto err; /* It's EOF, nothing to do, go on reading next events, the Format_description_log_event will be found naturally if it is written. */ } } /* end of if (pos > BIN_LOG_HEADER_SIZE); */ else { /* The Format_description_log_event event will be found naturally. */ } /* seek to the requested position, to start the requested dump */ my_b_seek(&log, pos); // Seek will done on next read while (!net->error && net->vio != 0 && !thd->killed) { Log_event_type event_type= UNKNOWN_EVENT; /* reset the transmit packet for the event read from binary log file */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; bool is_active_binlog= false; while (!(error= Log_event::read_log_event(&log, packet, log_lock, log_file_name, &is_active_binlog))) { #ifndef DBUG_OFF if (max_binlog_dump_events && !left_events--) { net_flush(net); errmsg = "Debugging binlog dump abort"; my_errno= ER_UNKNOWN_ERROR; goto err; } #endif /* log's filename does not change while it's active */ p_coord->pos= uint4korr(packet->ptr() + ev_offset + LOG_POS_OFFSET); event_type= (Log_event_type)((*packet)[LOG_EVENT_OFFSET+ev_offset]); DBUG_EXECUTE_IF("dump_thread_wait_before_send_xid", { if (event_type == XID_EVENT) { net_flush(net); const char act[]= "now " "wait_for signal.continue"; DBUG_ASSERT(opt_debug_sync_timeout > 0); DBUG_ASSERT(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act))); } }); if (event_type == FORMAT_DESCRIPTION_EVENT) { (*packet)[FLAGS_OFFSET+ev_offset] &= ~LOG_EVENT_BINLOG_IN_USE_F; } pos = my_b_tell(&log); if (RUN_HOOK(binlog_transmit, before_send_event, (thd, flags, packet, log_file_name, pos))) { my_errno= ER_UNKNOWN_ERROR; errmsg= "run 'before_send_event' hook failed"; goto err; } if (my_net_write(net, (uchar*) packet->ptr(), packet->length())) { errmsg = "Failed on my_net_write()"; my_errno= ER_UNKNOWN_ERROR; goto err; } DBUG_EXECUTE_IF("dump_thread_wait_before_send_xid", { if (event_type == XID_EVENT) { net_flush(net); } }); DBUG_PRINT("info", ("log event code %d", event_type)); if (event_type == LOAD_EVENT) { if (send_file(thd)) { errmsg = "failed in send_file()"; my_errno= ER_UNKNOWN_ERROR; goto err; } } if (RUN_HOOK(binlog_transmit, after_send_event, (thd, flags, packet))) { errmsg= "Failed to run hook 'after_send_event'"; my_errno= ER_UNKNOWN_ERROR; goto err; } /* reset transmit packet for next loop */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; } DBUG_EXECUTE_IF("wait_after_binlog_EOF", { const char act[]= "now wait_for signal.rotate_finished"; DBUG_ASSERT(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act))); };); /* TODO: now that we are logging the offset, check to make sure the recorded offset and the actual match. Guilhem 2003-06: this is not true if this master is a slave <4.0.15 running with --log-slave-updates, because then log_pos may be the offset in the-master-of-this-master's binlog. */ if (test_for_non_eof_log_read_errors(error, &errmsg)) goto err; /* We should only move to the next binlog when the last read event came from a already deactivated binlog. */ if (!(flags & BINLOG_DUMP_NON_BLOCK) && is_active_binlog) { /* Block until there is more data in the log */ if (net_flush(net)) { errmsg = "failed on net_flush()"; my_errno= ER_UNKNOWN_ERROR; goto err; } /* We may have missed the update broadcast from the log that has just happened, let's try to catch it if it did. If we did not miss anything, we just wait for other threads to signal us. */ { log.error=0; bool read_packet = 0; #ifndef DBUG_OFF if (max_binlog_dump_events && !left_events--) { errmsg = "Debugging binlog dump abort"; my_errno= ER_UNKNOWN_ERROR; goto err; } #endif /* reset the transmit packet for the event read from binary log file */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; /* No one will update the log while we are reading now, but we'll be quick and just read one record TODO: Add an counter that is incremented for each time we update the binary log. We can avoid the following read if the counter has not been updated since last read. */ mysql_mutex_lock(log_lock); switch (error= Log_event::read_log_event(&log, packet, (mysql_mutex_t*) 0)) { case 0: /* we read successfully, so we'll need to send it to the slave */ mysql_mutex_unlock(log_lock); read_packet = 1; p_coord->pos= uint4korr(packet->ptr() + ev_offset + LOG_POS_OFFSET); event_type= (Log_event_type)((*packet)[LOG_EVENT_OFFSET+ev_offset]); break; case LOG_READ_EOF: { int ret; ulong signal_cnt; DBUG_PRINT("wait",("waiting for data in binary log")); if (thd->server_id==0) // for mysqlbinlog (mysqlbinlog.server_id==0) { mysql_mutex_unlock(log_lock); goto end; } #ifndef DBUG_OFF ulong hb_info_counter= 0; #endif const char* old_msg= thd->proc_info; signal_cnt= mysql_bin_log.signal_cnt; do { if (heartbeat_period != 0) { DBUG_ASSERT(heartbeat_ts); set_timespec_nsec(*heartbeat_ts, heartbeat_period); } thd->enter_cond(log_cond, log_lock, "Master has sent all binlog to slave; " "waiting for binlog to be updated"); ret= mysql_bin_log.wait_for_update_bin_log(thd, heartbeat_ts); DBUG_ASSERT(ret == 0 || (heartbeat_period != 0)); if (ret == ETIMEDOUT || ret == ETIME) { #ifndef DBUG_OFF if (hb_info_counter < 3) { sql_print_information("master sends heartbeat message"); hb_info_counter++; if (hb_info_counter == 3) sql_print_information("the rest of heartbeat info skipped ..."); } #endif /* reset transmit packet for the heartbeat event */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) { thd->exit_cond(old_msg); goto err; } if (send_heartbeat_event(net, packet, p_coord)) { errmsg = "Failed on my_net_write()"; my_errno= ER_UNKNOWN_ERROR; thd->exit_cond(old_msg); goto err; } } else { DBUG_PRINT("wait",("binary log received update or a broadcast signal caught")); } } while (signal_cnt == mysql_bin_log.signal_cnt && !thd->killed); thd->exit_cond(old_msg); } break; default: mysql_mutex_unlock(log_lock); test_for_non_eof_log_read_errors(error, &errmsg); goto err; } if (read_packet) { thd_proc_info(thd, "Sending binlog event to slave"); pos = my_b_tell(&log); if (RUN_HOOK(binlog_transmit, before_send_event, (thd, flags, packet, log_file_name, pos))) { my_errno= ER_UNKNOWN_ERROR; errmsg= "run 'before_send_event' hook failed"; goto err; } if (my_net_write(net, (uchar*) packet->ptr(), packet->length()) ) { errmsg = "Failed on my_net_write()"; my_errno= ER_UNKNOWN_ERROR; goto err; } if (event_type == LOAD_EVENT) { if (send_file(thd)) { errmsg = "failed in send_file()"; my_errno= ER_UNKNOWN_ERROR; goto err; } } if (RUN_HOOK(binlog_transmit, after_send_event, (thd, flags, packet))) { my_errno= ER_UNKNOWN_ERROR; errmsg= "Failed to run hook 'after_send_event'"; goto err; } } log.error=0; } } else { bool loop_breaker = 0; /* need this to break out of the for loop from switch */ thd_proc_info(thd, "Finished reading one binlog; switching to next binlog"); switch (mysql_bin_log.find_next_log(&linfo, 1)) { case 0: break; case LOG_INFO_EOF: if (mysql_bin_log.is_active(log_file_name)) { loop_breaker = (flags & BINLOG_DUMP_NON_BLOCK); break; } default: errmsg = "could not find next log"; my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } if (loop_breaker) break; end_io_cache(&log); mysql_file_close(file, MYF(MY_WME)); /* reset transmit packet for the possible fake rotate event */ if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg)) goto err; /* Call fake_rotate_event() in case the previous log (the one which we have just finished reading) did not contain a Rotate event (for example (I don't know any other example) the previous log was the last one before the master was shutdown & restarted). This way we tell the slave about the new log's name and position. If the binlog is 5.0, the next event we are going to read and send is Format_description_log_event. */ if ((file=open_binlog(&log, log_file_name, &errmsg)) < 0 || fake_rotate_event(net, packet, log_file_name, BIN_LOG_HEADER_SIZE, &errmsg)) { my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG; goto err; } p_coord->file_name= log_file_name; // reset to the next } } end: end_io_cache(&log); mysql_file_close(file, MYF(MY_WME)); RUN_HOOK(binlog_transmit, transmit_stop, (thd, flags)); my_eof(thd); thd_proc_info(thd, "Waiting to finalize termination"); mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = 0; mysql_mutex_unlock(&LOCK_thread_count); thd->variables.max_allowed_packet= old_max_allowed_packet; DBUG_VOID_RETURN; err: thd_proc_info(thd, "Waiting to finalize termination"); if (my_errno == ER_MASTER_FATAL_ERROR_READING_BINLOG && my_b_inited(&log)) { /* detailing the fatal error message with coordinates of the last position read. */ my_snprintf(error_text, sizeof(error_text), "%s; the first event '%s' at %lld, " "the last event read from '%s' at %lld, " "the last byte read from '%s' at %lld.", errmsg, p_start_coord->file_name, p_start_coord->pos, p_coord->file_name, p_coord->pos, log_file_name, my_b_tell(&log)); } else strcpy(error_text, errmsg); end_io_cache(&log); RUN_HOOK(binlog_transmit, transmit_stop, (thd, flags)); /* Exclude iteration through thread list this is needed for purge_logs() - it will iterate through thread list and update thd->current_linfo->index_file_offset this mutex will make sure that it never tried to update our linfo after we return from this stack frame */ mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = 0; mysql_mutex_unlock(&LOCK_thread_count); if (file >= 0) mysql_file_close(file, MYF(MY_WME)); thd->variables.max_allowed_packet= old_max_allowed_packet; my_message(my_errno, error_text, MYF(0)); DBUG_VOID_RETURN; } /** Execute a START SLAVE statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object for the slave's IO thread. @param net_report If true, saves the exit status into thd->stmt_da. @retval 0 success @retval 1 error */ int start_slave(THD* thd , Master_info* mi, bool net_report) { int slave_errno= 0; int thread_mask; DBUG_ENTER("start_slave"); if (check_access(thd, SUPER_ACL, any_db, NULL, NULL, 0, 0)) DBUG_RETURN(1); lock_slave_threads(mi); // this allows us to cleanly read slave_running // Get a mask of _stopped_ threads init_thread_mask(&thread_mask,mi,1 /* inverse */); /* Below we will start all stopped threads. But if the user wants to start only one thread, do as if the other thread was running (as we don't wan't to touch the other thread), so set the bit to 0 for the other thread */ if (thd->lex->slave_thd_opt) thread_mask&= thd->lex->slave_thd_opt; if (thread_mask) //some threads are stopped, start them { if (init_master_info(mi,master_info_file,relay_log_info_file, 0, thread_mask)) slave_errno=ER_MASTER_INFO; else if (server_id_supplied && *mi->host) { /* If we will start SQL thread we will care about UNTIL options If not and they are specified we will ignore them and warn user about this fact. */ if (thread_mask & SLAVE_SQL) { mysql_mutex_lock(&mi->rli.data_lock); if (thd->lex->mi.pos) { if (thd->lex->mi.relay_log_pos) slave_errno=ER_BAD_SLAVE_UNTIL_COND; mi->rli.until_condition= Relay_log_info::UNTIL_MASTER_POS; mi->rli.until_log_pos= thd->lex->mi.pos; /* We don't check thd->lex->mi.log_file_name for NULL here since it is checked in sql_yacc.yy */ strmake(mi->rli.until_log_name, thd->lex->mi.log_file_name, sizeof(mi->rli.until_log_name)-1); } else if (thd->lex->mi.relay_log_pos) { if (thd->lex->mi.pos) slave_errno=ER_BAD_SLAVE_UNTIL_COND; mi->rli.until_condition= Relay_log_info::UNTIL_RELAY_POS; mi->rli.until_log_pos= thd->lex->mi.relay_log_pos; strmake(mi->rli.until_log_name, thd->lex->mi.relay_log_name, sizeof(mi->rli.until_log_name)-1); } else mi->rli.clear_until_condition(); if (mi->rli.until_condition != Relay_log_info::UNTIL_NONE) { /* Preparing members for effective until condition checking */ const char *p= fn_ext(mi->rli.until_log_name); char *p_end; if (*p) { //p points to '.' mi->rli.until_log_name_extension= strtoul(++p,&p_end, 10); /* p_end points to the first invalid character. If it equals to p, no digits were found, error. If it contains '\0' it means conversion went ok. */ if (p_end==p || *p_end) slave_errno=ER_BAD_SLAVE_UNTIL_COND; } else slave_errno=ER_BAD_SLAVE_UNTIL_COND; /* mark the cached result of the UNTIL comparison as "undefined" */ mi->rli.until_log_names_cmp_result= Relay_log_info::UNTIL_LOG_NAMES_CMP_UNKNOWN; /* Issuing warning then started without --skip-slave-start */ if (!opt_skip_slave_start) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_MISSING_SKIP_SLAVE, ER(ER_MISSING_SKIP_SLAVE)); } mysql_mutex_unlock(&mi->rli.data_lock); } else if (thd->lex->mi.pos || thd->lex->mi.relay_log_pos) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_UNTIL_COND_IGNORED, ER(ER_UNTIL_COND_IGNORED)); if (!slave_errno) slave_errno = start_slave_threads(0 /*no mutex */, 1 /* wait for start */, mi, master_info_file,relay_log_info_file, thread_mask); } else slave_errno = ER_BAD_SLAVE; } else { /* no error if all threads are already started, only a warning */ push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_SLAVE_WAS_RUNNING, ER(ER_SLAVE_WAS_RUNNING)); } unlock_slave_threads(mi); if (slave_errno) { if (net_report) my_message(slave_errno, ER(slave_errno), MYF(0)); DBUG_RETURN(1); } else if (net_report) my_ok(thd); DBUG_RETURN(0); } /** Execute a STOP SLAVE statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object for the slave's IO thread. @param net_report If true, saves the exit status into thd->stmt_da. @retval 0 success @retval 1 error */ int stop_slave(THD* thd, Master_info* mi, bool net_report ) { DBUG_ENTER("stop_slave"); int slave_errno; if (!thd) thd = current_thd; if (check_access(thd, SUPER_ACL, any_db, NULL, NULL, 0, 0)) DBUG_RETURN(1); thd_proc_info(thd, "Killing slave"); int thread_mask; lock_slave_threads(mi); // Get a mask of _running_ threads init_thread_mask(&thread_mask,mi,0 /* not inverse*/); /* Below we will stop all running threads. But if the user wants to stop only one thread, do as if the other thread was stopped (as we don't wan't to touch the other thread), so set the bit to 0 for the other thread */ if (thd->lex->slave_thd_opt) thread_mask &= thd->lex->slave_thd_opt; if (thread_mask) { slave_errno= terminate_slave_threads(mi,thread_mask, 1 /*skip lock */); } else { //no error if both threads are already stopped, only a warning slave_errno= 0; push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_SLAVE_WAS_NOT_RUNNING, ER(ER_SLAVE_WAS_NOT_RUNNING)); } unlock_slave_threads(mi); thd_proc_info(thd, 0); if (slave_errno) { if (net_report) my_message(slave_errno, ER(slave_errno), MYF(0)); DBUG_RETURN(1); } else if (net_report) my_ok(thd); DBUG_RETURN(0); } /** Execute a RESET SLAVE statement. @param thd Pointer to THD object of the client thread executing the statement. @param mi Pointer to Master_info object for the slave. @retval 0 success @retval 1 error */ int reset_slave(THD *thd, Master_info* mi) { MY_STAT stat_area; char fname[FN_REFLEN]; int thread_mask= 0, error= 0; uint sql_errno=ER_UNKNOWN_ERROR; const char* errmsg= "Unknown error occured while reseting slave"; DBUG_ENTER("reset_slave"); lock_slave_threads(mi); init_thread_mask(&thread_mask,mi,0 /* not inverse */); if (thread_mask) // We refuse if any slave thread is running { sql_errno= ER_SLAVE_MUST_STOP; error=1; goto err; } ha_reset_slave(thd); // delete relay logs, clear relay log coordinates if ((error= purge_relay_logs(&mi->rli, thd, 1 /* just reset */, &errmsg))) { sql_errno= ER_RELAY_LOG_FAIL; goto err; } /* Clear master's log coordinates and associated information */ mi->clear_in_memory_info(thd->lex->reset_slave_info.all); /* Reset errors (the idea is that we forget about the old master). */ mi->clear_error(); mi->rli.clear_error(); mi->rli.clear_until_condition(); // close master_info_file, relay_log_info_file, set mi->inited=rli->inited=0 end_master_info(mi); // and delete these two files fn_format(fname, master_info_file, mysql_data_home, "", 4+32); if (mysql_file_stat(key_file_master_info, fname, &stat_area, MYF(0)) && mysql_file_delete(key_file_master_info, fname, MYF(MY_WME))) { error=1; goto err; } // delete relay_log_info_file fn_format(fname, relay_log_info_file, mysql_data_home, "", 4+32); if (mysql_file_stat(key_file_relay_log_info, fname, &stat_area, MYF(0)) && mysql_file_delete(key_file_relay_log_info, fname, MYF(MY_WME))) { error=1; goto err; } RUN_HOOK(binlog_relay_io, after_reset_slave, (thd, mi)); err: unlock_slave_threads(mi); if (error) my_error(sql_errno, MYF(0), errmsg); DBUG_RETURN(error); } /* Kill all Binlog_dump threads which previously talked to the same slave ("same" means with the same server id). Indeed, if the slave stops, if the Binlog_dump thread is waiting (mysql_cond_wait) for binlog update, then it will keep existing until a query is written to the binlog. If the master is idle, then this could last long, and if the slave reconnects, we could have 2 Binlog_dump threads in SHOW PROCESSLIST, until a query is written to the binlog. To avoid this, when the slave reconnects and sends COM_BINLOG_DUMP, the master kills any existing thread with the slave's server id (if this id is not zero; it will be true for real slaves, but false for mysqlbinlog when it sends COM_BINLOG_DUMP to get a remote binlog dump). SYNOPSIS kill_zombie_dump_threads() slave_server_id the slave's server id */ void kill_zombie_dump_threads(uint32 slave_server_id) { mysql_mutex_lock(&LOCK_thread_count); I_List_iterator<THD> it(threads); THD *tmp; while ((tmp=it++)) { if (tmp->command == COM_BINLOG_DUMP && tmp->server_id == slave_server_id) { mysql_mutex_lock(&tmp->LOCK_thd_data); // Lock from delete break; } } mysql_mutex_unlock(&LOCK_thread_count); if (tmp) { /* Here we do not call kill_one_thread() as it will be slow because it will iterate through the list again. We just to do kill the thread ourselves. */ tmp->awake(THD::KILL_QUERY); mysql_mutex_unlock(&tmp->LOCK_thd_data); } } /** Execute a CHANGE MASTER statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object belonging to the slave's IO thread. @retval FALSE success @retval TRUE error */ bool change_master(THD* thd, Master_info* mi) { int thread_mask; const char* errmsg= 0; bool need_relay_log_purge= 1; bool ret= FALSE; char saved_host[HOSTNAME_LENGTH + 1]; uint saved_port; char saved_log_name[FN_REFLEN]; my_off_t saved_log_pos; DBUG_ENTER("change_master"); lock_slave_threads(mi); init_thread_mask(&thread_mask,mi,0 /*not inverse*/); LEX_MASTER_INFO* lex_mi= &thd->lex->mi; if (thread_mask) // We refuse if any slave thread is running { my_message(ER_SLAVE_MUST_STOP, ER(ER_SLAVE_MUST_STOP), MYF(0)); ret= TRUE; goto err; } thd_proc_info(thd, "Changing master"); /* We need to check if there is an empty master_host. Otherwise change master succeeds, a master.info file is created containing empty master_host string and when issuing: start slave; an error is thrown stating that the server is not configured as slave. (See BUG#28796). */ if(lex_mi->host && !*lex_mi->host) { my_error(ER_WRONG_ARGUMENTS, MYF(0), "MASTER_HOST"); unlock_slave_threads(mi); DBUG_RETURN(TRUE); } // TODO: see if needs re-write if (init_master_info(mi, master_info_file, relay_log_info_file, 0, thread_mask)) { my_message(ER_MASTER_INFO, ER(ER_MASTER_INFO), MYF(0)); ret= TRUE; goto err; } /* Data lock not needed since we have already stopped the running threads, and we have the hold on the run locks which will keep all threads that could possibly modify the data structures from running */ /* Before processing the command, save the previous state. */ strmake(saved_host, mi->host, HOSTNAME_LENGTH); saved_port= mi->port; strmake(saved_log_name, mi->master_log_name, FN_REFLEN - 1); saved_log_pos= mi->master_log_pos; /* If the user specified host or port without binlog or position, reset binlog's name to FIRST and position to 4. */ if ((lex_mi->host || lex_mi->port) && !lex_mi->log_file_name && !lex_mi->pos) { mi->master_log_name[0] = 0; mi->master_log_pos= BIN_LOG_HEADER_SIZE; } if (lex_mi->log_file_name) strmake(mi->master_log_name, lex_mi->log_file_name, sizeof(mi->master_log_name)-1); if (lex_mi->pos) { mi->master_log_pos= lex_mi->pos; } DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->master_log_pos)); if (lex_mi->host) strmake(mi->host, lex_mi->host, sizeof(mi->host)-1); if (lex_mi->user) strmake(mi->user, lex_mi->user, sizeof(mi->user)-1); if (lex_mi->password) strmake(mi->password, lex_mi->password, sizeof(mi->password)-1); if (lex_mi->port) mi->port = lex_mi->port; if (lex_mi->connect_retry) mi->connect_retry = lex_mi->connect_retry; if (lex_mi->heartbeat_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->heartbeat_period = lex_mi->heartbeat_period; else mi->heartbeat_period= (float) min(SLAVE_MAX_HEARTBEAT_PERIOD, (slave_net_timeout/2.0)); mi->received_heartbeats= LL(0); // counter lives until master is CHANGEd /* reset the last time server_id list if the current CHANGE MASTER is mentioning IGNORE_SERVER_IDS= (...) */ if (lex_mi->repl_ignore_server_ids_opt == LEX_MASTER_INFO::LEX_MI_ENABLE) reset_dynamic(&mi->ignore_server_ids); for (uint i= 0; i < lex_mi->repl_ignore_server_ids.elements; i++) { ulong s_id; get_dynamic(&lex_mi->repl_ignore_server_ids, (uchar*) &s_id, i); if (s_id == ::server_id && replicate_same_server_id) { my_error(ER_SLAVE_IGNORE_SERVER_IDS, MYF(0), static_cast<int>(s_id)); ret= TRUE; goto err; } else { if (bsearch((const ulong *) &s_id, mi->ignore_server_ids.buffer, mi->ignore_server_ids.elements, sizeof(ulong), (int (*) (const void*, const void*)) change_master_server_id_cmp) == NULL) insert_dynamic(&mi->ignore_server_ids, (uchar*) &s_id); } } sort_dynamic(&mi->ignore_server_ids, (qsort_cmp) change_master_server_id_cmp); if (lex_mi->ssl != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->ssl= (lex_mi->ssl == LEX_MASTER_INFO::LEX_MI_ENABLE); if (lex_mi->ssl_verify_server_cert != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->ssl_verify_server_cert= (lex_mi->ssl_verify_server_cert == LEX_MASTER_INFO::LEX_MI_ENABLE); if (lex_mi->ssl_ca) strmake(mi->ssl_ca, lex_mi->ssl_ca, sizeof(mi->ssl_ca)-1); if (lex_mi->ssl_capath) strmake(mi->ssl_capath, lex_mi->ssl_capath, sizeof(mi->ssl_capath)-1); if (lex_mi->ssl_cert) strmake(mi->ssl_cert, lex_mi->ssl_cert, sizeof(mi->ssl_cert)-1); if (lex_mi->ssl_cipher) strmake(mi->ssl_cipher, lex_mi->ssl_cipher, sizeof(mi->ssl_cipher)-1); if (lex_mi->ssl_key) strmake(mi->ssl_key, lex_mi->ssl_key, sizeof(mi->ssl_key)-1); #ifndef HAVE_OPENSSL if (lex_mi->ssl || lex_mi->ssl_ca || lex_mi->ssl_capath || lex_mi->ssl_cert || lex_mi->ssl_cipher || lex_mi->ssl_key || lex_mi->ssl_verify_server_cert ) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_SLAVE_IGNORED_SSL_PARAMS, ER(ER_SLAVE_IGNORED_SSL_PARAMS)); #endif if (lex_mi->relay_log_name) { need_relay_log_purge= 0; char relay_log_name[FN_REFLEN]; mi->rli.relay_log.make_log_name(relay_log_name, lex_mi->relay_log_name); strmake(mi->rli.group_relay_log_name, relay_log_name, sizeof(mi->rli.group_relay_log_name)-1); strmake(mi->rli.event_relay_log_name, relay_log_name, sizeof(mi->rli.event_relay_log_name)-1); } if (lex_mi->relay_log_pos) { need_relay_log_purge= 0; mi->rli.group_relay_log_pos= mi->rli.event_relay_log_pos= lex_mi->relay_log_pos; } /* If user did specify neither host nor port nor any log name nor any log pos, i.e. he specified only user/password/master_connect_retry, he probably wants replication to resume from where it had left, i.e. from the coordinates of the **SQL** thread (imagine the case where the I/O is ahead of the SQL; restarting from the coordinates of the I/O would lose some events which is probably unwanted when you are just doing minor changes like changing master_connect_retry). A side-effect is that if only the I/O thread was started, this thread may restart from ''/4 after the CHANGE MASTER. That's a minor problem (it is a much more unlikely situation than the one we are fixing here). Note: coordinates of the SQL thread must be read here, before the 'if (need_relay_log_purge)' block which resets them. */ if (!lex_mi->host && !lex_mi->port && !lex_mi->log_file_name && !lex_mi->pos && need_relay_log_purge) { /* Sometimes mi->rli.master_log_pos == 0 (it happens when the SQL thread is not initialized), so we use a max(). What happens to mi->rli.master_log_pos during the initialization stages of replication is not 100% clear, so we guard against problems using max(). */ mi->master_log_pos = max(BIN_LOG_HEADER_SIZE, mi->rli.group_master_log_pos); strmake(mi->master_log_name, mi->rli.group_master_log_name, sizeof(mi->master_log_name)-1); } /* Relay log's IO_CACHE may not be inited, if rli->inited==0 (server was never a slave before). */ if (flush_master_info(mi, FALSE, FALSE)) { my_error(ER_RELAY_LOG_INIT, MYF(0), "Failed to flush master info file"); ret= TRUE; goto err; } if (need_relay_log_purge) { relay_log_purge= 1; thd_proc_info(thd, "Purging old relay logs"); if (purge_relay_logs(&mi->rli, thd, 0 /* not only reset, but also reinit */, &errmsg)) { my_error(ER_RELAY_LOG_FAIL, MYF(0), errmsg); ret= TRUE; goto err; } } else { const char* msg; relay_log_purge= 0; /* Relay log is already initialized */ if (init_relay_log_pos(&mi->rli, mi->rli.group_relay_log_name, mi->rli.group_relay_log_pos, 0 /*no data lock*/, &msg, 0)) { my_error(ER_RELAY_LOG_INIT, MYF(0), msg); ret= TRUE; goto err; } } /* Coordinates in rli were spoilt by the 'if (need_relay_log_purge)' block, so restore them to good values. If we left them to ''/0, that would work; but that would fail in the case of 2 successive CHANGE MASTER (without a START SLAVE in between): because first one would set the coords in mi to the good values of those in rli, the set those in rli to ''/0, then second CHANGE MASTER would set the coords in mi to those of rli, i.e. to ''/0: we have lost all copies of the original good coordinates. That's why we always save good coords in rli. */ mi->rli.group_master_log_pos= mi->master_log_pos; DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->master_log_pos)); strmake(mi->rli.group_master_log_name,mi->master_log_name, sizeof(mi->rli.group_master_log_name)-1); if (!mi->rli.group_master_log_name[0]) // uninitialized case mi->rli.group_master_log_pos=0; mysql_mutex_lock(&mi->rli.data_lock); mi->rli.abort_pos_wait++; /* for MASTER_POS_WAIT() to abort */ /* Clear the errors, for a clean start */ mi->rli.clear_error(); mi->rli.clear_until_condition(); sql_print_information("'CHANGE MASTER TO executed'. " "Previous state master_host='%s', master_port='%u', master_log_file='%s', " "master_log_pos='%ld'. " "New state master_host='%s', master_port='%u', master_log_file='%s', " "master_log_pos='%ld'.", saved_host, saved_port, saved_log_name, (ulong) saved_log_pos, mi->host, mi->port, mi->master_log_name, (ulong) mi->master_log_pos); /* If we don't write new coordinates to disk now, then old will remain in relay-log.info until START SLAVE is issued; but if mysqld is shutdown before START SLAVE, then old will remain in relay-log.info, and will be the in-memory value at restart (thus causing errors, as the old relay log does not exist anymore). */ flush_relay_log_info(&mi->rli); mysql_cond_broadcast(&mi->data_cond); mysql_mutex_unlock(&mi->rli.data_lock); err: unlock_slave_threads(mi); thd_proc_info(thd, 0); if (ret == FALSE) my_ok(thd); DBUG_RETURN(ret); } /** Execute a RESET MASTER statement. @param thd Pointer to THD object of the client thread executing the statement. @retval 0 success @retval 1 error */ int reset_master(THD* thd) { if (!mysql_bin_log.is_open()) { my_message(ER_FLUSH_MASTER_BINLOG_CLOSED, ER(ER_FLUSH_MASTER_BINLOG_CLOSED), MYF(ME_BELL+ME_WAITTANG)); return 1; } if (mysql_bin_log.reset_logs(thd)) return 1; RUN_HOOK(binlog_transmit, after_reset_master, (thd, 0 /* flags */)); return 0; } /** Execute a SHOW BINLOG EVENTS statement. @param thd Pointer to THD object for the client thread executing the statement. @retval FALSE success @retval TRUE failure */ bool mysql_show_binlog_events(THD* thd) { Protocol *protocol= thd->protocol; List<Item> field_list; const char *errmsg = 0; bool ret = TRUE; IO_CACHE log; File file = -1; MYSQL_BIN_LOG *binary_log= NULL; int old_max_allowed_packet= thd->variables.max_allowed_packet; LOG_INFO linfo; DBUG_ENTER("mysql_show_binlog_events"); Log_event::init_show_field_list(&field_list); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); Format_description_log_event *description_event= new Format_description_log_event(3); /* MySQL 4.0 by default */ DBUG_ASSERT(thd->lex->sql_command == SQLCOM_SHOW_BINLOG_EVENTS || thd->lex->sql_command == SQLCOM_SHOW_RELAYLOG_EVENTS); /* select wich binary log to use: binlog or relay */ if ( thd->lex->sql_command == SQLCOM_SHOW_BINLOG_EVENTS ) { /* Wait for handlers to insert any pending information into the binlog. For e.g. ndb which updates the binlog asynchronously this is needed so that the uses sees all its own commands in the binlog */ ha_binlog_wait(thd); binary_log= &mysql_bin_log; } else /* showing relay log contents */ { if (!active_mi) DBUG_RETURN(TRUE); binary_log= &(active_mi->rli.relay_log); } if (binary_log->is_open()) { LEX_MASTER_INFO *lex_mi= &thd->lex->mi; SELECT_LEX_UNIT *unit= &thd->lex->unit; ha_rows event_count, limit_start, limit_end; my_off_t pos = max(BIN_LOG_HEADER_SIZE, lex_mi->pos); // user-friendly char search_file_name[FN_REFLEN], *name; const char *log_file_name = lex_mi->log_file_name; mysql_mutex_t *log_lock = binary_log->get_log_lock(); Log_event* ev; unit->set_limit(thd->lex->current_select); limit_start= unit->offset_limit_cnt; limit_end= unit->select_limit_cnt; name= search_file_name; if (log_file_name) binary_log->make_log_name(search_file_name, log_file_name); else name=0; // Find first log linfo.index_file_offset = 0; if (binary_log->find_log_pos(&linfo, name, 1)) { errmsg = "Could not find target log"; goto err; } mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = &linfo; mysql_mutex_unlock(&LOCK_thread_count); if ((file=open_binlog(&log, linfo.log_file_name, &errmsg)) < 0) goto err; /* to account binlog event header size */ thd->variables.max_allowed_packet += MAX_LOG_EVENT_HEADER; mysql_mutex_lock(log_lock); /* open_binlog() sought to position 4. Read the first event in case it's a Format_description_log_event, to know the format. If there's no such event, we are 3.23 or 4.x. This code, like before, can't read 3.23 binlogs. This code will fail on a mixed relay log (one which has Format_desc then Rotate then Format_desc). */ ev= Log_event::read_log_event(&log, (mysql_mutex_t*)0, description_event); if (ev) { if (ev->get_type_code() == FORMAT_DESCRIPTION_EVENT) { delete description_event; description_event= (Format_description_log_event*) ev; } else delete ev; } my_b_seek(&log, pos); if (!description_event->is_valid()) { errmsg="Invalid Format_description event; could be out of memory"; goto err; } for (event_count = 0; (ev = Log_event::read_log_event(&log, (mysql_mutex_t*) 0, description_event)); ) { if (event_count >= limit_start && ev->net_send(protocol, linfo.log_file_name, pos)) { errmsg = "Net error"; delete ev; mysql_mutex_unlock(log_lock); goto err; } pos = my_b_tell(&log); delete ev; if (++event_count >= limit_end) break; } if (event_count < limit_end && log.error) { errmsg = "Wrong offset or I/O error"; mysql_mutex_unlock(log_lock); goto err; } mysql_mutex_unlock(log_lock); } // Check that linfo is still on the function scope. DEBUG_SYNC(thd, "after_show_binlog_events"); ret= FALSE; err: delete description_event; if (file >= 0) { end_io_cache(&log); mysql_file_close(file, MYF(MY_WME)); } if (errmsg) my_error(ER_ERROR_WHEN_EXECUTING_COMMAND, MYF(0), "SHOW BINLOG EVENTS", errmsg); else my_eof(thd); mysql_mutex_lock(&LOCK_thread_count); thd->current_linfo = 0; mysql_mutex_unlock(&LOCK_thread_count); thd->variables.max_allowed_packet= old_max_allowed_packet; DBUG_RETURN(ret); } /** Execute a SHOW MASTER STATUS statement. @param thd Pointer to THD object for the client thread executing the statement. @retval FALSE success @retval TRUE failure */ bool show_binlog_info(THD* thd) { Protocol *protocol= thd->protocol; DBUG_ENTER("show_binlog_info"); List<Item> field_list; field_list.push_back(new Item_empty_string("File", FN_REFLEN)); field_list.push_back(new Item_return_int("Position",20, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_empty_string("Binlog_Do_DB",255)); field_list.push_back(new Item_empty_string("Binlog_Ignore_DB",255)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); protocol->prepare_for_resend(); if (mysql_bin_log.is_open()) { LOG_INFO li; mysql_bin_log.get_current_log(&li); int dir_len = dirname_length(li.log_file_name); protocol->store(li.log_file_name + dir_len, &my_charset_bin); protocol->store((ulonglong) li.pos); protocol->store(binlog_filter->get_do_db()); protocol->store(binlog_filter->get_ignore_db()); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); } /** Execute a SHOW BINARY LOGS statement. @param thd Pointer to THD object for the client thread executing the statement. @retval FALSE success @retval TRUE failure */ bool show_binlogs(THD* thd) { IO_CACHE *index_file; LOG_INFO cur; File file; char fname[FN_REFLEN]; List<Item> field_list; uint length; int cur_dir_len; Protocol *protocol= thd->protocol; DBUG_ENTER("show_binlogs"); if (!mysql_bin_log.is_open()) { my_error(ER_NO_BINARY_LOGGING, MYF(0)); DBUG_RETURN(TRUE); } field_list.push_back(new Item_empty_string("Log_name", 255)); field_list.push_back(new Item_return_int("File_size", 20, MYSQL_TYPE_LONGLONG)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); mysql_mutex_lock(mysql_bin_log.get_log_lock()); mysql_bin_log.lock_index(); index_file=mysql_bin_log.get_index_file(); mysql_bin_log.raw_get_current_log(&cur); // dont take mutex mysql_mutex_unlock(mysql_bin_log.get_log_lock()); // lockdep, OK cur_dir_len= dirname_length(cur.log_file_name); reinit_io_cache(index_file, READ_CACHE, (my_off_t) 0, 0, 0); /* The file ends with EOF or empty line */ while ((length=my_b_gets(index_file, fname, sizeof(fname))) > 1) { int dir_len; ulonglong file_length= 0; // Length if open fails fname[--length] = '\0'; // remove the newline protocol->prepare_for_resend(); dir_len= dirname_length(fname); length-= dir_len; protocol->store(fname + dir_len, length, &my_charset_bin); if (!(strncmp(fname+dir_len, cur.log_file_name+cur_dir_len, length))) file_length= cur.pos; /* The active log, use the active position */ else { /* this is an old log, open it and find the size */ if ((file= mysql_file_open(key_file_binlog, fname, O_RDONLY | O_SHARE | O_BINARY, MYF(0))) >= 0) { file_length= (ulonglong) mysql_file_seek(file, 0L, MY_SEEK_END, MYF(0)); mysql_file_close(file, MYF(0)); } } protocol->store(file_length); if (protocol->write()) goto err; } if(index_file->error == -1) goto err; mysql_bin_log.unlock_index(); my_eof(thd); DBUG_RETURN(FALSE); err: mysql_bin_log.unlock_index(); DBUG_RETURN(TRUE); } /** Load data's io cache specific hook to be executed before a chunk of data is being read into the cache's buffer The fuction instantianates and writes into the binlog replication events along LOAD DATA processing. @param file pointer to io-cache @retval 0 success @retval 1 failure */ int log_loaded_block(IO_CACHE* file) { DBUG_ENTER("log_loaded_block"); LOAD_FILE_INFO *lf_info; uint block_len; /* buffer contains position where we started last read */ uchar* buffer= (uchar*) my_b_get_buffer_start(file); uint max_event_size= current_thd->variables.max_allowed_packet; lf_info= (LOAD_FILE_INFO*) file->arg; if (lf_info->thd->is_current_stmt_binlog_format_row()) DBUG_RETURN(0); if (lf_info->last_pos_in_file != HA_POS_ERROR && lf_info->last_pos_in_file >= my_b_get_pos_in_file(file)) DBUG_RETURN(0); for (block_len= (uint) (my_b_get_bytes_in_buffer(file)); block_len > 0; buffer += min(block_len, max_event_size), block_len -= min(block_len, max_event_size)) { lf_info->last_pos_in_file= my_b_get_pos_in_file(file); if (lf_info->wrote_create_file) { Append_block_log_event a(lf_info->thd, lf_info->thd->db, buffer, min(block_len, max_event_size), lf_info->log_delayed); if (mysql_bin_log.write(&a)) DBUG_RETURN(1); } else { Begin_load_query_log_event b(lf_info->thd, lf_info->thd->db, buffer, min(block_len, max_event_size), lf_info->log_delayed); if (mysql_bin_log.write(&b)) DBUG_RETURN(1); lf_info->wrote_create_file= 1; } } DBUG_RETURN(0); } #endif /* HAVE_REPLICATION */
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Function with list databases, tables or fields */ #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */ #include "sql_priv.h" #include "unireg.h" #include "sql_acl.h" // fill_schema_*_privileges #include "sql_select.h" // For select_describe #include "sql_base.h" // close_tables_for_reopen #include "sql_show.h" #include "sql_table.h" // filename_to_tablename, // primary_key_name, // build_table_filename #include "repl_failsafe.h" #include "sql_parse.h" // check_access, check_table_access #include "sql_partition.h" // partition_element #include "sql_derived.h" // mysql_derived_prepare, // mysql_handle_derived, #include "sql_db.h" // check_db_dir_existence, load_db_opt_by_name #include "sql_time.h" // interval_type_to_name #include "tztime.h" // struct Time_zone #include "sql_acl.h" // TABLE_ACLS, check_grant, DB_ACLS, acl_get, // check_grant_db #include "filesort.h" // filesort_free_buffers #include "sp.h" #include "sp_head.h" #include "sp_pcontext.h" #include "set_var.h" #include "sql_trigger.h" #include "authors.h" #include "contributors.h" #include "sql_partition.h" #ifdef HAVE_EVENT_SCHEDULER #include "events.h" #include "event_data_objects.h" #endif #include <my_dir.h> #include "lock.h" // MYSQL_OPEN_IGNORE_FLUSH #include "debug_sync.h" #include "datadict.h" // dd_frm_type() #define STR_OR_NIL(S) ((S) ? (S) : "<nil>") #ifdef WITH_PARTITION_STORAGE_ENGINE #include "ha_partition.h" #endif enum enum_i_s_events_fields { ISE_EVENT_CATALOG= 0, ISE_EVENT_SCHEMA, ISE_EVENT_NAME, ISE_DEFINER, ISE_TIME_ZONE, ISE_EVENT_BODY, ISE_EVENT_DEFINITION, ISE_EVENT_TYPE, ISE_EXECUTE_AT, ISE_INTERVAL_VALUE, ISE_INTERVAL_FIELD, ISE_SQL_MODE, ISE_STARTS, ISE_ENDS, ISE_STATUS, ISE_ON_COMPLETION, ISE_CREATED, ISE_LAST_ALTERED, ISE_LAST_EXECUTED, ISE_EVENT_COMMENT, ISE_ORIGINATOR, ISE_CLIENT_CS, ISE_CONNECTION_CL, ISE_DB_CL }; #ifndef NO_EMBEDDED_ACCESS_CHECKS static const char *grant_names[]={ "select","insert","update","delete","create","drop","reload","shutdown", "process","file","grant","references","index","alter"}; static TYPELIB grant_types = { sizeof(grant_names)/sizeof(char **), "grant_types", grant_names, NULL}; #endif static void store_key_options(THD *thd, String *packet, TABLE *table, KEY *key_info); #ifdef WITH_PARTITION_STORAGE_ENGINE static void get_cs_converted_string_value(THD *thd, String *input_str, String *output_str, CHARSET_INFO *cs, bool use_hex); #endif static void append_algorithm(TABLE_LIST *table, String *buff); static COND * make_cond_for_info_schema(COND *cond, TABLE_LIST *table); /*************************************************************************** ** List all table types supported ***************************************************************************/ static int make_version_string(char *buf, int buf_length, uint version) { return my_snprintf(buf, buf_length, "%d.%d", version>>8,version&0xff); } static my_bool show_plugins(THD *thd, plugin_ref plugin, void *arg) { TABLE *table= (TABLE*) arg; struct st_mysql_plugin *plug= plugin_decl(plugin); struct st_plugin_dl *plugin_dl= plugin_dlib(plugin); CHARSET_INFO *cs= system_charset_info; char version_buf[20]; restore_record(table, s->default_values); table->field[0]->store(plugin_name(plugin)->str, plugin_name(plugin)->length, cs); table->field[1]->store(version_buf, make_version_string(version_buf, sizeof(version_buf), plug->version), cs); switch (plugin_state(plugin)) { /* case PLUGIN_IS_FREED: does not happen */ case PLUGIN_IS_DELETED: table->field[2]->store(STRING_WITH_LEN("DELETED"), cs); break; case PLUGIN_IS_UNINITIALIZED: table->field[2]->store(STRING_WITH_LEN("INACTIVE"), cs); break; case PLUGIN_IS_READY: table->field[2]->store(STRING_WITH_LEN("ACTIVE"), cs); break; case PLUGIN_IS_DISABLED: table->field[2]->store(STRING_WITH_LEN("DISABLED"), cs); break; default: DBUG_ASSERT(0); } table->field[3]->store(plugin_type_names[plug->type].str, plugin_type_names[plug->type].length, cs); table->field[4]->store(version_buf, make_version_string(version_buf, sizeof(version_buf), *(uint *)plug->info), cs); if (plugin_dl) { table->field[5]->store(plugin_dl->dl.str, plugin_dl->dl.length, cs); table->field[5]->set_notnull(); table->field[6]->store(version_buf, make_version_string(version_buf, sizeof(version_buf), plugin_dl->version), cs); table->field[6]->set_notnull(); } else { table->field[5]->set_null(); table->field[6]->set_null(); } if (plug->author) { table->field[7]->store(plug->author, strlen(plug->author), cs); table->field[7]->set_notnull(); } else table->field[7]->set_null(); if (plug->descr) { table->field[8]->store(plug->descr, strlen(plug->descr), cs); table->field[8]->set_notnull(); } else table->field[8]->set_null(); switch (plug->license) { case PLUGIN_LICENSE_GPL: table->field[9]->store(PLUGIN_LICENSE_GPL_STRING, strlen(PLUGIN_LICENSE_GPL_STRING), cs); break; case PLUGIN_LICENSE_BSD: table->field[9]->store(PLUGIN_LICENSE_BSD_STRING, strlen(PLUGIN_LICENSE_BSD_STRING), cs); break; default: table->field[9]->store(PLUGIN_LICENSE_PROPRIETARY_STRING, strlen(PLUGIN_LICENSE_PROPRIETARY_STRING), cs); break; } table->field[9]->set_notnull(); table->field[10]->store( global_plugin_typelib_names[plugin_load_option(plugin)], strlen(global_plugin_typelib_names[plugin_load_option(plugin)]), cs); return schema_table_store_record(thd, table); } int fill_plugins(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_plugins"); TABLE *table= tables->table; if (plugin_foreach_with_mask(thd, show_plugins, MYSQL_ANY_PLUGIN, ~PLUGIN_IS_FREED, table)) DBUG_RETURN(1); DBUG_RETURN(0); } /*************************************************************************** ** List all Authors. ** If you can update it, you get to be in it :) ***************************************************************************/ bool mysqld_show_authors(THD *thd) { List<Item> field_list; Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_show_authors"); field_list.push_back(new Item_empty_string("Name",40)); field_list.push_back(new Item_empty_string("Location",40)); field_list.push_back(new Item_empty_string("Comment",80)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); show_table_authors_st *authors; for (authors= show_table_authors; authors->name; authors++) { protocol->prepare_for_resend(); protocol->store(authors->name, system_charset_info); protocol->store(authors->location, system_charset_info); protocol->store(authors->comment, system_charset_info); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); } /*************************************************************************** ** List all Contributors. ** Please get permission before updating ***************************************************************************/ bool mysqld_show_contributors(THD *thd) { List<Item> field_list; Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_show_contributors"); field_list.push_back(new Item_empty_string("Name",40)); field_list.push_back(new Item_empty_string("Location",40)); field_list.push_back(new Item_empty_string("Comment",80)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); show_table_contributors_st *contributors; for (contributors= show_table_contributors; contributors->name; contributors++) { protocol->prepare_for_resend(); protocol->store(contributors->name, system_charset_info); protocol->store(contributors->location, system_charset_info); protocol->store(contributors->comment, system_charset_info); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); } /*************************************************************************** List all privileges supported ***************************************************************************/ struct show_privileges_st { const char *privilege; const char *context; const char *comment; }; static struct show_privileges_st sys_privileges[]= { {"Alter", "Tables", "To alter the table"}, {"Alter routine", "Functions,Procedures", "To alter or drop stored functions/procedures"}, {"Create", "Databases,Tables,Indexes", "To create new databases and tables"}, {"Create routine","Databases","To use CREATE FUNCTION/PROCEDURE"}, {"Create temporary tables","Databases","To use CREATE TEMPORARY TABLE"}, {"Create view", "Tables", "To create new views"}, {"Create user", "Server Admin", "To create new users"}, {"Delete", "Tables", "To delete existing rows"}, {"Drop", "Databases,Tables", "To drop databases, tables, and views"}, #ifdef HAVE_EVENT_SCHEDULER {"Event","Server Admin","To create, alter, drop and execute events"}, #endif {"Execute", "Functions,Procedures", "To execute stored routines"}, {"File", "File access on server", "To read and write files on the server"}, {"Grant option", "Databases,Tables,Functions,Procedures", "To give to other users those privileges you possess"}, {"Index", "Tables", "To create or drop indexes"}, {"Insert", "Tables", "To insert data into tables"}, {"Lock tables","Databases","To use LOCK TABLES (together with SELECT privilege)"}, {"Process", "Server Admin", "To view the plain text of currently executing queries"}, {"Proxy", "Server Admin", "To make proxy user possible"}, {"References", "Databases,Tables", "To have references on tables"}, {"Reload", "Server Admin", "To reload or refresh tables, logs and privileges"}, {"Replication client","Server Admin","To ask where the slave or master servers are"}, {"Replication slave","Server Admin","To read binary log events from the master"}, {"Select", "Tables", "To retrieve rows from table"}, {"Show databases","Server Admin","To see all databases with SHOW DATABASES"}, {"Show view","Tables","To see views with SHOW CREATE VIEW"}, {"Shutdown","Server Admin", "To shut down the server"}, {"Super","Server Admin","To use KILL thread, SET GLOBAL, CHANGE MASTER, etc."}, {"Trigger","Tables", "To use triggers"}, {"Create tablespace", "Server Admin", "To create/alter/drop tablespaces"}, {"Update", "Tables", "To update existing rows"}, {"Usage","Server Admin","No privileges - allow connect only"}, {NullS, NullS, NullS} }; bool mysqld_show_privileges(THD *thd) { List<Item> field_list; Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_show_privileges"); field_list.push_back(new Item_empty_string("Privilege",10)); field_list.push_back(new Item_empty_string("Context",15)); field_list.push_back(new Item_empty_string("Comment",NAME_CHAR_LEN)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); show_privileges_st *privilege= sys_privileges; for (privilege= sys_privileges; privilege->privilege ; privilege++) { protocol->prepare_for_resend(); protocol->store(privilege->privilege, system_charset_info); protocol->store(privilege->context, system_charset_info); protocol->store(privilege->comment, system_charset_info); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); } /* find_files() - find files in a given directory. SYNOPSIS find_files() thd thread handler files put found files in this list db database name to set in TABLE_LIST structure path path to database wild filter for found files dir read databases in path if TRUE, read .frm files in database otherwise RETURN FIND_FILES_OK success FIND_FILES_OOM out of memory error FIND_FILES_DIR no such directory, or directory can't be read */ find_files_result find_files(THD *thd, List<LEX_STRING> *files, const char *db, const char *path, const char *wild, bool dir) { uint i; char *ext; MY_DIR *dirp; FILEINFO *file; LEX_STRING *file_name= 0; uint file_name_len; #ifndef NO_EMBEDDED_ACCESS_CHECKS uint col_access=thd->col_access; #endif uint wild_length= 0; TABLE_LIST table_list; DBUG_ENTER("find_files"); if (wild) { if (!wild[0]) wild= 0; else wild_length= strlen(wild); } bzero((char*) &table_list,sizeof(table_list)); if (!(dirp = my_dir(path,MYF(dir ? MY_WANT_STAT : 0)))) { if (my_errno == ENOENT) my_error(ER_BAD_DB_ERROR, MYF(ME_BELL+ME_WAITTANG), db); else my_error(ER_CANT_READ_DIR, MYF(ME_BELL+ME_WAITTANG), path, my_errno); DBUG_RETURN(FIND_FILES_DIR); } for (i=0 ; i < (uint) dirp->number_off_files ; i++) { char uname[NAME_LEN + 1]; /* Unencoded name */ file=dirp->dir_entry+i; if (dir) { /* Return databases */ if ((file->name[0] == '.' && ((file->name[1] == '.' && file->name[2] == '\0') || file->name[1] == '\0'))) continue; /* . or .. */ #ifdef USE_SYMDIR char *ext; char buff[FN_REFLEN]; if (my_use_symdir && !strcmp(ext=fn_ext(file->name), ".sym")) { /* Only show the sym file if it points to a directory */ char *end; *ext=0; /* Remove extension */ unpack_dirname(buff, file->name); end= strend(buff); if (end != buff && end[-1] == FN_LIBCHAR) end[-1]= 0; // Remove end FN_LIBCHAR if (!mysql_file_stat(key_file_misc, buff, file->mystat, MYF(0))) continue; } #endif if (!MY_S_ISDIR(file->mystat->st_mode)) continue; file_name_len= filename_to_tablename(file->name, uname, sizeof(uname)); if (wild) { if (lower_case_table_names) { if (my_wildcmp(files_charset_info, uname, uname + file_name_len, wild, wild + wild_length, wild_prefix, wild_one,wild_many)) continue; } else if (wild_compare(uname, wild, 0)) continue; } } else { // Return only .frm files which aren't temp files. if (my_strcasecmp(system_charset_info, ext=fn_rext(file->name),reg_ext) || is_prefix(file->name, tmp_file_prefix)) continue; *ext=0; file_name_len= filename_to_tablename(file->name, uname, sizeof(uname)); if (wild) { if (lower_case_table_names) { if (my_wildcmp(files_charset_info, uname, uname + file_name_len, wild, wild + wild_length, wild_prefix, wild_one,wild_many)) continue; } else if (wild_compare(uname, wild, 0)) continue; } } #ifndef NO_EMBEDDED_ACCESS_CHECKS /* Don't show tables where we don't have any privileges */ if (db && !(col_access & TABLE_ACLS)) { table_list.db= (char*) db; table_list.db_length= strlen(db); table_list.table_name= uname; table_list.table_name_length= file_name_len; table_list.grant.privilege=col_access; if (check_grant(thd, TABLE_ACLS, &table_list, TRUE, 1, TRUE)) continue; } #endif if (!(file_name= thd->make_lex_string(file_name, uname, file_name_len, TRUE)) || files->push_back(file_name)) { my_dirend(dirp); DBUG_RETURN(FIND_FILES_OOM); } } DBUG_PRINT("info",("found: %d files", files->elements)); my_dirend(dirp); (void) ha_find_files(thd, db, path, wild, dir, files); DBUG_RETURN(FIND_FILES_OK); } /** An Internal_error_handler that suppresses errors regarding views' underlying tables that occur during privilege checking within SHOW CREATE VIEW commands. This happens in the cases when - A view's underlying table (e.g. referenced in its SELECT list) does not exist. There should not be an error as no attempt was made to access it per se. - Access is denied for some table, column, function or stored procedure such as mentioned above. This error gets raised automatically, since we can't untangle its access checking from that of the view itself. */ class Show_create_error_handler : public Internal_error_handler { TABLE_LIST *m_top_view; bool m_handling; Security_context *m_sctx; char m_view_access_denied_message[MYSQL_ERRMSG_SIZE]; char *m_view_access_denied_message_ptr; public: /** Creates a new Show_create_error_handler for the particular security context and view. @thd Thread context, used for security context information if needed. @top_view The view. We do not verify at this point that top_view is in fact a view since, alas, these things do not stay constant. */ explicit Show_create_error_handler(THD *thd, TABLE_LIST *top_view) : m_top_view(top_view), m_handling(FALSE), m_view_access_denied_message_ptr(NULL) { m_sctx = test(m_top_view->security_ctx) ? m_top_view->security_ctx : thd->security_ctx; } /** Lazy instantiation of 'view access denied' message. The purpose of the Show_create_error_handler is to hide details of underlying tables for which we have no privileges behind ER_VIEW_INVALID messages. But this obviously does not apply if we lack privileges on the view itself. Unfortunately the information about for which table privilege checking failed is not available at this point. The only way for us to check is by reconstructing the actual error message and see if it's the same. */ char* get_view_access_denied_message() { if (!m_view_access_denied_message_ptr) { m_view_access_denied_message_ptr= m_view_access_denied_message; my_snprintf(m_view_access_denied_message, MYSQL_ERRMSG_SIZE, ER(ER_TABLEACCESS_DENIED_ERROR), "SHOW VIEW", m_sctx->priv_user, m_sctx->host_or_ip, m_top_view->get_table_name()); } return m_view_access_denied_message_ptr; } bool handle_condition(THD *thd, uint sql_errno, const char * /* sqlstate */, MYSQL_ERROR::enum_warning_level level, const char *message, MYSQL_ERROR ** /* cond_hdl */) { /* The handler does not handle the errors raised by itself. At this point we know if top_view is really a view. */ if (m_handling || !m_top_view->view) return FALSE; m_handling= TRUE; bool is_handled; switch (sql_errno) { case ER_TABLEACCESS_DENIED_ERROR: if (!strcmp(get_view_access_denied_message(), message)) { /* Access to top view is not granted, don't interfere. */ is_handled= FALSE; break; } case ER_COLUMNACCESS_DENIED_ERROR: case ER_VIEW_NO_EXPLAIN: /* Error was anonymized, ignore all the same. */ case ER_PROCACCESS_DENIED_ERROR: is_handled= TRUE; break; case ER_NO_SUCH_TABLE: /* Established behavior: warn if underlying tables are missing. */ push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_VIEW_INVALID, ER(ER_VIEW_INVALID), m_top_view->get_db_name(), m_top_view->get_table_name()); is_handled= TRUE; break; case ER_SP_DOES_NOT_EXIST: /* Established behavior: warn if underlying functions are missing. */ push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_VIEW_INVALID, ER(ER_VIEW_INVALID), m_top_view->get_db_name(), m_top_view->get_table_name()); is_handled= TRUE; break; default: is_handled= FALSE; } m_handling= FALSE; return is_handled; } }; bool mysqld_show_create(THD *thd, TABLE_LIST *table_list) { Protocol *protocol= thd->protocol; char buff[2048]; String buffer(buff, sizeof(buff), system_charset_info); List<Item> field_list; bool error= TRUE; DBUG_ENTER("mysqld_show_create"); DBUG_PRINT("enter",("db: %s table: %s",table_list->db, table_list->table_name)); /* Metadata locks taken during SHOW CREATE should be released when the statmement completes as it is an information statement. */ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint(); /* We want to preserve the tree for views. */ thd->lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW; { /* Use open_tables() directly rather than open_normal_and_derived_tables(). This ensures that close_thread_tables() is not called if open tables fails and the error is ignored. This allows us to handle broken views nicely. */ uint counter; Show_create_error_handler view_error_suppressor(thd, table_list); thd->push_internal_handler(&view_error_suppressor); bool open_error= open_tables(thd, &table_list, &counter, MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL) || mysql_handle_derived(thd->lex, &mysql_derived_prepare); thd->pop_internal_handler(); if (open_error && (thd->killed || thd->is_error())) goto exit; } /* TODO: add environment variables show when it become possible */ if (thd->lex->only_view && !table_list->view) { my_error(ER_WRONG_OBJECT, MYF(0), table_list->db, table_list->table_name, "VIEW"); goto exit; } buffer.length(0); if (table_list->view) buffer.set_charset(table_list->view_creation_ctx->get_client_cs()); if ((table_list->view ? view_store_create_info(thd, table_list, &buffer) : store_create_info(thd, table_list, &buffer, NULL, FALSE /* show_database */))) goto exit; if (table_list->view) { field_list.push_back(new Item_empty_string("View",NAME_CHAR_LEN)); field_list.push_back(new Item_empty_string("Create View", max(buffer.length(),1024))); field_list.push_back(new Item_empty_string("character_set_client", MY_CS_NAME_SIZE)); field_list.push_back(new Item_empty_string("collation_connection", MY_CS_NAME_SIZE)); } else { field_list.push_back(new Item_empty_string("Table",NAME_CHAR_LEN)); // 1024 is for not to confuse old clients field_list.push_back(new Item_empty_string("Create Table", max(buffer.length(),1024))); } if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) goto exit; protocol->prepare_for_resend(); if (table_list->view) protocol->store(table_list->view_name.str, system_charset_info); else { if (table_list->schema_table) protocol->store(table_list->schema_table->table_name, system_charset_info); else protocol->store(table_list->table->alias, system_charset_info); } if (table_list->view) { protocol->store(buffer.ptr(), buffer.length(), table_list->view_creation_ctx->get_client_cs()); protocol->store(table_list->view_creation_ctx->get_client_cs()->csname, system_charset_info); protocol->store(table_list->view_creation_ctx->get_connection_cl()->name, system_charset_info); } else protocol->store(buffer.ptr(), buffer.length(), buffer.charset()); if (protocol->write()) goto exit; error= FALSE; my_eof(thd); exit: close_thread_tables(thd); /* Release any metadata locks taken during SHOW CREATE. */ thd->mdl_context.rollback_to_savepoint(mdl_savepoint); DBUG_RETURN(error); } bool mysqld_show_create_db(THD *thd, char *dbname, HA_CREATE_INFO *create_info) { char buff[2048]; String buffer(buff, sizeof(buff), system_charset_info); #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *sctx= thd->security_ctx; uint db_access; #endif HA_CREATE_INFO create; uint create_options = create_info ? create_info->options : 0; Protocol *protocol=thd->protocol; DBUG_ENTER("mysql_show_create_db"); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (test_all_bits(sctx->master_access, DB_ACLS)) db_access=DB_ACLS; else db_access= (acl_get(sctx->get_host()->ptr(), sctx->get_ip()->ptr(), sctx->priv_user, dbname, 0) | sctx->master_access); if (!(db_access & DB_ACLS) && check_grant_db(thd,dbname)) { my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), sctx->priv_user, sctx->host_or_ip, dbname); general_log_print(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR), sctx->priv_user, sctx->host_or_ip, dbname); DBUG_RETURN(TRUE); } #endif if (is_infoschema_db(dbname)) { dbname= INFORMATION_SCHEMA_NAME.str; create.default_table_charset= system_charset_info; } else { if (check_db_dir_existence(dbname)) { my_error(ER_BAD_DB_ERROR, MYF(0), dbname); DBUG_RETURN(TRUE); } load_db_opt_by_name(thd, dbname, &create); } List<Item> field_list; field_list.push_back(new Item_empty_string("Database",NAME_CHAR_LEN)); field_list.push_back(new Item_empty_string("Create Database",1024)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); protocol->prepare_for_resend(); protocol->store(dbname, strlen(dbname), system_charset_info); buffer.length(0); buffer.append(STRING_WITH_LEN("CREATE DATABASE ")); if (create_options & HA_LEX_CREATE_IF_NOT_EXISTS) buffer.append(STRING_WITH_LEN("/*!32312 IF NOT EXISTS*/ ")); append_identifier(thd, &buffer, dbname, strlen(dbname)); if (create.default_table_charset) { buffer.append(STRING_WITH_LEN(" /*!40100")); buffer.append(STRING_WITH_LEN(" DEFAULT CHARACTER SET ")); buffer.append(create.default_table_charset->csname); if (!(create.default_table_charset->state & MY_CS_PRIMARY)) { buffer.append(STRING_WITH_LEN(" COLLATE ")); buffer.append(create.default_table_charset->name); } buffer.append(STRING_WITH_LEN(" */")); } protocol->store(buffer.ptr(), buffer.length(), buffer.charset()); if (protocol->write()) DBUG_RETURN(TRUE); my_eof(thd); DBUG_RETURN(FALSE); } /**************************************************************************** Return only fields for API mysql_list_fields Use "show table wildcard" in mysql instead of this ****************************************************************************/ void mysqld_list_fields(THD *thd, TABLE_LIST *table_list, const char *wild) { TABLE *table; DBUG_ENTER("mysqld_list_fields"); DBUG_PRINT("enter",("table: %s",table_list->table_name)); if (open_normal_and_derived_tables(thd, table_list, MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL)) DBUG_VOID_RETURN; table= table_list->table; List<Item> field_list; Field **ptr,*field; for (ptr=table->field ; (field= *ptr); ptr++) { if (!wild || !wild[0] || !wild_case_compare(system_charset_info, field->field_name,wild)) { if (table_list->view) field_list.push_back(new Item_ident_for_show(field, table_list->view_db.str, table_list->view_name.str)); else field_list.push_back(new Item_field(field)); } } restore_record(table, s->default_values); // Get empty record table->use_all_columns(); if (thd->protocol->send_result_set_metadata(&field_list, Protocol::SEND_DEFAULTS)) DBUG_VOID_RETURN; my_eof(thd); DBUG_VOID_RETURN; } /* Go through all character combinations and ensure that sql_lex.cc can parse it as an identifier. SYNOPSIS require_quotes() name attribute name name_length length of name RETURN # Pointer to conflicting character 0 No conflicting character */ static const char *require_quotes(const char *name, uint name_length) { uint length; bool pure_digit= TRUE; const char *end= name + name_length; for (; name < end ; name++) { uchar chr= (uchar) *name; length= my_mbcharlen(system_charset_info, chr); if (length == 1 && !system_charset_info->ident_map[chr]) return name; if (length == 1 && (chr < '0' || chr > '9')) pure_digit= FALSE; } if (pure_digit) return name; return 0; } /* Quote the given identifier if needed and append it to the target string. If the given identifier is empty, it will be quoted. SYNOPSIS append_identifier() thd thread handler packet target string name the identifier to be appended name_length length of the appending identifier */ void append_identifier(THD *thd, String *packet, const char *name, uint length) { const char *name_end; char quote_char; int q; q= thd ? get_quote_char_for_identifier(thd, name, length) : '`'; if (q == EOF) { packet->append(name, length, packet->charset()); return; } /* The identifier must be quoted as it includes a quote character or it's a keyword */ (void) packet->reserve(length*2 + 2); quote_char= (char) q; packet->append(&quote_char, 1, system_charset_info); for (name_end= name+length ; name < name_end ; name+= length) { uchar chr= (uchar) *name; length= my_mbcharlen(system_charset_info, chr); /* my_mbcharlen can return 0 on a wrong multibyte sequence. It is possible when upgrading from 4.0, and identifier contains some accented characters. The manual says it does not work. So we'll just change length to 1 not to hang in the endless loop. */ if (!length) length= 1; if (length == 1 && chr == (uchar) quote_char) packet->append(&quote_char, 1, system_charset_info); packet->append(name, length, system_charset_info); } packet->append(&quote_char, 1, system_charset_info); } /* Get the quote character for displaying an identifier. SYNOPSIS get_quote_char_for_identifier() thd Thread handler name name to quote length length of name IMPLEMENTATION Force quoting in the following cases: - name is empty (for one, it is possible when we use this function for quoting user and host names for DEFINER clause); - name is a keyword; - name includes a special character; Otherwise identifier is quoted only if the option OPTION_QUOTE_SHOW_CREATE is set. RETURN EOF No quote character is needed # Quote character */ int get_quote_char_for_identifier(THD *thd, const char *name, uint length) { if (length && !is_keyword(name,length) && !require_quotes(name, length) && !(thd->variables.option_bits & OPTION_QUOTE_SHOW_CREATE)) return EOF; if (thd->variables.sql_mode & MODE_ANSI_QUOTES) return '"'; return '`'; } /* Append directory name (if exists) to CREATE INFO */ static void append_directory(THD *thd, String *packet, const char *dir_type, const char *filename) { if (filename && !(thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE)) { uint length= dirname_length(filename); packet->append(' '); packet->append(dir_type); packet->append(STRING_WITH_LEN(" DIRECTORY='")); #ifdef __WIN__ /* Convert \ to / to be able to create table on unix */ char *winfilename= (char*) thd->memdup(filename, length); char *pos, *end; for (pos= winfilename, end= pos+length ; pos < end ; pos++) { if (*pos == '\\') *pos = '/'; } filename= winfilename; #endif packet->append(filename, length); packet->append('\''); } } #define LIST_PROCESS_HOST_LEN 64 static bool get_field_default_value(THD *thd, Field *timestamp_field, Field *field, String *def_value, bool quoted) { bool has_default; bool has_now_default; enum enum_field_types field_type= field->type(); /* We are using CURRENT_TIMESTAMP instead of NOW because it is more standard */ has_now_default= (timestamp_field == field && field->unireg_check != Field::TIMESTAMP_UN_FIELD); has_default= (field_type != FIELD_TYPE_BLOB && !(field->flags & NO_DEFAULT_VALUE_FLAG) && field->unireg_check != Field::NEXT_NUMBER && !((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) && has_now_default)); def_value->length(0); if (has_default) { if (has_now_default) def_value->append(STRING_WITH_LEN("CURRENT_TIMESTAMP")); else if (!field->is_null()) { // Not null by default char tmp[MAX_FIELD_WIDTH]; String type(tmp, sizeof(tmp), field->charset()); if (field_type == MYSQL_TYPE_BIT) { longlong dec= field->val_int(); char *ptr= longlong2str(dec, tmp + 2, 2); uint32 length= (uint32) (ptr - tmp); tmp[0]= 'b'; tmp[1]= '\''; tmp[length]= '\''; type.length(length + 1); quoted= 0; } else field->val_str(&type); if (type.length()) { String def_val; uint dummy_errors; /* convert to system_charset_info == utf8 */ def_val.copy(type.ptr(), type.length(), field->charset(), system_charset_info, &dummy_errors); if (quoted) append_unescaped(def_value, def_val.ptr(), def_val.length()); else def_value->append(def_val.ptr(), def_val.length()); } else if (quoted) def_value->append(STRING_WITH_LEN("''")); } else if (field->maybe_null() && quoted) def_value->append(STRING_WITH_LEN("NULL")); // Null as default else return 0; } return has_default; } /* Build a CREATE TABLE statement for a table. SYNOPSIS store_create_info() thd The thread table_list A list containing one table to write statement for. packet Pointer to a string where statement will be written. create_info_arg Pointer to create information that can be used to tailor the format of the statement. Can be NULL, in which case only SQL_MODE is considered when building the statement. NOTE Currently always return 0, but might return error code in the future. RETURN 0 OK */ int store_create_info(THD *thd, TABLE_LIST *table_list, String *packet, HA_CREATE_INFO *create_info_arg, bool show_database) { List<Item> field_list; char tmp[MAX_FIELD_WIDTH], *for_str, buff[128], def_value_buf[MAX_FIELD_WIDTH]; const char *alias; String type(tmp, sizeof(tmp), system_charset_info); String def_value(def_value_buf, sizeof(def_value_buf), system_charset_info); Field **ptr,*field; uint primary_key; KEY *key_info; TABLE *table= table_list->table; handler *file= table->file; TABLE_SHARE *share= table->s; HA_CREATE_INFO create_info; #ifdef WITH_PARTITION_STORAGE_ENGINE bool show_table_options= FALSE; #endif /* WITH_PARTITION_STORAGE_ENGINE */ bool foreign_db_mode= (thd->variables.sql_mode & (MODE_POSTGRESQL | MODE_ORACLE | MODE_MSSQL | MODE_DB2 | MODE_MAXDB | MODE_ANSI)) != 0; bool limited_mysql_mode= (thd->variables.sql_mode & (MODE_NO_FIELD_OPTIONS | MODE_MYSQL323 | MODE_MYSQL40)) != 0; my_bitmap_map *old_map; int error= 0; DBUG_ENTER("store_create_info"); DBUG_PRINT("enter",("table: %s", table->s->table_name.str)); restore_record(table, s->default_values); // Get empty record if (share->tmp_table) packet->append(STRING_WITH_LEN("CREATE TEMPORARY TABLE ")); else packet->append(STRING_WITH_LEN("CREATE TABLE ")); if (create_info_arg && (create_info_arg->options & HA_LEX_CREATE_IF_NOT_EXISTS)) packet->append(STRING_WITH_LEN("IF NOT EXISTS ")); if (table_list->schema_table) alias= table_list->schema_table->table_name; else { if (lower_case_table_names == 2) alias= table->alias; else { alias= share->table_name.str; } } /* Print the database before the table name if told to do that. The database name is only printed in the event that it is different from the current database. The main reason for doing this is to avoid having to update gazillions of tests and result files, but it also saves a few bytes of the binary log. */ if (show_database) { const LEX_STRING *const db= table_list->schema_table ? &INFORMATION_SCHEMA_NAME : &table->s->db; if (!thd->db || strcmp(db->str, thd->db)) { append_identifier(thd, packet, db->str, db->length); packet->append(STRING_WITH_LEN(".")); } } append_identifier(thd, packet, alias, strlen(alias)); packet->append(STRING_WITH_LEN(" (\n")); /* We need this to get default values from the table We have to restore the read_set if we are called from insert in case of row based replication. */ old_map= tmp_use_all_columns(table, table->read_set); for (ptr=table->field ; (field= *ptr); ptr++) { uint flags = field->flags; if (ptr != table->field) packet->append(STRING_WITH_LEN(",\n")); packet->append(STRING_WITH_LEN(" ")); append_identifier(thd,packet,field->field_name, strlen(field->field_name)); packet->append(' '); // check for surprises from the previous call to Field::sql_type() if (type.ptr() != tmp) type.set(tmp, sizeof(tmp), system_charset_info); else type.set_charset(system_charset_info); field->sql_type(type); packet->append(type.ptr(), type.length(), system_charset_info); if (field->has_charset() && !(thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40))) { if (field->charset() != share->table_charset) { packet->append(STRING_WITH_LEN(" CHARACTER SET ")); packet->append(field->charset()->csname); } /* For string types dump collation name only if collation is not primary for the given charset */ if (!(field->charset()->state & MY_CS_PRIMARY)) { packet->append(STRING_WITH_LEN(" COLLATE ")); packet->append(field->charset()->name); } } if (flags & NOT_NULL_FLAG) packet->append(STRING_WITH_LEN(" NOT NULL")); else if (field->type() == MYSQL_TYPE_TIMESTAMP) { /* TIMESTAMP field require explicit NULL flag, because unlike all other fields they are treated as NOT NULL by default. */ packet->append(STRING_WITH_LEN(" NULL")); } if (get_field_default_value(thd, table->timestamp_field, field, &def_value, 1)) { packet->append(STRING_WITH_LEN(" DEFAULT ")); packet->append(def_value.ptr(), def_value.length(), system_charset_info); } if (!limited_mysql_mode && table->timestamp_field == field && field->unireg_check != Field::TIMESTAMP_DN_FIELD) packet->append(STRING_WITH_LEN(" ON UPDATE CURRENT_TIMESTAMP")); if (field->unireg_check == Field::NEXT_NUMBER && !(thd->variables.sql_mode & MODE_NO_FIELD_OPTIONS)) packet->append(STRING_WITH_LEN(" AUTO_INCREMENT")); if (field->comment.length) { packet->append(STRING_WITH_LEN(" COMMENT ")); append_unescaped(packet, field->comment.str, field->comment.length); } } key_info= table->key_info; bzero((char*) &create_info, sizeof(create_info)); /* Allow update_create_info to update row type */ create_info.row_type= share->row_type; file->update_create_info(&create_info); primary_key= share->primary_key; for (uint i=0 ; i < share->keys ; i++,key_info++) { KEY_PART_INFO *key_part= key_info->key_part; bool found_primary=0; packet->append(STRING_WITH_LEN(",\n ")); if (i == primary_key && !strcmp(key_info->name, primary_key_name)) { found_primary=1; /* No space at end, because a space will be added after where the identifier would go, but that is not added for primary key. */ packet->append(STRING_WITH_LEN("PRIMARY KEY")); } else if (key_info->flags & HA_NOSAME) packet->append(STRING_WITH_LEN("UNIQUE KEY ")); else if (key_info->flags & HA_FULLTEXT) packet->append(STRING_WITH_LEN("FULLTEXT KEY ")); else if (key_info->flags & HA_SPATIAL) packet->append(STRING_WITH_LEN("SPATIAL KEY ")); else packet->append(STRING_WITH_LEN("KEY ")); if (!found_primary) append_identifier(thd, packet, key_info->name, strlen(key_info->name)); packet->append(STRING_WITH_LEN(" (")); for (uint j=0 ; j < key_info->key_parts ; j++,key_part++) { if (j) packet->append(','); if (key_part->field) append_identifier(thd,packet,key_part->field->field_name, strlen(key_part->field->field_name)); if (key_part->field && (key_part->length != table->field[key_part->fieldnr-1]->key_length() && !(key_info->flags & (HA_FULLTEXT | HA_SPATIAL)))) { char *end; buff[0] = '('; end= int10_to_str((long) key_part->length / key_part->field->charset()->mbmaxlen, buff + 1,10); *end++ = ')'; packet->append(buff,(uint) (end-buff)); } } packet->append(')'); store_key_options(thd, packet, table, key_info); if (key_info->parser) { LEX_STRING *parser_name= plugin_name(key_info->parser); packet->append(STRING_WITH_LEN(" /*!50100 WITH PARSER ")); append_identifier(thd, packet, parser_name->str, parser_name->length); packet->append(STRING_WITH_LEN(" */ ")); } } /* Get possible foreign key definitions stored in InnoDB and append them to the CREATE TABLE statement */ if ((for_str= file->get_foreign_key_create_info())) { packet->append(for_str, strlen(for_str)); file->free_foreign_key_create_info(for_str); } packet->append(STRING_WITH_LEN("\n)")); if (!(thd->variables.sql_mode & MODE_NO_TABLE_OPTIONS) && !foreign_db_mode) { #ifdef WITH_PARTITION_STORAGE_ENGINE show_table_options= TRUE; #endif /* WITH_PARTITION_STORAGE_ENGINE */ /* TABLESPACE and STORAGE */ if (share->tablespace || share->default_storage_media != HA_SM_DEFAULT) { packet->append(STRING_WITH_LEN(" /*!50100")); if (share->tablespace) { packet->append(STRING_WITH_LEN(" TABLESPACE ")); packet->append(share->tablespace, strlen(share->tablespace)); } if (share->default_storage_media == HA_SM_DISK) packet->append(STRING_WITH_LEN(" STORAGE DISK")); if (share->default_storage_media == HA_SM_MEMORY) packet->append(STRING_WITH_LEN(" STORAGE MEMORY")); packet->append(STRING_WITH_LEN(" */")); } /* IF check_create_info THEN add ENGINE only if it was used when creating the table */ if (!create_info_arg || (create_info_arg->used_fields & HA_CREATE_USED_ENGINE)) { if (thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) packet->append(STRING_WITH_LEN(" TYPE=")); else packet->append(STRING_WITH_LEN(" ENGINE=")); #ifdef WITH_PARTITION_STORAGE_ENGINE if (table->part_info) packet->append(ha_resolve_storage_engine_name( table->part_info->default_engine_type)); else packet->append(file->table_type()); #else packet->append(file->table_type()); #endif } /* Add AUTO_INCREMENT=... if there is an AUTO_INCREMENT column, and NEXT_ID > 1 (the default). We must not print the clause for engines that do not support this as it would break the import of dumps, but as of this writing, the test for whether AUTO_INCREMENT columns are allowed and wether AUTO_INCREMENT=... is supported is identical, !(file->table_flags() & HA_NO_AUTO_INCREMENT)) Because of that, we do not explicitly test for the feature, but may extrapolate its existence from that of an AUTO_INCREMENT column. */ if (create_info.auto_increment_value > 1) { char *end; packet->append(STRING_WITH_LEN(" AUTO_INCREMENT=")); end= longlong10_to_str(create_info.auto_increment_value, buff,10); packet->append(buff, (uint) (end - buff)); } if (share->table_charset && !(thd->variables.sql_mode & MODE_MYSQL323) && !(thd->variables.sql_mode & MODE_MYSQL40)) { /* IF check_create_info THEN add DEFAULT CHARSET only if it was used when creating the table */ if (!create_info_arg || (create_info_arg->used_fields & HA_CREATE_USED_DEFAULT_CHARSET)) { packet->append(STRING_WITH_LEN(" DEFAULT CHARSET=")); packet->append(share->table_charset->csname); if (!(share->table_charset->state & MY_CS_PRIMARY)) { packet->append(STRING_WITH_LEN(" COLLATE=")); packet->append(table->s->table_charset->name); } } } if (share->min_rows) { char *end; packet->append(STRING_WITH_LEN(" MIN_ROWS=")); end= longlong10_to_str(share->min_rows, buff, 10); packet->append(buff, (uint) (end- buff)); } if (share->max_rows && !table_list->schema_table) { char *end; packet->append(STRING_WITH_LEN(" MAX_ROWS=")); end= longlong10_to_str(share->max_rows, buff, 10); packet->append(buff, (uint) (end - buff)); } if (share->avg_row_length) { char *end; packet->append(STRING_WITH_LEN(" AVG_ROW_LENGTH=")); end= longlong10_to_str(share->avg_row_length, buff,10); packet->append(buff, (uint) (end - buff)); } if (share->db_create_options & HA_OPTION_PACK_KEYS) packet->append(STRING_WITH_LEN(" PACK_KEYS=1")); if (share->db_create_options & HA_OPTION_NO_PACK_KEYS) packet->append(STRING_WITH_LEN(" PACK_KEYS=0")); /* We use CHECKSUM, instead of TABLE_CHECKSUM, for backward compability */ if (share->db_create_options & HA_OPTION_CHECKSUM) packet->append(STRING_WITH_LEN(" CHECKSUM=1")); if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE) packet->append(STRING_WITH_LEN(" DELAY_KEY_WRITE=1")); if (create_info.row_type != ROW_TYPE_DEFAULT) { packet->append(STRING_WITH_LEN(" ROW_FORMAT=")); packet->append(ha_row_type[(uint) create_info.row_type]); } if (table->s->key_block_size) { char *end; packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE=")); end= longlong10_to_str(table->s->key_block_size, buff, 10); packet->append(buff, (uint) (end - buff)); } table->file->append_create_info(packet); if (share->comment.length) { packet->append(STRING_WITH_LEN(" COMMENT=")); append_unescaped(packet, share->comment.str, share->comment.length); } if (share->connect_string.length) { packet->append(STRING_WITH_LEN(" CONNECTION=")); append_unescaped(packet, share->connect_string.str, share->connect_string.length); } append_directory(thd, packet, "DATA", create_info.data_file_name); append_directory(thd, packet, "INDEX", create_info.index_file_name); } #ifdef WITH_PARTITION_STORAGE_ENGINE { if (table->part_info && !((table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION) && table->part_info->is_auto_partitioned)) { /* Partition syntax for CREATE TABLE is at the end of the syntax. */ uint part_syntax_len; char *part_syntax; String comment_start; table->part_info->set_show_version_string(&comment_start); if ((part_syntax= generate_partition_syntax(table->part_info, &part_syntax_len, FALSE, show_table_options, NULL, NULL, comment_start.c_ptr()))) { packet->append(comment_start); if (packet->append(part_syntax, part_syntax_len) || packet->append(STRING_WITH_LEN(" */"))) error= 1; my_free(part_syntax); } } } #endif tmp_restore_column_map(table->read_set, old_map); DBUG_RETURN(error); } static void store_key_options(THD *thd, String *packet, TABLE *table, KEY *key_info) { bool limited_mysql_mode= (thd->variables.sql_mode & (MODE_NO_FIELD_OPTIONS | MODE_MYSQL323 | MODE_MYSQL40)) != 0; bool foreign_db_mode= (thd->variables.sql_mode & (MODE_POSTGRESQL | MODE_ORACLE | MODE_MSSQL | MODE_DB2 | MODE_MAXDB | MODE_ANSI)) != 0; char *end, buff[32]; if (!(thd->variables.sql_mode & MODE_NO_KEY_OPTIONS) && !limited_mysql_mode && !foreign_db_mode) { if (key_info->algorithm == HA_KEY_ALG_BTREE) packet->append(STRING_WITH_LEN(" USING BTREE")); if (key_info->algorithm == HA_KEY_ALG_HASH) packet->append(STRING_WITH_LEN(" USING HASH")); /* send USING only in non-default case: non-spatial rtree */ if ((key_info->algorithm == HA_KEY_ALG_RTREE) && !(key_info->flags & HA_SPATIAL)) packet->append(STRING_WITH_LEN(" USING RTREE")); if ((key_info->flags & HA_USES_BLOCK_SIZE) && table->s->key_block_size != key_info->block_size) { packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE=")); end= longlong10_to_str(key_info->block_size, buff, 10); packet->append(buff, (uint) (end - buff)); } DBUG_ASSERT(test(key_info->flags & HA_USES_COMMENT) == (key_info->comment.length > 0)); if (key_info->flags & HA_USES_COMMENT) { packet->append(STRING_WITH_LEN(" COMMENT ")); append_unescaped(packet, key_info->comment.str, key_info->comment.length); } } } void view_store_options(THD *thd, TABLE_LIST *table, String *buff) { append_algorithm(table, buff); append_definer(thd, buff, &table->definer.user, &table->definer.host); if (table->view_suid) buff->append(STRING_WITH_LEN("SQL SECURITY DEFINER ")); else buff->append(STRING_WITH_LEN("SQL SECURITY INVOKER ")); } /* Append DEFINER clause to the given buffer. SYNOPSIS append_definer() thd [in] thread handle buffer [inout] buffer to hold DEFINER clause definer_user [in] user name part of definer definer_host [in] host name part of definer */ static void append_algorithm(TABLE_LIST *table, String *buff) { buff->append(STRING_WITH_LEN("ALGORITHM=")); switch ((int8)table->algorithm) { case VIEW_ALGORITHM_UNDEFINED: buff->append(STRING_WITH_LEN("UNDEFINED ")); break; case VIEW_ALGORITHM_TMPTABLE: buff->append(STRING_WITH_LEN("TEMPTABLE ")); break; case VIEW_ALGORITHM_MERGE: buff->append(STRING_WITH_LEN("MERGE ")); break; default: DBUG_ASSERT(0); // never should happen } } /* Append DEFINER clause to the given buffer. SYNOPSIS append_definer() thd [in] thread handle buffer [inout] buffer to hold DEFINER clause definer_user [in] user name part of definer definer_host [in] host name part of definer */ void append_definer(THD *thd, String *buffer, const LEX_STRING *definer_user, const LEX_STRING *definer_host) { buffer->append(STRING_WITH_LEN("DEFINER=")); append_identifier(thd, buffer, definer_user->str, definer_user->length); buffer->append('@'); append_identifier(thd, buffer, definer_host->str, definer_host->length); buffer->append(' '); } int view_store_create_info(THD *thd, TABLE_LIST *table, String *buff) { my_bool compact_view_name= TRUE; my_bool foreign_db_mode= (thd->variables.sql_mode & (MODE_POSTGRESQL | MODE_ORACLE | MODE_MSSQL | MODE_DB2 | MODE_MAXDB | MODE_ANSI)) != 0; if (!thd->db || strcmp(thd->db, table->view_db.str)) /* print compact view name if the view belongs to the current database */ compact_view_name= table->compact_view_format= FALSE; else { /* Compact output format for view body can be used if this view only references table inside it's own db */ TABLE_LIST *tbl; table->compact_view_format= TRUE; for (tbl= thd->lex->query_tables; tbl; tbl= tbl->next_global) { if (strcmp(table->view_db.str, tbl->view ? tbl->view_db.str :tbl->db)!= 0) { table->compact_view_format= FALSE; break; } } } buff->append(STRING_WITH_LEN("CREATE ")); if (!foreign_db_mode) { view_store_options(thd, table, buff); } buff->append(STRING_WITH_LEN("VIEW ")); if (!compact_view_name) { append_identifier(thd, buff, table->view_db.str, table->view_db.length); buff->append('.'); } append_identifier(thd, buff, table->view_name.str, table->view_name.length); buff->append(STRING_WITH_LEN(" AS ")); /* We can't just use table->query, because our SQL_MODE may trigger a different syntax, like when ANSI_QUOTES is defined. */ table->view->unit.print(buff, QT_ORDINARY); if (table->with_check != VIEW_CHECK_NONE) { if (table->with_check == VIEW_CHECK_LOCAL) buff->append(STRING_WITH_LEN(" WITH LOCAL CHECK OPTION")); else buff->append(STRING_WITH_LEN(" WITH CASCADED CHECK OPTION")); } return 0; } /**************************************************************************** Return info about all processes returns for each thread: thread id, user, host, db, command, info ****************************************************************************/ class thread_info :public ilink { public: static void *operator new(size_t size) { return (void*) sql_alloc((uint) size); } static void operator delete(void *ptr __attribute__((unused)), size_t size __attribute__((unused))) { TRASH(ptr, size); } ulong thread_id; time_t start_time; uint command; const char *user,*host,*db,*proc_info,*state_info; CSET_STRING query_string; }; #ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION template class I_List<thread_info>; #endif static const char *thread_state_info(THD *tmp) { #ifndef EMBEDDED_LIBRARY if (tmp->net.reading_or_writing) { if (tmp->net.reading_or_writing == 2) return "Writing to net"; else if (tmp->command == COM_SLEEP) return ""; else return "Reading from net"; } else #endif { if (tmp->proc_info) return tmp->proc_info; else if (tmp->mysys_var && tmp->mysys_var->current_cond) return "Waiting on cond"; else return NULL; } } void mysqld_list_processes(THD *thd,const char *user, bool verbose) { Item *field; List<Item> field_list; I_List<thread_info> thread_infos; ulong max_query_length= (verbose ? thd->variables.max_allowed_packet : PROCESS_LIST_WIDTH); Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_list_processes"); field_list.push_back(new Item_int("Id", 0, MY_INT32_NUM_DECIMAL_DIGITS)); field_list.push_back(new Item_empty_string("User",16)); field_list.push_back(new Item_empty_string("Host",LIST_PROCESS_HOST_LEN)); field_list.push_back(field=new Item_empty_string("db",NAME_CHAR_LEN)); field->maybe_null=1; field_list.push_back(new Item_empty_string("Command",16)); field_list.push_back(field= new Item_return_int("Time",7, MYSQL_TYPE_LONG)); field->unsigned_flag= 0; field_list.push_back(field=new Item_empty_string("State",30)); field->maybe_null=1; field_list.push_back(field=new Item_empty_string("Info",max_query_length)); field->maybe_null=1; if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_VOID_RETURN; mysql_mutex_lock(&LOCK_thread_count); // For unlink from list if (!thd->killed) { I_List_iterator<THD> it(threads); THD *tmp; while ((tmp=it++)) { Security_context *tmp_sctx= tmp->security_ctx; struct st_my_thread_var *mysys_var; if ((tmp->vio_ok() || tmp->system_thread) && (!user || (tmp_sctx->user && !strcmp(tmp_sctx->user, user)))) { thread_info *thd_info= new thread_info; thd_info->thread_id=tmp->thread_id; thd_info->user= thd->strdup(tmp_sctx->user ? tmp_sctx->user : (tmp->system_thread ? "system user" : "unauthenticated user")); if (tmp->peer_port && (tmp_sctx->get_host()->length() || tmp_sctx->get_ip()->length()) && thd->security_ctx->host_or_ip[0]) { if ((thd_info->host= (char*) thd->alloc(LIST_PROCESS_HOST_LEN+1))) my_snprintf((char *) thd_info->host, LIST_PROCESS_HOST_LEN, "%s:%u", tmp_sctx->host_or_ip, tmp->peer_port); } else thd_info->host= thd->strdup(tmp_sctx->host_or_ip[0] ? tmp_sctx->host_or_ip : tmp_sctx->get_host()->length() ? tmp_sctx->get_host()->ptr() : ""); thd_info->command=(int) tmp->command; mysql_mutex_lock(&tmp->LOCK_thd_data); if ((thd_info->db= tmp->db)) // Safe test thd_info->db= thd->strdup(thd_info->db); if ((mysys_var= tmp->mysys_var)) mysql_mutex_lock(&mysys_var->mutex); thd_info->proc_info= (char*) (tmp->killed == THD::KILL_CONNECTION? "Killed" : 0); thd_info->state_info= thread_state_info(tmp); if (mysys_var) mysql_mutex_unlock(&mysys_var->mutex); /* Lock THD mutex that protects its data when looking at it. */ if (tmp->query()) { uint length= min(max_query_length, tmp->query_length()); char *q= thd->strmake(tmp->query(),length); /* Safety: in case strmake failed, we set length to 0. */ thd_info->query_string= CSET_STRING(q, q ? length : 0, tmp->query_charset()); } mysql_mutex_unlock(&tmp->LOCK_thd_data); thd_info->start_time= tmp->start_time; thread_infos.append(thd_info); } } } mysql_mutex_unlock(&LOCK_thread_count); thread_info *thd_info; time_t now= my_time(0); while ((thd_info=thread_infos.get())) { protocol->prepare_for_resend(); protocol->store((ulonglong) thd_info->thread_id); protocol->store(thd_info->user, system_charset_info); protocol->store(thd_info->host, system_charset_info); protocol->store(thd_info->db, system_charset_info); if (thd_info->proc_info) protocol->store(thd_info->proc_info, system_charset_info); else protocol->store(command_name[thd_info->command].str, system_charset_info); if (thd_info->start_time) protocol->store_long ((longlong) (now - thd_info->start_time)); else protocol->store_null(); protocol->store(thd_info->state_info, system_charset_info); protocol->store(thd_info->query_string.str(), thd_info->query_string.charset()); if (protocol->write()) break; /* purecov: inspected */ } my_eof(thd); DBUG_VOID_RETURN; } int fill_schema_processlist(THD* thd, TABLE_LIST* tables, COND* cond) { TABLE *table= tables->table; CHARSET_INFO *cs= system_charset_info; char *user; time_t now= my_time(0); DBUG_ENTER("fill_process_list"); user= thd->security_ctx->master_access & PROCESS_ACL ? NullS : thd->security_ctx->priv_user; mysql_mutex_lock(&LOCK_thread_count); if (!thd->killed) { I_List_iterator<THD> it(threads); THD* tmp; while ((tmp= it++)) { Security_context *tmp_sctx= tmp->security_ctx; struct st_my_thread_var *mysys_var; const char *val, *db; if ((!tmp->vio_ok() && !tmp->system_thread) || (user && (!tmp_sctx->user || strcmp(tmp_sctx->user, user)))) continue; restore_record(table, s->default_values); /* ID */ table->field[0]->store((longlong) tmp->thread_id, TRUE); /* USER */ val= tmp_sctx->user ? tmp_sctx->user : (tmp->system_thread ? "system user" : "unauthenticated user"); table->field[1]->store(val, strlen(val), cs); /* HOST */ if (tmp->peer_port && (tmp_sctx->get_host()->length() || tmp_sctx->get_ip()->length()) && thd->security_ctx->host_or_ip[0]) { char host[LIST_PROCESS_HOST_LEN + 1]; my_snprintf(host, LIST_PROCESS_HOST_LEN, "%s:%u", tmp_sctx->host_or_ip, tmp->peer_port); table->field[2]->store(host, strlen(host), cs); } else table->field[2]->store(tmp_sctx->host_or_ip, strlen(tmp_sctx->host_or_ip), cs); /* DB */ mysql_mutex_lock(&tmp->LOCK_thd_data); if ((db= tmp->db)) { table->field[3]->store(db, strlen(db), cs); table->field[3]->set_notnull(); } if ((mysys_var= tmp->mysys_var)) mysql_mutex_lock(&mysys_var->mutex); /* COMMAND */ if ((val= (char *) (tmp->killed == THD::KILL_CONNECTION? "Killed" : 0))) table->field[4]->store(val, strlen(val), cs); else table->field[4]->store(command_name[tmp->command].str, command_name[tmp->command].length, cs); /* MYSQL_TIME */ table->field[5]->store((longlong)(tmp->start_time ? now - tmp->start_time : 0), FALSE); /* STATE */ if ((val= thread_state_info(tmp))) { table->field[6]->store(val, strlen(val), cs); table->field[6]->set_notnull(); } if (mysys_var) mysql_mutex_unlock(&mysys_var->mutex); mysql_mutex_unlock(&tmp->LOCK_thd_data); /* INFO */ /* Lock THD mutex that protects its data when looking at it. */ mysql_mutex_lock(&tmp->LOCK_thd_data); if (tmp->query()) { table->field[7]->store(tmp->query(), min(PROCESS_LIST_INFO_WIDTH, tmp->query_length()), cs); table->field[7]->set_notnull(); } mysql_mutex_unlock(&tmp->LOCK_thd_data); if (schema_table_store_record(thd, table)) { mysql_mutex_unlock(&LOCK_thread_count); DBUG_RETURN(1); } } } mysql_mutex_unlock(&LOCK_thread_count); DBUG_RETURN(0); } /***************************************************************************** Status functions *****************************************************************************/ static DYNAMIC_ARRAY all_status_vars; static bool status_vars_inited= 0; C_MODE_START static int show_var_cmp(const void *var1, const void *var2) { return strcmp(((SHOW_VAR*)var1)->name, ((SHOW_VAR*)var2)->name); } C_MODE_END /* deletes all the SHOW_UNDEF elements from the array and calls delete_dynamic() if it's completely empty. */ static void shrink_var_array(DYNAMIC_ARRAY *array) { uint a,b; SHOW_VAR *all= dynamic_element(array, 0, SHOW_VAR *); for (a= b= 0; b < array->elements; b++) if (all[b].type != SHOW_UNDEF) all[a++]= all[b]; if (a) { bzero(all+a, sizeof(SHOW_VAR)); // writing NULL-element to the end array->elements= a; } else // array is completely empty - delete it delete_dynamic(array); } /* Adds an array of SHOW_VAR entries to the output of SHOW STATUS SYNOPSIS add_status_vars(SHOW_VAR *list) list - an array of SHOW_VAR entries to add to all_status_vars the last entry must be {0,0,SHOW_UNDEF} NOTE The handling of all_status_vars[] is completely internal, it's allocated automatically when something is added to it, and deleted completely when the last entry is removed. As a special optimization, if add_status_vars() is called before init_status_vars(), it assumes "startup mode" - neither concurrent access to the array nor SHOW STATUS are possible (thus it skips locks and qsort) The last entry of the all_status_vars[] should always be {0,0,SHOW_UNDEF} */ int add_status_vars(SHOW_VAR *list) { int res= 0; if (status_vars_inited) mysql_mutex_lock(&LOCK_status); if (!all_status_vars.buffer && // array is not allocated yet - do it now my_init_dynamic_array(&all_status_vars, sizeof(SHOW_VAR), 200, 20)) { res= 1; goto err; } while (list->name) res|= insert_dynamic(&all_status_vars, (uchar*)list++); res|= insert_dynamic(&all_status_vars, (uchar*)list); // appending NULL-element all_status_vars.elements--; // but next insert_dynamic should overwite it if (status_vars_inited) sort_dynamic(&all_status_vars, show_var_cmp); err: if (status_vars_inited) mysql_mutex_unlock(&LOCK_status); return res; } /* Make all_status_vars[] usable for SHOW STATUS NOTE See add_status_vars(). Before init_status_vars() call, add_status_vars() works in a special fast "startup" mode. Thus init_status_vars() should be called as late as possible but before enabling multi-threading. */ void init_status_vars() { status_vars_inited=1; sort_dynamic(&all_status_vars, show_var_cmp); } void reset_status_vars() { SHOW_VAR *ptr= (SHOW_VAR*) all_status_vars.buffer; SHOW_VAR *last= ptr + all_status_vars.elements; for (; ptr < last; ptr++) { /* Note that SHOW_LONG_NOFLUSH variables are not reset */ if (ptr->type == SHOW_LONG) *(ulong*) ptr->value= 0; } } /* catch-all cleanup function, cleans up everything no matter what DESCRIPTION This function is not strictly required if all add_to_status/ remove_status_vars are properly paired, but it's a safety measure that deletes everything from the all_status_vars[] even if some remove_status_vars were forgotten */ void free_status_vars() { delete_dynamic(&all_status_vars); } /* Removes an array of SHOW_VAR entries from the output of SHOW STATUS SYNOPSIS remove_status_vars(SHOW_VAR *list) list - an array of SHOW_VAR entries to remove to all_status_vars the last entry must be {0,0,SHOW_UNDEF} NOTE there's lots of room for optimizing this, especially in non-sorted mode, but nobody cares - it may be called only in case of failed plugin initialization in the mysqld startup. */ void remove_status_vars(SHOW_VAR *list) { if (status_vars_inited) { mysql_mutex_lock(&LOCK_status); SHOW_VAR *all= dynamic_element(&all_status_vars, 0, SHOW_VAR *); int a= 0, b= all_status_vars.elements, c= (a+b)/2; for (; list->name; list++) { int res= 0; for (a= 0, b= all_status_vars.elements; b-a > 1; c= (a+b)/2) { res= show_var_cmp(list, all+c); if (res < 0) b= c; else if (res > 0) a= c; else break; } if (res == 0) all[c].type= SHOW_UNDEF; } shrink_var_array(&all_status_vars); mysql_mutex_unlock(&LOCK_status); } else { SHOW_VAR *all= dynamic_element(&all_status_vars, 0, SHOW_VAR *); uint i; for (; list->name; list++) { for (i= 0; i < all_status_vars.elements; i++) { if (show_var_cmp(list, all+i)) continue; all[i].type= SHOW_UNDEF; break; } } shrink_var_array(&all_status_vars); } } inline void make_upper(char *buf) { for (; *buf; buf++) *buf= my_toupper(system_charset_info, *buf); } static bool show_status_array(THD *thd, const char *wild, SHOW_VAR *variables, enum enum_var_type value_type, struct system_status_var *status_var, const char *prefix, TABLE *table, bool ucase_names, COND *cond) { my_aligned_storage<SHOW_VAR_FUNC_BUFF_SIZE, MY_ALIGNOF(long)> buffer; char * const buff= buffer.data; char *prefix_end; /* the variable name should not be longer than 64 characters */ char name_buffer[64]; int len; LEX_STRING null_lex_str; SHOW_VAR tmp, *var; COND *partial_cond= 0; enum_check_fields save_count_cuted_fields= thd->count_cuted_fields; bool res= FALSE; CHARSET_INFO *charset= system_charset_info; DBUG_ENTER("show_status_array"); thd->count_cuted_fields= CHECK_FIELD_WARN; null_lex_str.str= 0; // For sys_var->value_ptr() null_lex_str.length= 0; prefix_end=strnmov(name_buffer, prefix, sizeof(name_buffer)-1); if (*prefix) *prefix_end++= '_'; len=name_buffer + sizeof(name_buffer) - prefix_end; partial_cond= make_cond_for_info_schema(cond, table->pos_in_table_list); for (; variables->name; variables++) { strnmov(prefix_end, variables->name, len); name_buffer[sizeof(name_buffer)-1]=0; /* Safety */ if (ucase_names) make_upper(name_buffer); restore_record(table, s->default_values); table->field[0]->store(name_buffer, strlen(name_buffer), system_charset_info); /* if var->type is SHOW_FUNC, call the function. Repeat as necessary, if new var is again SHOW_FUNC */ for (var=variables; var->type == SHOW_FUNC; var= &tmp) ((mysql_show_var_func)(var->value))(thd, &tmp, buff); SHOW_TYPE show_type=var->type; if (show_type == SHOW_ARRAY) { show_status_array(thd, wild, (SHOW_VAR *) var->value, value_type, status_var, name_buffer, table, ucase_names, partial_cond); } else { if (!(wild && wild[0] && wild_case_compare(system_charset_info, name_buffer, wild)) && (!partial_cond || partial_cond->val_int())) { char *value=var->value; const char *pos, *end; // We assign a lot of const's mysql_mutex_lock(&LOCK_global_system_variables); if (show_type == SHOW_SYS) { sys_var *var= ((sys_var *) value); show_type= var->show_type(); value= (char*) var->value_ptr(thd, value_type, &null_lex_str); charset= var->charset(thd); } pos= end= buff; /* note that value may be == buff. All SHOW_xxx code below should still work in this case */ switch (show_type) { case SHOW_DOUBLE_STATUS: value= ((char *) status_var + (ulong) value); /* fall through */ case SHOW_DOUBLE: /* 6 is the default precision for '%f' in sprintf() */ end= buff + my_fcvt(*(double *) value, 6, buff, NULL); break; case SHOW_LONG_STATUS: value= ((char *) status_var + (ulong) value); /* fall through */ case SHOW_LONG: case SHOW_LONG_NOFLUSH: // the difference lies in refresh_status() end= int10_to_str(*(long*) value, buff, 10); break; case SHOW_LONGLONG_STATUS: value= ((char *) status_var + (ulong) value); /* fall through */ case SHOW_LONGLONG: end= longlong10_to_str(*(longlong*) value, buff, 10); break; case SHOW_HA_ROWS: end= longlong10_to_str((longlong) *(ha_rows*) value, buff, 10); break; case SHOW_BOOL: end= strmov(buff, *(bool*) value ? "ON" : "OFF"); break; case SHOW_MY_BOOL: end= strmov(buff, *(my_bool*) value ? "ON" : "OFF"); break; case SHOW_INT: end= int10_to_str((long) *(uint32*) value, buff, 10); break; case SHOW_HAVE: { SHOW_COMP_OPTION tmp= *(SHOW_COMP_OPTION*) value; pos= show_comp_option_name[(int) tmp]; end= strend(pos); break; } case SHOW_CHAR: { if (!(pos= value)) pos= ""; end= strend(pos); break; } case SHOW_CHAR_PTR: { if (!(pos= *(char**) value)) pos= ""; DBUG_EXECUTE_IF("alter_server_version_str", if (!my_strcasecmp(system_charset_info, variables->name, "version")) { pos= "some-other-version"; }); end= strend(pos); break; } case SHOW_LEX_STRING: { LEX_STRING *ls=(LEX_STRING*)value; if (!(pos= ls->str)) end= pos= ""; else end= pos + ls->length; break; } case SHOW_KEY_CACHE_LONG: value= (char*) dflt_key_cache + (ulong)value; end= int10_to_str(*(long*) value, buff, 10); break; case SHOW_KEY_CACHE_LONGLONG: value= (char*) dflt_key_cache + (ulong)value; end= longlong10_to_str(*(longlong*) value, buff, 10); break; case SHOW_UNDEF: break; // Return empty string case SHOW_SYS: // Cannot happen default: DBUG_ASSERT(0); break; } table->field[1]->store(pos, (uint32) (end - pos), charset); thd->count_cuted_fields= CHECK_FIELD_IGNORE; table->field[1]->set_notnull(); mysql_mutex_unlock(&LOCK_global_system_variables); if (schema_table_store_record(thd, table)) { res= TRUE; goto end; } } } } end: thd->count_cuted_fields= save_count_cuted_fields; DBUG_RETURN(res); } /* collect status for all running threads */ void calc_sum_of_all_status(STATUS_VAR *to) { DBUG_ENTER("calc_sum_of_all_status"); /* Ensure that thread id not killed during loop */ mysql_mutex_lock(&LOCK_thread_count); // For unlink from list I_List_iterator<THD> it(threads); THD *tmp; /* Get global values as base */ *to= global_status_var; /* Add to this status from existing threads */ while ((tmp= it++)) add_to_status(to, &tmp->status_var); mysql_mutex_unlock(&LOCK_thread_count); DBUG_VOID_RETURN; } /* This is only used internally, but we need it here as a forward reference */ extern ST_SCHEMA_TABLE schema_tables[]; typedef struct st_lookup_field_values { LEX_STRING db_value, table_value; bool wild_db_value, wild_table_value; } LOOKUP_FIELD_VALUES; /* Store record to I_S table, convert HEAP table to MyISAM if necessary SYNOPSIS schema_table_store_record() thd thread handler table Information schema table to be updated RETURN 0 success 1 error */ bool schema_table_store_record(THD *thd, TABLE *table) { int error; if ((error= table->file->ha_write_row(table->record[0]))) { if (create_myisam_from_heap(thd, table, table->pos_in_table_list->schema_table_param, error, 0)) return 1; } return 0; } static int make_table_list(THD *thd, SELECT_LEX *sel, LEX_STRING *db_name, LEX_STRING *table_name) { Table_ident *table_ident; table_ident= new Table_ident(thd, *db_name, *table_name, 1); if (!sel->add_table_to_list(thd, table_ident, 0, 0, TL_READ, MDL_SHARED_READ)) return 1; return 0; } /** @brief Get lookup value from the part of 'WHERE' condition @details This function gets lookup value from the part of 'WHERE' condition if it's possible and fill appropriate lookup_field_vals struct field with this value. @param[in] thd thread handler @param[in] item_func part of WHERE condition @param[in] table I_S table @param[in, out] lookup_field_vals Struct which holds lookup values @return 0 success 1 error, there can be no matching records for the condition */ bool get_lookup_value(THD *thd, Item_func *item_func, TABLE_LIST *table, LOOKUP_FIELD_VALUES *lookup_field_vals) { ST_SCHEMA_TABLE *schema_table= table->schema_table; ST_FIELD_INFO *field_info= schema_table->fields_info; const char *field_name1= schema_table->idx_field1 >= 0 ? field_info[schema_table->idx_field1].field_name : ""; const char *field_name2= schema_table->idx_field2 >= 0 ? field_info[schema_table->idx_field2].field_name : ""; if (item_func->functype() == Item_func::EQ_FUNC || item_func->functype() == Item_func::EQUAL_FUNC) { int idx_field, idx_val; char tmp[MAX_FIELD_WIDTH]; String *tmp_str, str_buff(tmp, sizeof(tmp), system_charset_info); Item_field *item_field; CHARSET_INFO *cs= system_charset_info; if (item_func->arguments()[0]->type() == Item::FIELD_ITEM && item_func->arguments()[1]->const_item()) { idx_field= 0; idx_val= 1; } else if (item_func->arguments()[1]->type() == Item::FIELD_ITEM && item_func->arguments()[0]->const_item()) { idx_field= 1; idx_val= 0; } else return 0; item_field= (Item_field*) item_func->arguments()[idx_field]; if (table->table != item_field->field->table) return 0; tmp_str= item_func->arguments()[idx_val]->val_str(&str_buff); /* impossible value */ if (!tmp_str) return 1; /* Lookup value is database name */ if (!cs->coll->strnncollsp(cs, (uchar *) field_name1, strlen(field_name1), (uchar *) item_field->field_name, strlen(item_field->field_name), 0)) { thd->make_lex_string(&lookup_field_vals->db_value, tmp_str->ptr(), tmp_str->length(), FALSE); } /* Lookup value is table name */ else if (!cs->coll->strnncollsp(cs, (uchar *) field_name2, strlen(field_name2), (uchar *) item_field->field_name, strlen(item_field->field_name), 0)) { thd->make_lex_string(&lookup_field_vals->table_value, tmp_str->ptr(), tmp_str->length(), FALSE); } } return 0; } /** @brief Calculates lookup values from 'WHERE' condition @details This function calculates lookup value(database name, table name) from 'WHERE' condition if it's possible and fill lookup_field_vals struct fields with these values. @param[in] thd thread handler @param[in] cond WHERE condition @param[in] table I_S table @param[in, out] lookup_field_vals Struct which holds lookup values @return 0 success 1 error, there can be no matching records for the condition */ bool calc_lookup_values_from_cond(THD *thd, COND *cond, TABLE_LIST *table, LOOKUP_FIELD_VALUES *lookup_field_vals) { if (!cond) return 0; if (cond->type() == Item::COND_ITEM) { if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) { List_iterator<Item> li(*((Item_cond*) cond)->argument_list()); Item *item; while ((item= li++)) { if (item->type() == Item::FUNC_ITEM) { if (get_lookup_value(thd, (Item_func*)item, table, lookup_field_vals)) return 1; } else { if (calc_lookup_values_from_cond(thd, item, table, lookup_field_vals)) return 1; } } } return 0; } else if (cond->type() == Item::FUNC_ITEM && get_lookup_value(thd, (Item_func*) cond, table, lookup_field_vals)) return 1; return 0; } bool uses_only_table_name_fields(Item *item, TABLE_LIST *table) { if (item->type() == Item::FUNC_ITEM) { Item_func *item_func= (Item_func*)item; for (uint i=0; i<item_func->argument_count(); i++) { if (!uses_only_table_name_fields(item_func->arguments()[i], table)) return 0; } } else if (item->type() == Item::FIELD_ITEM) { Item_field *item_field= (Item_field*)item; CHARSET_INFO *cs= system_charset_info; ST_SCHEMA_TABLE *schema_table= table->schema_table; ST_FIELD_INFO *field_info= schema_table->fields_info; const char *field_name1= schema_table->idx_field1 >= 0 ? field_info[schema_table->idx_field1].field_name : ""; const char *field_name2= schema_table->idx_field2 >= 0 ? field_info[schema_table->idx_field2].field_name : ""; if (table->table != item_field->field->table || (cs->coll->strnncollsp(cs, (uchar *) field_name1, strlen(field_name1), (uchar *) item_field->field_name, strlen(item_field->field_name), 0) && cs->coll->strnncollsp(cs, (uchar *) field_name2, strlen(field_name2), (uchar *) item_field->field_name, strlen(item_field->field_name), 0))) return 0; } else if (item->type() == Item::REF_ITEM) return uses_only_table_name_fields(item->real_item(), table); if (item->type() == Item::SUBSELECT_ITEM && !item->const_item()) return 0; return 1; } static COND * make_cond_for_info_schema(COND *cond, TABLE_LIST *table) { if (!cond) return (COND*) 0; if (cond->type() == Item::COND_ITEM) { if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) { /* Create new top level AND item */ Item_cond_and *new_cond=new Item_cond_and; if (!new_cond) return (COND*) 0; List_iterator<Item> li(*((Item_cond*) cond)->argument_list()); Item *item; while ((item=li++)) { Item *fix= make_cond_for_info_schema(item, table); if (fix) new_cond->argument_list()->push_back(fix); } switch (new_cond->argument_list()->elements) { case 0: return (COND*) 0; case 1: return new_cond->argument_list()->head(); default: new_cond->quick_fix_field(); return new_cond; } } else { // Or list Item_cond_or *new_cond=new Item_cond_or; if (!new_cond) return (COND*) 0; List_iterator<Item> li(*((Item_cond*) cond)->argument_list()); Item *item; while ((item=li++)) { Item *fix=make_cond_for_info_schema(item, table); if (!fix) return (COND*) 0; new_cond->argument_list()->push_back(fix); } new_cond->quick_fix_field(); new_cond->top_level_item(); return new_cond; } } if (!uses_only_table_name_fields(cond, table)) return (COND*) 0; return cond; } /** @brief Calculate lookup values(database name, table name) @details This function calculates lookup values(database name, table name) from 'WHERE' condition or wild values (for 'SHOW' commands only) from LEX struct and fill lookup_field_vals struct field with these values. @param[in] thd thread handler @param[in] cond WHERE condition @param[in] tables I_S table @param[in, out] lookup_field_values Struct which holds lookup values @return 0 success 1 error, there can be no matching records for the condition */ bool get_lookup_field_values(THD *thd, COND *cond, TABLE_LIST *tables, LOOKUP_FIELD_VALUES *lookup_field_values) { LEX *lex= thd->lex; const char *wild= lex->wild ? lex->wild->ptr() : NullS; bool rc= 0; bzero((char*) lookup_field_values, sizeof(LOOKUP_FIELD_VALUES)); switch (lex->sql_command) { case SQLCOM_SHOW_DATABASES: if (wild) { thd->make_lex_string(&lookup_field_values->db_value, wild, strlen(wild), 0); lookup_field_values->wild_db_value= 1; } break; case SQLCOM_SHOW_TABLES: case SQLCOM_SHOW_TABLE_STATUS: case SQLCOM_SHOW_TRIGGERS: case SQLCOM_SHOW_EVENTS: thd->make_lex_string(&lookup_field_values->db_value, lex->select_lex.db, strlen(lex->select_lex.db), 0); if (wild) { thd->make_lex_string(&lookup_field_values->table_value, wild, strlen(wild), 0); lookup_field_values->wild_table_value= 1; } break; default: /* The "default" is for queries over I_S. All previous cases handle SHOW commands. */ rc= calc_lookup_values_from_cond(thd, cond, tables, lookup_field_values); break; } if (lower_case_table_names && !rc) { /* We can safely do in-place upgrades here since all of the above cases are allocating a new memory buffer for these strings. */ if (lookup_field_values->db_value.str && lookup_field_values->db_value.str[0]) my_casedn_str(system_charset_info, lookup_field_values->db_value.str); if (lookup_field_values->table_value.str && lookup_field_values->table_value.str[0]) my_casedn_str(system_charset_info, lookup_field_values->table_value.str); } return rc; } enum enum_schema_tables get_schema_table_idx(ST_SCHEMA_TABLE *schema_table) { return (enum enum_schema_tables) (schema_table - &schema_tables[0]); } /* Create db names list. Information schema name always is first in list SYNOPSIS make_db_list() thd thread handler files list of db names wild wild string idx_field_vals idx_field_vals->db_name contains db name or wild string with_i_schema returns 1 if we added 'IS' name to list otherwise returns 0 RETURN zero success non-zero error */ int make_db_list(THD *thd, List<LEX_STRING> *files, LOOKUP_FIELD_VALUES *lookup_field_vals, bool *with_i_schema) { LEX_STRING *i_s_name_copy= 0; i_s_name_copy= thd->make_lex_string(i_s_name_copy, INFORMATION_SCHEMA_NAME.str, INFORMATION_SCHEMA_NAME.length, TRUE); *with_i_schema= 0; if (lookup_field_vals->wild_db_value) { /* This part of code is only for SHOW DATABASES command. idx_field_vals->db_value can be 0 when we don't use LIKE clause (see also get_index_field_values() function) */ if (!lookup_field_vals->db_value.str || !wild_case_compare(system_charset_info, INFORMATION_SCHEMA_NAME.str, lookup_field_vals->db_value.str)) { *with_i_schema= 1; if (files->push_back(i_s_name_copy)) return 1; } return (find_files(thd, files, NullS, mysql_data_home, lookup_field_vals->db_value.str, 1) != FIND_FILES_OK); } /* If we have db lookup vaule we just add it to list and exit from the function. We don't do this for database names longer than the maximum path length. */ if (lookup_field_vals->db_value.str && lookup_field_vals->db_value.length < FN_REFLEN) { if (is_infoschema_db(lookup_field_vals->db_value.str, lookup_field_vals->db_value.length)) { *with_i_schema= 1; if (files->push_back(i_s_name_copy)) return 1; return 0; } if (files->push_back(&lookup_field_vals->db_value)) return 1; return 0; } /* Create list of existing databases. It is used in case of select from information schema table */ if (files->push_back(i_s_name_copy)) return 1; *with_i_schema= 1; return (find_files(thd, files, NullS, mysql_data_home, NullS, 1) != FIND_FILES_OK); } struct st_add_schema_table { List<LEX_STRING> *files; const char *wild; }; static my_bool add_schema_table(THD *thd, plugin_ref plugin, void* p_data) { LEX_STRING *file_name= 0; st_add_schema_table *data= (st_add_schema_table *)p_data; List<LEX_STRING> *file_list= data->files; const char *wild= data->wild; ST_SCHEMA_TABLE *schema_table= plugin_data(plugin, ST_SCHEMA_TABLE *); DBUG_ENTER("add_schema_table"); if (schema_table->hidden) DBUG_RETURN(0); if (wild) { if (lower_case_table_names) { if (wild_case_compare(files_charset_info, schema_table->table_name, wild)) DBUG_RETURN(0); } else if (wild_compare(schema_table->table_name, wild, 0)) DBUG_RETURN(0); } if ((file_name= thd->make_lex_string(file_name, schema_table->table_name, strlen(schema_table->table_name), TRUE)) && !file_list->push_back(file_name)) DBUG_RETURN(0); DBUG_RETURN(1); } int schema_tables_add(THD *thd, List<LEX_STRING> *files, const char *wild) { LEX_STRING *file_name= 0; ST_SCHEMA_TABLE *tmp_schema_table= schema_tables; st_add_schema_table add_data; DBUG_ENTER("schema_tables_add"); for (; tmp_schema_table->table_name; tmp_schema_table++) { if (tmp_schema_table->hidden) continue; if (wild) { if (lower_case_table_names) { if (wild_case_compare(files_charset_info, tmp_schema_table->table_name, wild)) continue; } else if (wild_compare(tmp_schema_table->table_name, wild, 0)) continue; } if ((file_name= thd->make_lex_string(file_name, tmp_schema_table->table_name, strlen(tmp_schema_table->table_name), TRUE)) && !files->push_back(file_name)) continue; DBUG_RETURN(1); } add_data.files= files; add_data.wild= wild; if (plugin_foreach(thd, add_schema_table, MYSQL_INFORMATION_SCHEMA_PLUGIN, &add_data)) DBUG_RETURN(1); DBUG_RETURN(0); } /** @brief Create table names list @details The function creates the list of table names in database @param[in] thd thread handler @param[in] table_names List of table names in database @param[in] lex pointer to LEX struct @param[in] lookup_field_vals pointer to LOOKUP_FIELD_VALUE struct @param[in] with_i_schema TRUE means that we add I_S tables to list @param[in] db_name database name @return Operation status @retval 0 ok @retval 1 fatal error @retval 2 Not fatal error; Safe to ignore this file list */ static int make_table_name_list(THD *thd, List<LEX_STRING> *table_names, LEX *lex, LOOKUP_FIELD_VALUES *lookup_field_vals, bool with_i_schema, LEX_STRING *db_name) { char path[FN_REFLEN + 1]; build_table_filename(path, sizeof(path) - 1, db_name->str, "", "", 0); if (!lookup_field_vals->wild_table_value && lookup_field_vals->table_value.str) { if (with_i_schema) { LEX_STRING *name; ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, lookup_field_vals->table_value.str); if (schema_table && !schema_table->hidden) { if (!(name= thd->make_lex_string(NULL, schema_table->table_name, strlen(schema_table->table_name), TRUE)) || table_names->push_back(name)) return 1; } } else { if (table_names->push_back(&lookup_field_vals->table_value)) return 1; /* Check that table is relevant in current transaction. (used for ndb engine, see ndbcluster_find_files(), ha_ndbcluster.cc) */ (void) ha_find_files(thd, db_name->str, path, lookup_field_vals->table_value.str, 0, table_names); } return 0; } /* This call will add all matching the wildcards (if specified) IS tables to the list */ if (with_i_schema) return (schema_tables_add(thd, table_names, lookup_field_vals->table_value.str)); find_files_result res= find_files(thd, table_names, db_name->str, path, lookup_field_vals->table_value.str, 0); if (res != FIND_FILES_OK) { /* Downgrade errors about problems with database directory to warnings if this is not a 'SHOW' command. Another thread may have dropped database, and we may still have a name for that directory. */ if (res == FIND_FILES_DIR) { if (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) return 1; thd->clear_error(); return 2; } return 1; } return 0; } /** Fill I_S table with data obtained by performing full-blown table open. @param thd Thread handler. @param is_show_fields_or_keys Indicates whether it is a legacy SHOW COLUMNS or SHOW KEYS statement. @param table TABLE object for I_S table to be filled. @param schema_table I_S table description structure. @param orig_db_name Database name. @param orig_table_name Table name. @param open_tables_state_backup Open_tables_state object which is used to save/restore original status of variables related to open tables state. @param can_deadlock Indicates that deadlocks are possible due to metadata locks, so to avoid them we should not wait in case if conflicting lock is present. @retval FALSE - Success. @retval TRUE - Failure. */ static bool fill_schema_table_by_open(THD *thd, bool is_show_fields_or_keys, TABLE *table, ST_SCHEMA_TABLE *schema_table, LEX_STRING *orig_db_name, LEX_STRING *orig_table_name, Open_tables_backup *open_tables_state_backup, bool can_deadlock) { Query_arena i_s_arena(thd->mem_root, Query_arena::STMT_CONVENTIONAL_EXECUTION), backup_arena, *old_arena; LEX *old_lex= thd->lex, temp_lex, *lex; LEX_STRING db_name, table_name; TABLE_LIST *table_list; bool result= true; DBUG_ENTER("fill_schema_table_by_open"); /* When a view is opened its structures are allocated on a permanent statement arena and linked into the LEX tree for the current statement (this happens even in cases when view is handled through TEMPTABLE algorithm). To prevent this process from unnecessary hogging of memory in the permanent arena of our I_S query and to avoid damaging its LEX we use temporary arena and LEX for table/view opening. Use temporary arena instead of statement permanent arena. Also make it active arena and save original one for successive restoring. */ old_arena= thd->stmt_arena; thd->stmt_arena= &i_s_arena; thd->set_n_backup_active_arena(&i_s_arena, &backup_arena); /* Prepare temporary LEX. */ thd->lex= lex= &temp_lex; lex_start(thd); /* Disable constant subquery evaluation as we won't be locking tables. */ lex->context_analysis_only= CONTEXT_ANALYSIS_ONLY_VIEW; /* Some of process_table() functions rely on wildcard being passed from old LEX (or at least being initialized). */ lex->wild= old_lex->wild; /* Since make_table_list() might change database and table name passed to it we create copies of orig_db_name and orig_table_name here. These copies are used for make_table_list() while unaltered values are passed to process_table() functions. */ if (!thd->make_lex_string(&db_name, orig_db_name->str, orig_db_name->length, FALSE) || !thd->make_lex_string(&table_name, orig_table_name->str, orig_table_name->length, FALSE)) goto end; /* Create table list element for table to be open. Link it with the temporary LEX. The latter is required to correctly open views and produce table describing their structure. */ if (make_table_list(thd, &lex->select_lex, &db_name, &table_name)) goto end; table_list= lex->select_lex.table_list.first; if (is_show_fields_or_keys) { /* Restore thd->temporary_tables to be able to process temporary tables (only for 'show index' & 'show columns'). This should be changed when processing of temporary tables for I_S tables will be done. */ thd->temporary_tables= open_tables_state_backup->temporary_tables; } else { /* Apply optimization flags for table opening which are relevant for this I_S table. We can't do this for SHOW COLUMNS/KEYS because of backward compatibility. */ table_list->i_s_requested_object= schema_table->i_s_requested_object; } /* Let us set fake sql_command so views won't try to merge themselves into main statement. If we don't do this, SELECT * from information_schema.xxxx will cause problems. SQLCOM_SHOW_FIELDS is used because it satisfies 'only_view_structure()'. */ lex->sql_command= SQLCOM_SHOW_FIELDS; result= open_normal_and_derived_tables(thd, table_list, (MYSQL_OPEN_IGNORE_FLUSH | MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL | (can_deadlock ? MYSQL_OPEN_FAIL_ON_MDL_CONFLICT : 0))); /* Restore old value of sql_command back as it is being looked at in process_table() function. */ lex->sql_command= old_lex->sql_command; DEBUG_SYNC(thd, "after_open_table_ignore_flush"); /* XXX: show_table_list has a flag i_is_requested, and when it's set, open_normal_and_derived_tables() can return an error without setting an error message in THD, which is a hack. This is why we have to check for res, then for thd->is_error() and only then for thd->main_da.sql_errno(). Again we don't do this for SHOW COLUMNS/KEYS because of backward compatibility. */ if (!is_show_fields_or_keys && result && thd->is_error() && thd->stmt_da->sql_errno() == ER_NO_SUCH_TABLE) { /* Hide error for a non-existing table. For example, this error can occur when we use a where condition with a db name and table, but the table does not exist. */ result= false; thd->clear_error(); } else { result= schema_table->process_table(thd, table_list, table, result, orig_db_name, orig_table_name); } end: lex->unit.cleanup(); /* Restore original LEX value, statement's arena and THD arena values. */ lex_end(thd->lex); // Free items, before restoring backup_arena below. DBUG_ASSERT(i_s_arena.free_list == NULL); thd->free_items(); /* For safety reset list of open temporary tables before closing all tables open within this Open_tables_state. */ thd->temporary_tables= NULL; close_thread_tables(thd); /* Release metadata lock we might have acquired. See comment in fill_schema_table_from_frm() for details. */ thd->mdl_context.rollback_to_savepoint(open_tables_state_backup->mdl_system_tables_svp); thd->lex= old_lex; thd->stmt_arena= old_arena; thd->restore_active_arena(&i_s_arena, &backup_arena); DBUG_RETURN(result); } /** @brief Fill I_S table for SHOW TABLE NAMES commands @param[in] thd thread handler @param[in] table TABLE struct for I_S table @param[in] db_name database name @param[in] table_name table name @param[in] with_i_schema I_S table if TRUE @return Operation status @retval 0 success @retval 1 error */ static int fill_schema_table_names(THD *thd, TABLE *table, LEX_STRING *db_name, LEX_STRING *table_name, bool with_i_schema, bool need_table_type) { /* Avoid opening FRM files if table type is not needed. */ if (need_table_type) { if (with_i_schema) { table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), system_charset_info); } else { enum legacy_db_type not_used; char path[FN_REFLEN + 1]; (void) build_table_filename(path, sizeof(path) - 1, db_name->str, table_name->str, reg_ext, 0); switch (dd_frm_type(thd, path, &not_used)) { case FRMTYPE_ERROR: table->field[3]->store(STRING_WITH_LEN("ERROR"), system_charset_info); break; case FRMTYPE_TABLE: table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), system_charset_info); break; case FRMTYPE_VIEW: table->field[3]->store(STRING_WITH_LEN("VIEW"), system_charset_info); break; default: DBUG_ASSERT(0); } if (thd->is_error() && thd->stmt_da->sql_errno() == ER_NO_SUCH_TABLE) { thd->clear_error(); return 0; } } } if (schema_table_store_record(thd, table)) return 1; return 0; } /** @brief Get open table method @details The function calculates the method which will be used for table opening: SKIP_OPEN_TABLE - do not open table OPEN_FRM_ONLY - open FRM file only OPEN_FULL_TABLE - open FRM, data, index files @param[in] tables I_S table table_list @param[in] schema_table I_S table struct @param[in] schema_table_idx I_S table index @return return a set of flags @retval SKIP_OPEN_TABLE | OPEN_FRM_ONLY | OPEN_FULL_TABLE */ uint get_table_open_method(TABLE_LIST *tables, ST_SCHEMA_TABLE *schema_table, enum enum_schema_tables schema_table_idx) { /* determine which method will be used for table opening */ if (schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE) { Field **ptr, *field; int table_open_method= 0, field_indx= 0; uint star_table_open_method= OPEN_FULL_TABLE; bool used_star= true; // true if '*' is used in select for (ptr=tables->table->field; (field= *ptr) ; ptr++) { star_table_open_method= min(star_table_open_method, schema_table->fields_info[field_indx].open_method); if (bitmap_is_set(tables->table->read_set, field->field_index)) { used_star= false; table_open_method|= schema_table->fields_info[field_indx].open_method; } field_indx++; } if (used_star) return star_table_open_method; return table_open_method; } /* I_S tables which use get_all_tables but can not be optimized */ return (uint) OPEN_FULL_TABLE; } /** Try acquire high priority share metadata lock on a table (with optional wait for conflicting locks to go away). @param thd Thread context. @param mdl_request Pointer to memory to be used for MDL_request object for a lock request. @param table Table list element for the table @param can_deadlock Indicates that deadlocks are possible due to metadata locks, so to avoid them we should not wait in case if conflicting lock is present. @note This is an auxiliary function to be used in cases when we want to access table's description by looking up info in TABLE_SHARE without going through full-blown table open. @note This function assumes that there are no other metadata lock requests in the current metadata locking context. @retval FALSE No error, if lock was obtained TABLE_LIST::mdl_request::ticket is set to non-NULL value. @retval TRUE Some error occured (probably thread was killed). */ static bool try_acquire_high_prio_shared_mdl_lock(THD *thd, TABLE_LIST *table, bool can_deadlock) { bool error; table->mdl_request.init(MDL_key::TABLE, table->db, table->table_name, MDL_SHARED_HIGH_PRIO, MDL_TRANSACTION); if (can_deadlock) { /* When .FRM is being open in order to get data for an I_S table, we might have some tables not only open but also locked. E.g. this happens when a SHOW or I_S statement is run under LOCK TABLES or inside a stored function. By waiting for the conflicting metadata lock to go away we might create a deadlock which won't entirely belong to the MDL subsystem and thus won't be detectable by this subsystem's deadlock detector. To avoid such situation, when there are other locked tables, we prefer not to wait on a conflicting lock. */ error= thd->mdl_context.try_acquire_lock(&table->mdl_request); } else error= thd->mdl_context.acquire_lock(&table->mdl_request, thd->variables.lock_wait_timeout); return error; } /** @brief Fill I_S table with data from FRM file only @param[in] thd thread handler @param[in] table TABLE struct for I_S table @param[in] schema_table I_S table struct @param[in] db_name database name @param[in] table_name table name @param[in] schema_table_idx I_S table index @param[in] open_tables_state_backup Open_tables_state object which is used to save/restore original state of metadata locks. @param[in] can_deadlock Indicates that deadlocks are possible due to metadata locks, so to avoid them we should not wait in case if conflicting lock is present. @return Operation status @retval 0 Table is processed and we can continue with new table @retval 1 It's view and we have to use open_tables function for this table */ static int fill_schema_table_from_frm(THD *thd, TABLE_LIST *tables, ST_SCHEMA_TABLE *schema_table, LEX_STRING *db_name, LEX_STRING *table_name, enum enum_schema_tables schema_table_idx, Open_tables_backup *open_tables_state_backup, bool can_deadlock) { TABLE *table= tables->table; TABLE_SHARE *share; TABLE tbl; TABLE_LIST table_list; uint res= 0; int not_used; my_hash_value_type hash_value; char key[MAX_DBKEY_LENGTH]; uint key_length; char db_name_buff[NAME_LEN + 1], table_name_buff[NAME_LEN + 1]; bzero((char*) &table_list, sizeof(TABLE_LIST)); bzero((char*) &tbl, sizeof(TABLE)); if (lower_case_table_names) { /* In lower_case_table_names > 0 metadata locking and table definition cache subsystems require normalized (lowercased) database and table names as input. */ strmov(db_name_buff, db_name->str); strmov(table_name_buff, table_name->str); my_casedn_str(files_charset_info, db_name_buff); my_casedn_str(files_charset_info, table_name_buff); table_list.db= db_name_buff; table_list.table_name= table_name_buff; } else { table_list.table_name= table_name->str; table_list.db= db_name->str; } /* TODO: investigate if in this particular situation we can get by simply obtaining internal lock of the data-dictionary instead of obtaining full-blown metadata lock. */ if (try_acquire_high_prio_shared_mdl_lock(thd, &table_list, can_deadlock)) { /* Some error occured (most probably we have been killed while waiting for conflicting locks to go away), let the caller to handle the situation. */ return 1; } if (! table_list.mdl_request.ticket) { /* We are in situation when we have encountered conflicting metadata lock and deadlocks can occur due to waiting for it to go away. So instead of waiting skip this table with an appropriate warning. */ DBUG_ASSERT(can_deadlock); push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_I_S_SKIPPED_TABLE, ER(ER_WARN_I_S_SKIPPED_TABLE), table_list.db, table_list.table_name); return 0; } if (schema_table->i_s_requested_object & OPEN_TRIGGER_ONLY) { init_sql_alloc(&tbl.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); if (!Table_triggers_list::check_n_load(thd, db_name->str, table_name->str, &tbl, 1)) { table_list.table= &tbl; res= schema_table->process_table(thd, &table_list, table, res, db_name, table_name); delete tbl.triggers; } free_root(&tbl.mem_root, MYF(0)); goto end; } key_length= create_table_def_key(thd, key, &table_list, 0); hash_value= my_calc_hash(&table_def_cache, (uchar*) key, key_length); mysql_mutex_lock(&LOCK_open); share= get_table_share(thd, &table_list, key, key_length, OPEN_VIEW, &not_used, hash_value); if (!share) { res= 0; goto end_unlock; } if (share->is_view) { if (schema_table->i_s_requested_object & OPEN_TABLE_ONLY) { /* skip view processing */ res= 0; goto end_share; } else if (schema_table->i_s_requested_object & OPEN_VIEW_FULL) { /* tell get_all_tables() to fall back to open_normal_and_derived_tables() */ res= 1; goto end_share; } } if (share->is_view) { if (open_new_frm(thd, share, table_name->str, (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE | HA_GET_INDEX | HA_TRY_READ_ONLY), READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD | OPEN_VIEW_NO_PARSE, thd->open_options, &tbl, &table_list, thd->mem_root)) goto end_share; table_list.view= (LEX*) share->is_view; res= schema_table->process_table(thd, &table_list, table, res, db_name, table_name); goto end_share; } if (!open_table_from_share(thd, share, table_name->str, 0, (EXTRA_RECORD | OPEN_FRM_FILE_ONLY), thd->open_options, &tbl, FALSE)) { tbl.s= share; table_list.table= &tbl; table_list.view= (LEX*) share->is_view; res= schema_table->process_table(thd, &table_list, table, res, db_name, table_name); free_root(&tbl.mem_root, MYF(0)); my_free((void *) tbl.alias); } end_share: release_table_share(share); end_unlock: mysql_mutex_unlock(&LOCK_open); end: /* Release metadata lock we might have acquired. Without this step metadata locks acquired for each table processed will be accumulated. In situation when a lot of tables are processed by I_S query this will result in transaction with too many metadata locks. As result performance of acquisition of new lock will suffer. Of course, the fact that we don't hold metadata lock on tables which were processed till the end of I_S query makes execution less isolated from concurrent DDL. Consequently one might get 'dirty' results from such a query. But we have never promised serializability of I_S queries anyway. We don't have any tables open since we took backup, so rolling back to savepoint is safe. */ DBUG_ASSERT(thd->open_tables == NULL); thd->mdl_context.rollback_to_savepoint(open_tables_state_backup->mdl_system_tables_svp); thd->clear_error(); return res; } /** Trigger_error_handler is intended to intercept and silence SQL conditions that might happen during trigger loading for SHOW statements. The potential SQL conditions are: - ER_PARSE_ERROR -- this error is thrown if a trigger definition file is damaged or contains invalid CREATE TRIGGER statement. That should not happen in normal life. - ER_TRG_NO_DEFINER -- this warning is thrown when we're loading a trigger created/imported in/from the version of MySQL, which does not support trigger definers. - ER_TRG_NO_CREATION_CTX -- this warning is thrown when we're loading a trigger created/imported in/from the version of MySQL, which does not support trigger creation contexts. */ class Trigger_error_handler : public Internal_error_handler { public: bool handle_condition(THD *thd, uint sql_errno, const char* sqlstate, MYSQL_ERROR::enum_warning_level level, const char* msg, MYSQL_ERROR ** cond_hdl) { if (sql_errno == ER_PARSE_ERROR || sql_errno == ER_TRG_NO_DEFINER || sql_errno == ER_TRG_NO_CREATION_CTX) return true; return false; } }; /** @brief Fill I_S tables whose data are retrieved from frm files and storage engine @details The information schema tables are internally represented as temporary tables that are filled at query execution time. Those I_S tables whose data are retrieved from frm files and storage engine are filled by the function get_all_tables(). @param[in] thd thread handler @param[in] tables I_S table @param[in] cond 'WHERE' condition @return Operation status @retval 0 success @retval 1 error */ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond) { LEX *lex= thd->lex; TABLE *table= tables->table; SELECT_LEX *lsel= tables->schema_select_lex; ST_SCHEMA_TABLE *schema_table= tables->schema_table; LOOKUP_FIELD_VALUES lookup_field_vals; LEX_STRING *db_name, *table_name; bool with_i_schema; enum enum_schema_tables schema_table_idx; List<LEX_STRING> db_names; List_iterator_fast<LEX_STRING> it(db_names); COND *partial_cond= 0; int error= 1; Open_tables_backup open_tables_state_backup; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *sctx= thd->security_ctx; #endif uint table_open_method; bool can_deadlock; DBUG_ENTER("get_all_tables"); /* In cases when SELECT from I_S table being filled by this call is part of statement which also uses other tables or is being executed under LOCK TABLES or is part of transaction which also uses other tables waiting for metadata locks which happens below might result in deadlocks. To avoid them we don't wait if conflicting metadata lock is encountered and skip table with emitting an appropriate warning. */ can_deadlock= thd->mdl_context.has_locks(); /* We should not introduce deadlocks even if we already have some tables open and locked, since we won't lock tables which we will open and will ignore pending exclusive metadata locks for these tables by using high-priority requests for shared metadata locks. */ thd->reset_n_backup_open_tables_state(&open_tables_state_backup); schema_table_idx= get_schema_table_idx(schema_table); tables->table_open_method= table_open_method= get_table_open_method(tables, schema_table, schema_table_idx); DBUG_PRINT("open_method", ("%d", tables->table_open_method)); /* this branch processes SHOW FIELDS, SHOW INDEXES commands. see sql_parse.cc, prepare_schema_table() function where this values are initialized */ if (lsel && lsel->table_list.first) { LEX_STRING db_name, table_name; db_name.str= lsel->table_list.first->db; db_name.length= lsel->table_list.first->db_length; table_name.str= lsel->table_list.first->table_name; table_name.length= lsel->table_list.first->table_name_length; error= fill_schema_table_by_open(thd, TRUE, table, schema_table, &db_name, &table_name, &open_tables_state_backup, can_deadlock); goto err; } if (get_lookup_field_values(thd, cond, tables, &lookup_field_vals)) { error= 0; goto err; } DBUG_PRINT("INDEX VALUES",("db_name='%s', table_name='%s'", STR_OR_NIL(lookup_field_vals.db_value.str), STR_OR_NIL(lookup_field_vals.table_value.str))); if (!lookup_field_vals.wild_db_value && !lookup_field_vals.wild_table_value) { /* if lookup value is empty string then it's impossible table name or db name */ if ((lookup_field_vals.db_value.str && !lookup_field_vals.db_value.str[0]) || (lookup_field_vals.table_value.str && !lookup_field_vals.table_value.str[0])) { error= 0; goto err; } } if (lookup_field_vals.db_value.length && !lookup_field_vals.wild_db_value) tables->has_db_lookup_value= TRUE; if (lookup_field_vals.table_value.length && !lookup_field_vals.wild_table_value) tables->has_table_lookup_value= TRUE; if (tables->has_db_lookup_value && tables->has_table_lookup_value) partial_cond= 0; else partial_cond= make_cond_for_info_schema(cond, tables); if (lex->describe) { /* EXPLAIN SELECT */ error= 0; goto err; } if (make_db_list(thd, &db_names, &lookup_field_vals, &with_i_schema)) goto err; it.rewind(); /* To get access to new elements in basis list */ while ((db_name= it++)) { #ifndef NO_EMBEDDED_ACCESS_CHECKS if (!(check_access(thd, SELECT_ACL, db_name->str, &thd->col_access, NULL, 0, 1) || (!thd->col_access && check_grant_db(thd, db_name->str))) || sctx->master_access & (DB_ACLS | SHOW_DB_ACL) || acl_get(sctx->get_host()->ptr(), sctx->get_ip()->ptr(), sctx->priv_user, db_name->str, 0)) #endif { List<LEX_STRING> table_names; int res= make_table_name_list(thd, &table_names, lex, &lookup_field_vals, with_i_schema, db_name); if (res == 2) /* Not fatal error, continue */ continue; if (res) goto err; List_iterator_fast<LEX_STRING> it_files(table_names); while ((table_name= it_files++)) { restore_record(table, s->default_values); table->field[schema_table->idx_field1]-> store(db_name->str, db_name->length, system_charset_info); table->field[schema_table->idx_field2]-> store(table_name->str, table_name->length, system_charset_info); if (!partial_cond || partial_cond->val_int()) { /* If table is I_S.tables and open_table_method is 0 (eg SKIP_OPEN) we can skip table opening and we don't have lookup value for table name or lookup value is wild string(table name list is already created by make_table_name_list() function). */ if (!table_open_method && schema_table_idx == SCH_TABLES && (!lookup_field_vals.table_value.length || lookup_field_vals.wild_table_value)) { table->field[0]->store(STRING_WITH_LEN("def"), system_charset_info); if (schema_table_store_record(thd, table)) goto err; /* Out of space in temporary table */ continue; } /* SHOW TABLE NAMES command */ if (schema_table_idx == SCH_TABLE_NAMES) { if (fill_schema_table_names(thd, tables->table, db_name, table_name, with_i_schema, lex->verbose)) continue; } else { if (!(table_open_method & ~OPEN_FRM_ONLY) && !with_i_schema) { /* Here we need to filter out warnings, which can happen during loading of triggers in fill_schema_table_from_frm(), because we don't need those warnings to pollute output of SELECT from I_S / SHOW-statements. */ Trigger_error_handler err_handler; thd->push_internal_handler(&err_handler); int res= fill_schema_table_from_frm(thd, tables, schema_table, db_name, table_name, schema_table_idx, &open_tables_state_backup, can_deadlock); thd->pop_internal_handler(); if (!res) continue; } DEBUG_SYNC(thd, "before_open_in_get_all_tables"); if (fill_schema_table_by_open(thd, FALSE, table, schema_table, db_name, table_name, &open_tables_state_backup, can_deadlock)) goto err; } } } /* If we have information schema its always the first table and only the first table. Reset for other tables. */ with_i_schema= 0; } } error= 0; err: thd->restore_backup_open_tables_state(&open_tables_state_backup); DBUG_RETURN(error); } bool store_schema_shemata(THD* thd, TABLE *table, LEX_STRING *db_name, CHARSET_INFO *cs) { restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), system_charset_info); table->field[1]->store(db_name->str, db_name->length, system_charset_info); table->field[2]->store(cs->csname, strlen(cs->csname), system_charset_info); table->field[3]->store(cs->name, strlen(cs->name), system_charset_info); return schema_table_store_record(thd, table); } int fill_schema_schemata(THD *thd, TABLE_LIST *tables, COND *cond) { /* TODO: fill_schema_shemata() is called when new client is connected. Returning error status in this case leads to client hangup. */ LOOKUP_FIELD_VALUES lookup_field_vals; List<LEX_STRING> db_names; LEX_STRING *db_name; bool with_i_schema; HA_CREATE_INFO create; TABLE *table= tables->table; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *sctx= thd->security_ctx; #endif DBUG_ENTER("fill_schema_shemata"); if (get_lookup_field_values(thd, cond, tables, &lookup_field_vals)) DBUG_RETURN(0); DBUG_PRINT("INDEX VALUES",("db_name='%s', table_name='%s'", lookup_field_vals.db_value.str, lookup_field_vals.table_value.str)); if (make_db_list(thd, &db_names, &lookup_field_vals, &with_i_schema)) DBUG_RETURN(1); /* If we have lookup db value we should check that the database exists */ if(lookup_field_vals.db_value.str && !lookup_field_vals.wild_db_value && !with_i_schema) { char path[FN_REFLEN+16]; uint path_len; MY_STAT stat_info; if (!lookup_field_vals.db_value.str[0]) DBUG_RETURN(0); path_len= build_table_filename(path, sizeof(path) - 1, lookup_field_vals.db_value.str, "", "", 0); path[path_len-1]= 0; if (!mysql_file_stat(key_file_misc, path, &stat_info, MYF(0))) DBUG_RETURN(0); } List_iterator_fast<LEX_STRING> it(db_names); while ((db_name=it++)) { if (with_i_schema) // information schema name is always first in list { if (store_schema_shemata(thd, table, db_name, system_charset_info)) DBUG_RETURN(1); with_i_schema= 0; continue; } #ifndef NO_EMBEDDED_ACCESS_CHECKS if (sctx->master_access & (DB_ACLS | SHOW_DB_ACL) || acl_get(sctx->get_host()->ptr(), sctx->get_ip()->ptr(), sctx->priv_user, db_name->str, 0) || !check_grant_db(thd, db_name->str)) #endif { load_db_opt_by_name(thd, db_name->str, &create); if (store_schema_shemata(thd, table, db_name, create.default_table_charset)) DBUG_RETURN(1); } } DBUG_RETURN(0); } static int get_schema_tables_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { const char *tmp_buff; MYSQL_TIME time; int info_error= 0; CHARSET_INFO *cs= system_charset_info; DBUG_ENTER("get_schema_tables_record"); restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); if (res) { /* There was a table open error, so set the table type and return */ if (tables->view) table->field[3]->store(STRING_WITH_LEN("VIEW"), cs); else if (tables->schema_table) table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), cs); else table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), cs); goto err; } if (tables->view) { table->field[3]->store(STRING_WITH_LEN("VIEW"), cs); table->field[20]->store(STRING_WITH_LEN("VIEW"), cs); } else { char option_buff[350],*ptr; TABLE *show_table= tables->table; TABLE_SHARE *share= show_table->s; handler *file= show_table->file; handlerton *tmp_db_type= share->db_type(); #ifdef WITH_PARTITION_STORAGE_ENGINE bool is_partitioned= FALSE; #endif if (share->tmp_table == SYSTEM_TMP_TABLE) table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), cs); else if (share->tmp_table) table->field[3]->store(STRING_WITH_LEN("LOCAL TEMPORARY"), cs); else table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), cs); for (int i= 4; i < 20; i++) { if (i == 7 || (i > 12 && i < 17) || i == 18) continue; table->field[i]->set_notnull(); } /* Collect table info from the table share */ #ifdef WITH_PARTITION_STORAGE_ENGINE if (share->db_type() == partition_hton && share->partition_info_str_len) { tmp_db_type= share->default_part_db_type; is_partitioned= TRUE; } #endif tmp_buff= (char *) ha_resolve_storage_engine_name(tmp_db_type); table->field[4]->store(tmp_buff, strlen(tmp_buff), cs); table->field[5]->store((longlong) share->frm_version, TRUE); ptr=option_buff; if (share->min_rows) { ptr=strmov(ptr," min_rows="); ptr=longlong10_to_str(share->min_rows,ptr,10); } if (share->max_rows) { ptr=strmov(ptr," max_rows="); ptr=longlong10_to_str(share->max_rows,ptr,10); } if (share->avg_row_length) { ptr=strmov(ptr," avg_row_length="); ptr=longlong10_to_str(share->avg_row_length,ptr,10); } if (share->db_create_options & HA_OPTION_PACK_KEYS) ptr=strmov(ptr," pack_keys=1"); if (share->db_create_options & HA_OPTION_NO_PACK_KEYS) ptr=strmov(ptr," pack_keys=0"); /* We use CHECKSUM, instead of TABLE_CHECKSUM, for backward compability */ if (share->db_create_options & HA_OPTION_CHECKSUM) ptr=strmov(ptr," checksum=1"); if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE) ptr=strmov(ptr," delay_key_write=1"); if (share->row_type != ROW_TYPE_DEFAULT) ptr=strxmov(ptr, " row_format=", ha_row_type[(uint) share->row_type], NullS); if (share->key_block_size) { ptr= strmov(ptr, " KEY_BLOCK_SIZE="); ptr= longlong10_to_str(share->key_block_size, ptr, 10); } #ifdef WITH_PARTITION_STORAGE_ENGINE if (is_partitioned) ptr= strmov(ptr, " partitioned"); #endif table->field[19]->store(option_buff+1, (ptr == option_buff ? 0 : (uint) (ptr-option_buff)-1), cs); tmp_buff= (share->table_charset ? share->table_charset->name : "default"); table->field[17]->store(tmp_buff, strlen(tmp_buff), cs); if (share->comment.str) table->field[20]->store(share->comment.str, share->comment.length, cs); /* Collect table info from the storage engine */ if(file) { /* If info() fails, then there's nothing else to do */ if ((info_error= file->info(HA_STATUS_VARIABLE | HA_STATUS_TIME | HA_STATUS_VARIABLE_EXTRA | HA_STATUS_AUTO)) != 0) goto err; enum row_type row_type = file->get_row_type(); switch (row_type) { case ROW_TYPE_NOT_USED: case ROW_TYPE_DEFAULT: tmp_buff= ((share->db_options_in_use & HA_OPTION_COMPRESS_RECORD) ? "Compressed" : (share->db_options_in_use & HA_OPTION_PACK_RECORD) ? "Dynamic" : "Fixed"); break; case ROW_TYPE_FIXED: tmp_buff= "Fixed"; break; case ROW_TYPE_DYNAMIC: tmp_buff= "Dynamic"; break; case ROW_TYPE_COMPRESSED: tmp_buff= "Compressed"; break; case ROW_TYPE_REDUNDANT: tmp_buff= "Redundant"; break; case ROW_TYPE_COMPACT: tmp_buff= "Compact"; break; case ROW_TYPE_PAGE: tmp_buff= "Paged"; break; } table->field[6]->store(tmp_buff, strlen(tmp_buff), cs); if (!tables->schema_table) { table->field[7]->store((longlong) file->stats.records, TRUE); table->field[7]->set_notnull(); } table->field[8]->store((longlong) file->stats.mean_rec_length, TRUE); table->field[9]->store((longlong) file->stats.data_file_length, TRUE); if (file->stats.max_data_file_length) { table->field[10]->store((longlong) file->stats.max_data_file_length, TRUE); } table->field[11]->store((longlong) file->stats.index_file_length, TRUE); table->field[12]->store((longlong) file->stats.delete_length, TRUE); if (show_table->found_next_number_field) { table->field[13]->store((longlong) file->stats.auto_increment_value, TRUE); table->field[13]->set_notnull(); } if (file->stats.create_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t) file->stats.create_time); table->field[14]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[14]->set_notnull(); } if (file->stats.update_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t) file->stats.update_time); table->field[15]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[15]->set_notnull(); } if (file->stats.check_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t) file->stats.check_time); table->field[16]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[16]->set_notnull(); } if (file->ha_table_flags() & (ulong) HA_HAS_CHECKSUM) { table->field[18]->store((longlong) file->checksum(), TRUE); table->field[18]->set_notnull(); } } } err: if (res || info_error) { /* If an error was encountered, push a warning, set the TABLE COMMENT column with the error text, and clear the error so that the operation can continue. */ const char *error= thd->is_error() ? thd->stmt_da->message() : ""; table->field[20]->store(error, strlen(error), cs); if (thd->is_error()) { push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); } } DBUG_RETURN(schema_table_store_record(thd, table)); } /** @brief Store field characteristics into appropriate I_S table columns @param[in] table I_S table @param[in] field processed field @param[in] cs I_S table charset @param[in] offset offset from beginning of table to DATE_TYPE column in I_S table @return void */ void store_column_type(TABLE *table, Field *field, CHARSET_INFO *cs, uint offset) { bool is_blob; int decimals, field_length; const char *tmp_buff; char column_type_buff[MAX_FIELD_WIDTH]; String column_type(column_type_buff, sizeof(column_type_buff), cs); field->sql_type(column_type); /* DTD_IDENTIFIER column */ table->field[offset + 7]->store(column_type.ptr(), column_type.length(), cs); table->field[offset + 7]->set_notnull(); /* DATA_TYPE column: MySQL column type has the following format: base_type [(dimension)] [unsigned] [zerofill]. For DATA_TYPE column we extract only base type. */ tmp_buff= strchr(column_type.ptr(), '('); if (!tmp_buff) /* if there is no dimention part then check the presence of [unsigned] [zerofill] attributes and cut them of if exist. */ tmp_buff= strchr(column_type.ptr(), ' '); table->field[offset]->store(column_type.ptr(), (tmp_buff ? tmp_buff - column_type.ptr() : column_type.length()), cs); is_blob= (field->type() == MYSQL_TYPE_BLOB); if (field->has_charset() || is_blob || field->real_type() == MYSQL_TYPE_VARCHAR || // For varbinary type field->real_type() == MYSQL_TYPE_STRING) // For binary type { uint32 octet_max_length= field->max_display_length(); if (is_blob && octet_max_length != (uint32) 4294967295U) octet_max_length /= field->charset()->mbmaxlen; longlong char_max_len= is_blob ? (longlong) octet_max_length / field->charset()->mbminlen : (longlong) octet_max_length / field->charset()->mbmaxlen; /* CHARACTER_MAXIMUM_LENGTH column*/ table->field[offset + 1]->store(char_max_len, TRUE); table->field[offset + 1]->set_notnull(); /* CHARACTER_OCTET_LENGTH column */ table->field[offset + 2]->store((longlong) octet_max_length, TRUE); table->field[offset + 2]->set_notnull(); } /* Calculate field_length and decimals. They are set to -1 if they should not be set (we should return NULL) */ decimals= field->decimals(); switch (field->type()) { case MYSQL_TYPE_NEWDECIMAL: field_length= ((Field_new_decimal*) field)->precision; break; case MYSQL_TYPE_DECIMAL: field_length= field->field_length - (decimals ? 2 : 1); break; case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24: field_length= field->max_display_length() - 1; break; case MYSQL_TYPE_LONGLONG: field_length= field->max_display_length() - ((field->flags & UNSIGNED_FLAG) ? 0 : 1); break; case MYSQL_TYPE_BIT: field_length= field->max_display_length(); decimals= -1; // return NULL break; case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: field_length= field->field_length; if (decimals == NOT_FIXED_DEC) decimals= -1; // return NULL break; default: field_length= decimals= -1; break; } /* NUMERIC_PRECISION column */ if (field_length >= 0) { table->field[offset + 3]->store((longlong) field_length, TRUE); table->field[offset + 3]->set_notnull(); } /* NUMERIC_SCALE column */ if (decimals >= 0) { table->field[offset + 4]->store((longlong) decimals, TRUE); table->field[offset + 4]->set_notnull(); } if (field->has_charset()) { /* CHARACTER_SET_NAME column*/ tmp_buff= field->charset()->csname; table->field[offset + 5]->store(tmp_buff, strlen(tmp_buff), cs); table->field[offset + 5]->set_notnull(); /* COLLATION_NAME column */ tmp_buff= field->charset()->name; table->field[offset + 6]->store(tmp_buff, strlen(tmp_buff), cs); table->field[offset + 6]->set_notnull(); } } static int get_schema_column_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { LEX *lex= thd->lex; const char *wild= lex->wild ? lex->wild->ptr() : NullS; CHARSET_INFO *cs= system_charset_info; TABLE *show_table; Field **ptr, *field, *timestamp_field; int count; DBUG_ENTER("get_schema_column_record"); if (res) { if (lex->sql_command != SQLCOM_SHOW_FIELDS) { /* I.e. we are in SELECT FROM INFORMATION_SCHEMA.COLUMS rather than in SHOW COLUMNS */ if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); res= 0; } DBUG_RETURN(res); } show_table= tables->table; count= 0; ptr= show_table->field; timestamp_field= show_table->timestamp_field; show_table->use_all_columns(); // Required for default restore_record(show_table, s->default_values); for (; (field= *ptr) ; ptr++) { uchar *pos; char tmp[MAX_FIELD_WIDTH]; String type(tmp,sizeof(tmp), system_charset_info); DEBUG_SYNC(thd, "get_schema_column"); if (wild && wild[0] && wild_case_compare(system_charset_info, field->field_name,wild)) continue; count++; /* Get default row, with all NULL fields set to NULL */ restore_record(table, s->default_values); #ifndef NO_EMBEDDED_ACCESS_CHECKS uint col_access; check_access(thd,SELECT_ACL, db_name->str, &tables->grant.privilege, 0, 0, test(tables->schema_table)); col_access= get_column_grant(thd, &tables->grant, db_name->str, table_name->str, field->field_name) & COL_ACLS; if (!tables->schema_table && !col_access) continue; char *end= tmp; for (uint bitnr=0; col_access ; col_access>>=1,bitnr++) { if (col_access & 1) { *end++=','; end=strmov(end,grant_types.type_names[bitnr]); } } table->field[17]->store(tmp+1,end == tmp ? 0 : (uint) (end-tmp-1), cs); #endif table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); table->field[3]->store(field->field_name, strlen(field->field_name), cs); table->field[4]->store((longlong) count, TRUE); field->sql_type(type); table->field[14]->store(type.ptr(), type.length(), cs); if (get_field_default_value(thd, timestamp_field, field, &type, 0)) { table->field[5]->store(type.ptr(), type.length(), cs); table->field[5]->set_notnull(); } pos=(uchar*) ((field->flags & NOT_NULL_FLAG) ? "NO" : "YES"); table->field[6]->store((const char*) pos, strlen((const char*) pos), cs); store_column_type(table, field, cs, 7); pos=(uchar*) ((field->flags & PRI_KEY_FLAG) ? "PRI" : (field->flags & UNIQUE_KEY_FLAG) ? "UNI" : (field->flags & MULTIPLE_KEY_FLAG) ? "MUL":""); table->field[15]->store((const char*) pos, strlen((const char*) pos), cs); if (field->unireg_check == Field::NEXT_NUMBER) table->field[16]->store(STRING_WITH_LEN("auto_increment"), cs); if (timestamp_field == field && field->unireg_check != Field::TIMESTAMP_DN_FIELD) table->field[16]->store(STRING_WITH_LEN("on update CURRENT_TIMESTAMP"), cs); table->field[18]->store(field->comment.str, field->comment.length, cs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } DBUG_RETURN(0); } int fill_schema_charsets(THD *thd, TABLE_LIST *tables, COND *cond) { CHARSET_INFO **cs; const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; TABLE *table= tables->table; CHARSET_INFO *scs= system_charset_info; for (cs= all_charsets ; cs < all_charsets + array_elements(all_charsets) ; cs++) { CHARSET_INFO *tmp_cs= cs[0]; if (tmp_cs && (tmp_cs->state & MY_CS_PRIMARY) && (tmp_cs->state & MY_CS_AVAILABLE) && !(tmp_cs->state & MY_CS_HIDDEN) && !(wild && wild[0] && wild_case_compare(scs, tmp_cs->csname,wild))) { const char *comment; restore_record(table, s->default_values); table->field[0]->store(tmp_cs->csname, strlen(tmp_cs->csname), scs); table->field[1]->store(tmp_cs->name, strlen(tmp_cs->name), scs); comment= tmp_cs->comment ? tmp_cs->comment : ""; table->field[2]->store(comment, strlen(comment), scs); table->field[3]->store((longlong) tmp_cs->mbmaxlen, TRUE); if (schema_table_store_record(thd, table)) return 1; } } return 0; } static my_bool iter_schema_engines(THD *thd, plugin_ref plugin, void *ptable) { TABLE *table= (TABLE *) ptable; handlerton *hton= plugin_data(plugin, handlerton *); const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; CHARSET_INFO *scs= system_charset_info; handlerton *default_type= ha_default_handlerton(thd); DBUG_ENTER("iter_schema_engines"); /* Disabled plugins */ if (plugin_state(plugin) != PLUGIN_IS_READY) { struct st_mysql_plugin *plug= plugin_decl(plugin); if (!(wild && wild[0] && wild_case_compare(scs, plug->name,wild))) { restore_record(table, s->default_values); table->field[0]->store(plug->name, strlen(plug->name), scs); table->field[1]->store(C_STRING_WITH_LEN("NO"), scs); table->field[2]->store(plug->descr, strlen(plug->descr), scs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } DBUG_RETURN(0); } if (!(hton->flags & HTON_HIDDEN)) { LEX_STRING *name= plugin_name(plugin); if (!(wild && wild[0] && wild_case_compare(scs, name->str,wild))) { LEX_STRING yesno[2]= {{ C_STRING_WITH_LEN("NO") }, { C_STRING_WITH_LEN("YES") }}; LEX_STRING *tmp; const char *option_name= show_comp_option_name[(int) hton->state]; restore_record(table, s->default_values); table->field[0]->store(name->str, name->length, scs); if (hton->state == SHOW_OPTION_YES && default_type == hton) option_name= "DEFAULT"; table->field[1]->store(option_name, strlen(option_name), scs); table->field[2]->store(plugin_decl(plugin)->descr, strlen(plugin_decl(plugin)->descr), scs); tmp= &yesno[test(hton->commit)]; table->field[3]->store(tmp->str, tmp->length, scs); table->field[3]->set_notnull(); tmp= &yesno[test(hton->prepare)]; table->field[4]->store(tmp->str, tmp->length, scs); table->field[4]->set_notnull(); tmp= &yesno[test(hton->savepoint_set)]; table->field[5]->store(tmp->str, tmp->length, scs); table->field[5]->set_notnull(); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } DBUG_RETURN(0); } int fill_schema_engines(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_schema_engines"); if (plugin_foreach_with_mask(thd, iter_schema_engines, MYSQL_STORAGE_ENGINE_PLUGIN, ~PLUGIN_IS_FREED, tables->table)) DBUG_RETURN(1); DBUG_RETURN(0); } int fill_schema_collation(THD *thd, TABLE_LIST *tables, COND *cond) { CHARSET_INFO **cs; const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; TABLE *table= tables->table; CHARSET_INFO *scs= system_charset_info; for (cs= all_charsets ; cs < all_charsets + array_elements(all_charsets) ; cs++ ) { CHARSET_INFO **cl; CHARSET_INFO *tmp_cs= cs[0]; if (!tmp_cs || !(tmp_cs->state & MY_CS_AVAILABLE) || (tmp_cs->state & MY_CS_HIDDEN) || !(tmp_cs->state & MY_CS_PRIMARY)) continue; for (cl= all_charsets; cl < all_charsets + array_elements(all_charsets) ; cl ++) { CHARSET_INFO *tmp_cl= cl[0]; if (!tmp_cl || !(tmp_cl->state & MY_CS_AVAILABLE) || !my_charset_same(tmp_cs, tmp_cl)) continue; if (!(wild && wild[0] && wild_case_compare(scs, tmp_cl->name,wild))) { const char *tmp_buff; restore_record(table, s->default_values); table->field[0]->store(tmp_cl->name, strlen(tmp_cl->name), scs); table->field[1]->store(tmp_cl->csname , strlen(tmp_cl->csname), scs); table->field[2]->store((longlong) tmp_cl->number, TRUE); tmp_buff= (tmp_cl->state & MY_CS_PRIMARY) ? "Yes" : ""; table->field[3]->store(tmp_buff, strlen(tmp_buff), scs); tmp_buff= (tmp_cl->state & MY_CS_COMPILED)? "Yes" : ""; table->field[4]->store(tmp_buff, strlen(tmp_buff), scs); table->field[5]->store((longlong) tmp_cl->strxfrm_multiply, TRUE); if (schema_table_store_record(thd, table)) return 1; } } } return 0; } int fill_schema_coll_charset_app(THD *thd, TABLE_LIST *tables, COND *cond) { CHARSET_INFO **cs; TABLE *table= tables->table; CHARSET_INFO *scs= system_charset_info; for (cs= all_charsets ; cs < all_charsets + array_elements(all_charsets) ; cs++ ) { CHARSET_INFO **cl; CHARSET_INFO *tmp_cs= cs[0]; if (!tmp_cs || !(tmp_cs->state & MY_CS_AVAILABLE) || !(tmp_cs->state & MY_CS_PRIMARY)) continue; for (cl= all_charsets; cl < all_charsets + array_elements(all_charsets) ; cl ++) { CHARSET_INFO *tmp_cl= cl[0]; if (!tmp_cl || !(tmp_cl->state & MY_CS_AVAILABLE) || (tmp_cl->state & MY_CS_HIDDEN) || !my_charset_same(tmp_cs,tmp_cl)) continue; restore_record(table, s->default_values); table->field[0]->store(tmp_cl->name, strlen(tmp_cl->name), scs); table->field[1]->store(tmp_cl->csname , strlen(tmp_cl->csname), scs); if (schema_table_store_record(thd, table)) return 1; } } return 0; } static inline void copy_field_as_string(Field *to_field, Field *from_field) { char buff[MAX_FIELD_WIDTH]; String tmp_str(buff, sizeof(buff), system_charset_info); from_field->val_str(&tmp_str); to_field->store(tmp_str.ptr(), tmp_str.length(), system_charset_info); } /** @brief Store record into I_S.PARAMETERS table @param[in] thd thread handler @param[in] table I_S table @param[in] proc_table 'mysql.proc' table @param[in] wild wild string, not used for now, will be useful if we add 'SHOW PARAMETERs' @param[in] full_access if 1 user has privileges on the routine @param[in] sp_user user in 'user@host' format @return Operation status @retval 0 ok @retval 1 error */ bool store_schema_params(THD *thd, TABLE *table, TABLE *proc_table, const char *wild, bool full_access, const char *sp_user) { TABLE_SHARE share; TABLE tbl; CHARSET_INFO *cs= system_charset_info; char params_buff[MAX_FIELD_WIDTH], returns_buff[MAX_FIELD_WIDTH], sp_db_buff[NAME_LEN], sp_name_buff[NAME_LEN], path[FN_REFLEN], definer_buff[USERNAME_LENGTH + HOSTNAME_LENGTH + 1]; String params(params_buff, sizeof(params_buff), cs); String returns(returns_buff, sizeof(returns_buff), cs); String sp_db(sp_db_buff, sizeof(sp_db_buff), cs); String sp_name(sp_name_buff, sizeof(sp_name_buff), cs); String definer(definer_buff, sizeof(definer_buff), cs); sp_head *sp; uint routine_type; bool free_sp_head; DBUG_ENTER("store_schema_params"); bzero((char*) &tbl, sizeof(TABLE)); (void) build_table_filename(path, sizeof(path), "", "", "", 0); init_tmp_table_share(thd, &share, "", 0, "", path); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_FIELD_DB], &sp_db); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_FIELD_NAME], &sp_name); get_field(thd->mem_root,proc_table->field[MYSQL_PROC_FIELD_DEFINER],&definer); routine_type= (uint) proc_table->field[MYSQL_PROC_MYSQL_TYPE]->val_int(); if (!full_access) full_access= !strcmp(sp_user, definer.ptr()); if (!full_access && check_some_routine_access(thd, sp_db.ptr(),sp_name.ptr(), routine_type == TYPE_ENUM_PROCEDURE)) DBUG_RETURN(0); params.length(0); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_FIELD_PARAM_LIST], &params); returns.length(0); if (routine_type == TYPE_ENUM_FUNCTION) get_field(thd->mem_root, proc_table->field[MYSQL_PROC_FIELD_RETURNS], &returns); sp= sp_load_for_information_schema(thd, proc_table, &sp_db, &sp_name, (ulong) proc_table-> field[MYSQL_PROC_FIELD_SQL_MODE]->val_int(), routine_type, returns.c_ptr_safe(), params.c_ptr_safe(), &free_sp_head); if (sp) { Field *field; Create_field *field_def; String tmp_string; if (routine_type == TYPE_ENUM_FUNCTION) { restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(sp_db.ptr(), sp_db.length(), cs); table->field[2]->store(sp_name.ptr(), sp_name.length(), cs); table->field[3]->store((longlong) 0, TRUE); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_MYSQL_TYPE], &tmp_string); table->field[14]->store(tmp_string.ptr(), tmp_string.length(), cs); field_def= &sp->m_return_field_def; field= make_field(&share, (uchar*) 0, field_def->length, (uchar*) "", 0, field_def->pack_flag, field_def->sql_type, field_def->charset, field_def->geom_type, Field::NONE, field_def->interval, ""); field->table= &tbl; tbl.in_use= thd; store_column_type(table, field, cs, 6); if (schema_table_store_record(thd, table)) { free_table_share(&share); if (free_sp_head) delete sp; DBUG_RETURN(1); } } sp_pcontext *spcont= sp->get_parse_context(); uint params= spcont->context_var_count(); for (uint i= 0 ; i < params ; i++) { const char *tmp_buff; sp_variable_t *spvar= spcont->find_variable(i); field_def= &spvar->field_def; switch (spvar->mode) { case sp_param_in: tmp_buff= "IN"; break; case sp_param_out: tmp_buff= "OUT"; break; case sp_param_inout: tmp_buff= "INOUT"; break; default: tmp_buff= ""; break; } restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(sp_db.ptr(), sp_db.length(), cs); table->field[2]->store(sp_name.ptr(), sp_name.length(), cs); table->field[3]->store((longlong) i + 1, TRUE); table->field[4]->store(tmp_buff, strlen(tmp_buff), cs); table->field[4]->set_notnull(); table->field[5]->store(spvar->name.str, spvar->name.length, cs); table->field[5]->set_notnull(); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_MYSQL_TYPE], &tmp_string); table->field[14]->store(tmp_string.ptr(), tmp_string.length(), cs); field= make_field(&share, (uchar*) 0, field_def->length, (uchar*) "", 0, field_def->pack_flag, field_def->sql_type, field_def->charset, field_def->geom_type, Field::NONE, field_def->interval, spvar->name.str); field->table= &tbl; tbl.in_use= thd; store_column_type(table, field, cs, 6); if (schema_table_store_record(thd, table)) { free_table_share(&share); if (free_sp_head) delete sp; DBUG_RETURN(1); } } if (free_sp_head) delete sp; } free_table_share(&share); DBUG_RETURN(0); } bool store_schema_proc(THD *thd, TABLE *table, TABLE *proc_table, const char *wild, bool full_access, const char *sp_user) { MYSQL_TIME time; LEX *lex= thd->lex; CHARSET_INFO *cs= system_charset_info; char sp_db_buff[NAME_LEN + 1], sp_name_buff[NAME_LEN + 1], definer_buff[USERNAME_LENGTH + HOSTNAME_LENGTH + 2], returns_buff[MAX_FIELD_WIDTH]; String sp_db(sp_db_buff, sizeof(sp_db_buff), cs); String sp_name(sp_name_buff, sizeof(sp_name_buff), cs); String definer(definer_buff, sizeof(definer_buff), cs); String returns(returns_buff, sizeof(returns_buff), cs); proc_table->field[MYSQL_PROC_FIELD_DB]->val_str(&sp_db); proc_table->field[MYSQL_PROC_FIELD_NAME]->val_str(&sp_name); proc_table->field[MYSQL_PROC_FIELD_DEFINER]->val_str(&definer); if (!full_access) full_access= !strcmp(sp_user, definer.c_ptr_safe()); if (!full_access && check_some_routine_access(thd, sp_db.c_ptr_safe(), sp_name.c_ptr_safe(), proc_table->field[MYSQL_PROC_MYSQL_TYPE]-> val_int() == TYPE_ENUM_PROCEDURE)) return 0; if ((lex->sql_command == SQLCOM_SHOW_STATUS_PROC && proc_table->field[MYSQL_PROC_MYSQL_TYPE]->val_int() == TYPE_ENUM_PROCEDURE) || (lex->sql_command == SQLCOM_SHOW_STATUS_FUNC && proc_table->field[MYSQL_PROC_MYSQL_TYPE]->val_int() == TYPE_ENUM_FUNCTION) || (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0) { restore_record(table, s->default_values); if (!wild || !wild[0] || !wild_case_compare(system_charset_info, sp_name.c_ptr_safe(), wild)) { int enum_idx= (int) proc_table->field[MYSQL_PROC_FIELD_ACCESS]->val_int(); table->field[3]->store(sp_name.ptr(), sp_name.length(), cs); copy_field_as_string(table->field[0], proc_table->field[MYSQL_PROC_FIELD_SPECIFIC_NAME]); table->field[1]->store(STRING_WITH_LEN("def"), cs); table->field[2]->store(sp_db.ptr(), sp_db.length(), cs); copy_field_as_string(table->field[4], proc_table->field[MYSQL_PROC_MYSQL_TYPE]); if (proc_table->field[MYSQL_PROC_MYSQL_TYPE]->val_int() == TYPE_ENUM_FUNCTION) { sp_head *sp; bool free_sp_head; proc_table->field[MYSQL_PROC_FIELD_RETURNS]->val_str(&returns); sp= sp_load_for_information_schema(thd, proc_table, &sp_db, &sp_name, (ulong) proc_table-> field[MYSQL_PROC_FIELD_SQL_MODE]-> val_int(), TYPE_ENUM_FUNCTION, returns.c_ptr_safe(), "", &free_sp_head); if (sp) { char path[FN_REFLEN]; TABLE_SHARE share; TABLE tbl; Field *field; Create_field *field_def= &sp->m_return_field_def; bzero((char*) &tbl, sizeof(TABLE)); (void) build_table_filename(path, sizeof(path), "", "", "", 0); init_tmp_table_share(thd, &share, "", 0, "", path); field= make_field(&share, (uchar*) 0, field_def->length, (uchar*) "", 0, field_def->pack_flag, field_def->sql_type, field_def->charset, field_def->geom_type, Field::NONE, field_def->interval, ""); field->table= &tbl; tbl.in_use= thd; store_column_type(table, field, cs, 5); free_table_share(&share); if (free_sp_head) delete sp; } } if (full_access) { copy_field_as_string(table->field[14], proc_table->field[MYSQL_PROC_FIELD_BODY_UTF8]); table->field[14]->set_notnull(); } table->field[13]->store(STRING_WITH_LEN("SQL"), cs); table->field[17]->store(STRING_WITH_LEN("SQL"), cs); copy_field_as_string(table->field[18], proc_table->field[MYSQL_PROC_FIELD_DETERMINISTIC]); table->field[19]->store(sp_data_access_name[enum_idx].str, sp_data_access_name[enum_idx].length , cs); copy_field_as_string(table->field[21], proc_table->field[MYSQL_PROC_FIELD_SECURITY_TYPE]); bzero((char *)&time, sizeof(time)); ((Field_timestamp *) proc_table->field[MYSQL_PROC_FIELD_CREATED])-> get_time(&time); table->field[22]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); bzero((char *)&time, sizeof(time)); ((Field_timestamp *) proc_table->field[MYSQL_PROC_FIELD_MODIFIED])-> get_time(&time); table->field[23]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); copy_field_as_string(table->field[24], proc_table->field[MYSQL_PROC_FIELD_SQL_MODE]); copy_field_as_string(table->field[25], proc_table->field[MYSQL_PROC_FIELD_COMMENT]); table->field[26]->store(definer.ptr(), definer.length(), cs); copy_field_as_string(table->field[27], proc_table-> field[MYSQL_PROC_FIELD_CHARACTER_SET_CLIENT]); copy_field_as_string(table->field[28], proc_table-> field[MYSQL_PROC_FIELD_COLLATION_CONNECTION]); copy_field_as_string(table->field[29], proc_table->field[MYSQL_PROC_FIELD_DB_COLLATION]); return schema_table_store_record(thd, table); } } return 0; } int fill_schema_proc(THD *thd, TABLE_LIST *tables, COND *cond) { TABLE *proc_table; TABLE_LIST proc_tables; const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; int res= 0; TABLE *table= tables->table; bool full_access; char definer[USER_HOST_BUFF_SIZE]; Open_tables_backup open_tables_state_backup; enum enum_schema_tables schema_table_idx= get_schema_table_idx(tables->schema_table); DBUG_ENTER("fill_schema_proc"); strxmov(definer, thd->security_ctx->priv_user, "@", thd->security_ctx->priv_host, NullS); /* We use this TABLE_LIST instance only for checking of privileges. */ bzero((char*) &proc_tables,sizeof(proc_tables)); proc_tables.db= (char*) "mysql"; proc_tables.db_length= 5; proc_tables.table_name= proc_tables.alias= (char*) "proc"; proc_tables.table_name_length= 4; proc_tables.lock_type= TL_READ; full_access= !check_table_access(thd, SELECT_ACL, &proc_tables, FALSE, 1, TRUE); if (!(proc_table= open_proc_table_for_read(thd, &open_tables_state_backup))) { DBUG_RETURN(1); } if (proc_table->file->ha_index_init(0, 1)) { res= 1; goto err; } if ((res= proc_table->file->index_first(proc_table->record[0]))) { res= (res == HA_ERR_END_OF_FILE) ? 0 : 1; goto err; } if (schema_table_idx == SCH_PROCEDURES ? store_schema_proc(thd, table, proc_table, wild, full_access, definer) : store_schema_params(thd, table, proc_table, wild, full_access, definer)) { res= 1; goto err; } while (!proc_table->file->index_next(proc_table->record[0])) { if (schema_table_idx == SCH_PROCEDURES ? store_schema_proc(thd, table, proc_table, wild, full_access, definer): store_schema_params(thd, table, proc_table, wild, full_access, definer)) { res= 1; goto err; } } err: if (proc_table->file->inited) (void) proc_table->file->ha_index_end(); close_system_tables(thd, &open_tables_state_backup); DBUG_RETURN(res); } static int get_schema_stat_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { CHARSET_INFO *cs= system_charset_info; DBUG_ENTER("get_schema_stat_record"); if (res) { if (thd->lex->sql_command != SQLCOM_SHOW_KEYS) { /* I.e. we are in SELECT FROM INFORMATION_SCHEMA.STATISTICS rather than in SHOW KEYS */ if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); res= 0; } DBUG_RETURN(res); } else if (!tables->view) { TABLE *show_table= tables->table; KEY *key_info=show_table->s->key_info; if (show_table->file) show_table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME); for (uint i=0 ; i < show_table->s->keys ; i++,key_info++) { KEY_PART_INFO *key_part= key_info->key_part; const char *str; for (uint j=0 ; j < key_info->key_parts ; j++,key_part++) { restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); table->field[3]->store((longlong) ((key_info->flags & HA_NOSAME) ? 0 : 1), TRUE); table->field[4]->store(db_name->str, db_name->length, cs); table->field[5]->store(key_info->name, strlen(key_info->name), cs); table->field[6]->store((longlong) (j+1), TRUE); str=(key_part->field ? key_part->field->field_name : "?unknown field?"); table->field[7]->store(str, strlen(str), cs); if (show_table->file) { if (show_table->file->index_flags(i, j, 0) & HA_READ_ORDER) { table->field[8]->store(((key_part->key_part_flag & HA_REVERSE_SORT) ? "D" : "A"), 1, cs); table->field[8]->set_notnull(); } KEY *key=show_table->key_info+i; if (key->rec_per_key[j]) { ha_rows records=(show_table->file->stats.records / key->rec_per_key[j]); table->field[9]->store((longlong) records, TRUE); table->field[9]->set_notnull(); } str= show_table->file->index_type(i); table->field[13]->store(str, strlen(str), cs); } if (!(key_info->flags & HA_FULLTEXT) && (key_part->field && key_part->length != show_table->s->field[key_part->fieldnr-1]->key_length())) { table->field[10]->store((longlong) key_part->length / key_part->field->charset()->mbmaxlen, TRUE); table->field[10]->set_notnull(); } uint flags= key_part->field ? key_part->field->flags : 0; const char *pos=(char*) ((flags & NOT_NULL_FLAG) ? "" : "YES"); table->field[12]->store(pos, strlen(pos), cs); if (!show_table->s->keys_in_use.is_set(i)) table->field[14]->store(STRING_WITH_LEN("disabled"), cs); else table->field[14]->store("", 0, cs); table->field[14]->set_notnull(); DBUG_ASSERT(test(key_info->flags & HA_USES_COMMENT) == (key_info->comment.length > 0)); if (key_info->flags & HA_USES_COMMENT) table->field[15]->store(key_info->comment.str, key_info->comment.length, cs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } } DBUG_RETURN(res); } static int get_schema_views_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { CHARSET_INFO *cs= system_charset_info; char definer[USER_HOST_BUFF_SIZE]; uint definer_len; bool updatable_view; DBUG_ENTER("get_schema_views_record"); if (tables->view) { Security_context *sctx= thd->security_ctx; if (!tables->allowed_show) { if (!my_strcasecmp(system_charset_info, tables->definer.user.str, sctx->priv_user) && !my_strcasecmp(system_charset_info, tables->definer.host.str, sctx->priv_host)) tables->allowed_show= TRUE; #ifndef NO_EMBEDDED_ACCESS_CHECKS else { if ((thd->col_access & (SHOW_VIEW_ACL|SELECT_ACL)) == (SHOW_VIEW_ACL|SELECT_ACL)) tables->allowed_show= TRUE; else { TABLE_LIST table_list; uint view_access; memset(&table_list, 0, sizeof(table_list)); table_list.db= tables->db; table_list.table_name= tables->table_name; table_list.grant.privilege= thd->col_access; view_access= get_table_grant(thd, &table_list); if ((view_access & (SHOW_VIEW_ACL|SELECT_ACL)) == (SHOW_VIEW_ACL|SELECT_ACL)) tables->allowed_show= TRUE; } } #endif } restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); if (tables->allowed_show) { table->field[3]->store(tables->view_body_utf8.str, tables->view_body_utf8.length, cs); } if (tables->with_check != VIEW_CHECK_NONE) { if (tables->with_check == VIEW_CHECK_LOCAL) table->field[4]->store(STRING_WITH_LEN("LOCAL"), cs); else table->field[4]->store(STRING_WITH_LEN("CASCADED"), cs); } else table->field[4]->store(STRING_WITH_LEN("NONE"), cs); /* Only try to fill in the information about view updatability if it is requested as part of the top-level query (i.e. it's select * from i_s.views, as opposed to, say, select security_type from i_s.views). Do not try to access the underlying tables if there was an error when opening the view: all underlying tables are released back to the table definition cache on error inside open_normal_and_derived_tables(). If a field is not assigned explicitly, it defaults to NULL. */ if (res == FALSE && table->pos_in_table_list->table_open_method & OPEN_FULL_TABLE) { updatable_view= 0; if (tables->algorithm != VIEW_ALGORITHM_TMPTABLE) { /* We should use tables->view->select_lex.item_list here and can not use Field_iterator_view because the view always uses temporary algorithm during opening for I_S and TABLE_LIST fields 'field_translation' & 'field_translation_end' are uninitialized is this case. */ List<Item> *fields= &tables->view->select_lex.item_list; List_iterator<Item> it(*fields); Item *item; Item_field *field; /* check that at least one column in view is updatable */ while ((item= it++)) { if ((field= item->filed_for_view_update()) && field->field && !field->field->table->pos_in_table_list->schema_table) { updatable_view= 1; break; } } if (updatable_view && !tables->view->can_be_merged()) updatable_view= 0; } if (updatable_view) table->field[5]->store(STRING_WITH_LEN("YES"), cs); else table->field[5]->store(STRING_WITH_LEN("NO"), cs); } definer_len= (strxmov(definer, tables->definer.user.str, "@", tables->definer.host.str, NullS) - definer); table->field[6]->store(definer, definer_len, cs); if (tables->view_suid) table->field[7]->store(STRING_WITH_LEN("DEFINER"), cs); else table->field[7]->store(STRING_WITH_LEN("INVOKER"), cs); table->field[8]->store(tables->view_creation_ctx->get_client_cs()->csname, strlen(tables->view_creation_ctx-> get_client_cs()->csname), cs); table->field[9]->store(tables->view_creation_ctx-> get_connection_cl()->name, strlen(tables->view_creation_ctx-> get_connection_cl()->name), cs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); if (res && thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); } if (res) thd->clear_error(); DBUG_RETURN(0); } bool store_constraints(THD *thd, TABLE *table, LEX_STRING *db_name, LEX_STRING *table_name, const char *key_name, uint key_len, const char *con_type, uint con_len) { CHARSET_INFO *cs= system_charset_info; restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(key_name, key_len, cs); table->field[3]->store(db_name->str, db_name->length, cs); table->field[4]->store(table_name->str, table_name->length, cs); table->field[5]->store(con_type, con_len, cs); return schema_table_store_record(thd, table); } static int get_schema_constraints_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { DBUG_ENTER("get_schema_constraints_record"); if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } else if (!tables->view) { List<FOREIGN_KEY_INFO> f_key_list; TABLE *show_table= tables->table; KEY *key_info=show_table->key_info; uint primary_key= show_table->s->primary_key; show_table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME); for (uint i=0 ; i < show_table->s->keys ; i++, key_info++) { if (i != primary_key && !(key_info->flags & HA_NOSAME)) continue; if (i == primary_key && !strcmp(key_info->name, primary_key_name)) { if (store_constraints(thd, table, db_name, table_name, key_info->name, strlen(key_info->name), STRING_WITH_LEN("PRIMARY KEY"))) DBUG_RETURN(1); } else if (key_info->flags & HA_NOSAME) { if (store_constraints(thd, table, db_name, table_name, key_info->name, strlen(key_info->name), STRING_WITH_LEN("UNIQUE"))) DBUG_RETURN(1); } } show_table->file->get_foreign_key_list(thd, &f_key_list); FOREIGN_KEY_INFO *f_key_info; List_iterator_fast<FOREIGN_KEY_INFO> it(f_key_list); while ((f_key_info=it++)) { if (store_constraints(thd, table, db_name, table_name, f_key_info->foreign_id->str, strlen(f_key_info->foreign_id->str), "FOREIGN KEY", 11)) DBUG_RETURN(1); } } DBUG_RETURN(res); } static bool store_trigger(THD *thd, TABLE *table, LEX_STRING *db_name, LEX_STRING *table_name, LEX_STRING *trigger_name, enum trg_event_type event, enum trg_action_time_type timing, LEX_STRING *trigger_stmt, ulong sql_mode, LEX_STRING *definer_buffer, LEX_STRING *client_cs_name, LEX_STRING *connection_cl_name, LEX_STRING *db_cl_name) { CHARSET_INFO *cs= system_charset_info; LEX_STRING sql_mode_rep; restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(trigger_name->str, trigger_name->length, cs); table->field[3]->store(trg_event_type_names[event].str, trg_event_type_names[event].length, cs); table->field[4]->store(STRING_WITH_LEN("def"), cs); table->field[5]->store(db_name->str, db_name->length, cs); table->field[6]->store(table_name->str, table_name->length, cs); table->field[9]->store(trigger_stmt->str, trigger_stmt->length, cs); table->field[10]->store(STRING_WITH_LEN("ROW"), cs); table->field[11]->store(trg_action_time_type_names[timing].str, trg_action_time_type_names[timing].length, cs); table->field[14]->store(STRING_WITH_LEN("OLD"), cs); table->field[15]->store(STRING_WITH_LEN("NEW"), cs); sql_mode_string_representation(thd, sql_mode, &sql_mode_rep); table->field[17]->store(sql_mode_rep.str, sql_mode_rep.length, cs); table->field[18]->store(definer_buffer->str, definer_buffer->length, cs); table->field[19]->store(client_cs_name->str, client_cs_name->length, cs); table->field[20]->store(connection_cl_name->str, connection_cl_name->length, cs); table->field[21]->store(db_cl_name->str, db_cl_name->length, cs); return schema_table_store_record(thd, table); } static int get_schema_triggers_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { DBUG_ENTER("get_schema_triggers_record"); /* res can be non zero value when processed table is a view or error happened during opening of processed table. */ if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } if (!tables->view && tables->table->triggers) { Table_triggers_list *triggers= tables->table->triggers; int event, timing; if (check_table_access(thd, TRIGGER_ACL, tables, FALSE, 1, TRUE)) goto ret; for (event= 0; event < (int)TRG_EVENT_MAX; event++) { for (timing= 0; timing < (int)TRG_ACTION_MAX; timing++) { LEX_STRING trigger_name; LEX_STRING trigger_stmt; ulong sql_mode; char definer_holder[USER_HOST_BUFF_SIZE]; LEX_STRING definer_buffer; LEX_STRING client_cs_name; LEX_STRING connection_cl_name; LEX_STRING db_cl_name; definer_buffer.str= definer_holder; if (triggers->get_trigger_info(thd, (enum trg_event_type) event, (enum trg_action_time_type)timing, &trigger_name, &trigger_stmt, &sql_mode, &definer_buffer, &client_cs_name, &connection_cl_name, &db_cl_name)) continue; if (store_trigger(thd, table, db_name, table_name, &trigger_name, (enum trg_event_type) event, (enum trg_action_time_type) timing, &trigger_stmt, sql_mode, &definer_buffer, &client_cs_name, &connection_cl_name, &db_cl_name)) DBUG_RETURN(1); } } } ret: DBUG_RETURN(0); } void store_key_column_usage(TABLE *table, LEX_STRING *db_name, LEX_STRING *table_name, const char *key_name, uint key_len, const char *con_type, uint con_len, longlong idx) { CHARSET_INFO *cs= system_charset_info; table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(key_name, key_len, cs); table->field[3]->store(STRING_WITH_LEN("def"), cs); table->field[4]->store(db_name->str, db_name->length, cs); table->field[5]->store(table_name->str, table_name->length, cs); table->field[6]->store(con_type, con_len, cs); table->field[7]->store((longlong) idx, TRUE); } static int get_schema_key_column_usage_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { DBUG_ENTER("get_schema_key_column_usage_record"); if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } else if (!tables->view) { List<FOREIGN_KEY_INFO> f_key_list; TABLE *show_table= tables->table; KEY *key_info=show_table->key_info; uint primary_key= show_table->s->primary_key; show_table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME); for (uint i=0 ; i < show_table->s->keys ; i++, key_info++) { if (i != primary_key && !(key_info->flags & HA_NOSAME)) continue; uint f_idx= 0; KEY_PART_INFO *key_part= key_info->key_part; for (uint j=0 ; j < key_info->key_parts ; j++,key_part++) { if (key_part->field) { f_idx++; restore_record(table, s->default_values); store_key_column_usage(table, db_name, table_name, key_info->name, strlen(key_info->name), key_part->field->field_name, strlen(key_part->field->field_name), (longlong) f_idx); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } } show_table->file->get_foreign_key_list(thd, &f_key_list); FOREIGN_KEY_INFO *f_key_info; List_iterator_fast<FOREIGN_KEY_INFO> fkey_it(f_key_list); while ((f_key_info= fkey_it++)) { LEX_STRING *f_info; LEX_STRING *r_info; List_iterator_fast<LEX_STRING> it(f_key_info->foreign_fields), it1(f_key_info->referenced_fields); uint f_idx= 0; while ((f_info= it++)) { r_info= it1++; f_idx++; restore_record(table, s->default_values); store_key_column_usage(table, db_name, table_name, f_key_info->foreign_id->str, f_key_info->foreign_id->length, f_info->str, f_info->length, (longlong) f_idx); table->field[8]->store((longlong) f_idx, TRUE); table->field[8]->set_notnull(); table->field[9]->store(f_key_info->referenced_db->str, f_key_info->referenced_db->length, system_charset_info); table->field[9]->set_notnull(); table->field[10]->store(f_key_info->referenced_table->str, f_key_info->referenced_table->length, system_charset_info); table->field[10]->set_notnull(); table->field[11]->store(r_info->str, r_info->length, system_charset_info); table->field[11]->set_notnull(); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } } DBUG_RETURN(res); } #ifdef WITH_PARTITION_STORAGE_ENGINE static void collect_partition_expr(THD *thd, List<char> &field_list, String *str) { List_iterator<char> part_it(field_list); ulong no_fields= field_list.elements; const char *field_str; str->length(0); while ((field_str= part_it++)) { append_identifier(thd, str, field_str, strlen(field_str)); if (--no_fields != 0) str->append(","); } return; } /* Convert a string in a given character set to a string which can be used for FRM file storage in which case use_hex is TRUE and we store the character constants as hex strings in the character set encoding their field have. In the case of SHOW CREATE TABLE and the PARTITIONS information schema table we instead provide utf8 strings to the user and convert to the utf8 character set. SYNOPSIS get_cs_converted_part_value_from_string() item Item from which constant comes input_str String as provided by val_str after conversion to character set output_str Out value: The string created cs Character set string is encoded in NULL for INT_RESULT's here use_hex TRUE => hex string created FALSE => utf8 constant string created RETURN VALUES TRUE Error FALSE Ok */ int get_cs_converted_part_value_from_string(THD *thd, Item *item, String *input_str, String *output_str, CHARSET_INFO *cs, bool use_hex) { if (item->result_type() == INT_RESULT) { longlong value= item->val_int(); output_str->set(value, system_charset_info); return FALSE; } if (!input_str) { my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0)); return TRUE; } get_cs_converted_string_value(thd, input_str, output_str, cs, use_hex); return FALSE; } #endif static void store_schema_partitions_record(THD *thd, TABLE *schema_table, TABLE *showing_table, partition_element *part_elem, handler *file, uint part_id) { TABLE* table= schema_table; CHARSET_INFO *cs= system_charset_info; PARTITION_STATS stat_info; MYSQL_TIME time; file->get_dynamic_partition_info(&stat_info, part_id); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[12]->store((longlong) stat_info.records, TRUE); table->field[13]->store((longlong) stat_info.mean_rec_length, TRUE); table->field[14]->store((longlong) stat_info.data_file_length, TRUE); if (stat_info.max_data_file_length) { table->field[15]->store((longlong) stat_info.max_data_file_length, TRUE); table->field[15]->set_notnull(); } table->field[16]->store((longlong) stat_info.index_file_length, TRUE); table->field[17]->store((longlong) stat_info.delete_length, TRUE); if (stat_info.create_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t)stat_info.create_time); table->field[18]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[18]->set_notnull(); } if (stat_info.update_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t)stat_info.update_time); table->field[19]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[19]->set_notnull(); } if (stat_info.check_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t)stat_info.check_time); table->field[20]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[20]->set_notnull(); } if (file->ha_table_flags() & (ulong) HA_HAS_CHECKSUM) { table->field[21]->store((longlong) stat_info.check_sum, TRUE); table->field[21]->set_notnull(); } if (part_elem) { if (part_elem->part_comment) table->field[22]->store(part_elem->part_comment, strlen(part_elem->part_comment), cs); else table->field[22]->store(STRING_WITH_LEN(""), cs); if (part_elem->nodegroup_id != UNDEF_NODEGROUP) table->field[23]->store((longlong) part_elem->nodegroup_id, TRUE); else table->field[23]->store(STRING_WITH_LEN("default"), cs); table->field[24]->set_notnull(); if (part_elem->tablespace_name) table->field[24]->store(part_elem->tablespace_name, strlen(part_elem->tablespace_name), cs); else { char *ts= showing_table->s->tablespace; if(ts) table->field[24]->store(ts, strlen(ts), cs); else table->field[24]->set_null(); } } return; } #ifdef WITH_PARTITION_STORAGE_ENGINE static int get_partition_column_description(THD *thd, partition_info *part_info, part_elem_value *list_value, String &tmp_str) { uint num_elements= part_info->part_field_list.elements; uint i; DBUG_ENTER("get_partition_column_description"); for (i= 0; i < num_elements; i++) { part_column_list_val *col_val= &list_value->col_val_array[i]; if (col_val->max_value) tmp_str.append(partition_keywords[PKW_MAXVALUE].str); else if (col_val->null_value) tmp_str.append("NULL"); else { char buffer[MAX_KEY_LENGTH]; String str(buffer, sizeof(buffer), &my_charset_bin); String val_conv; Item *item= col_val->item_expression; if (!(item= part_info->get_column_item(item, part_info->part_field_array[i]))) { DBUG_RETURN(1); } String *res= item->val_str(&str); if (get_cs_converted_part_value_from_string(thd, item, res, &val_conv, part_info->part_field_array[i]->charset(), FALSE)) { DBUG_RETURN(1); } tmp_str.append(val_conv); } if (i != num_elements - 1) tmp_str.append(","); } DBUG_RETURN(0); } #endif /* WITH_PARTITION_STORAGE_ENGINE */ static int get_schema_partitions_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { CHARSET_INFO *cs= system_charset_info; char buff[61]; String tmp_res(buff, sizeof(buff), cs); String tmp_str; TABLE *show_table= tables->table; handler *file; #ifdef WITH_PARTITION_STORAGE_ENGINE partition_info *part_info; #endif DBUG_ENTER("get_schema_partitions_record"); if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } file= show_table->file; #ifdef WITH_PARTITION_STORAGE_ENGINE part_info= show_table->part_info; if (part_info) { partition_element *part_elem; List_iterator<partition_element> part_it(part_info->partitions); uint part_pos= 0, part_id= 0; restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); /* Partition method*/ switch (part_info->part_type) { case RANGE_PARTITION: case LIST_PARTITION: tmp_res.length(0); if (part_info->part_type == RANGE_PARTITION) tmp_res.append(partition_keywords[PKW_RANGE].str, partition_keywords[PKW_RANGE].length); else tmp_res.append(partition_keywords[PKW_LIST].str, partition_keywords[PKW_LIST].length); if (part_info->column_list) tmp_res.append(partition_keywords[PKW_COLUMNS].str, partition_keywords[PKW_COLUMNS].length); table->field[7]->store(tmp_res.ptr(), tmp_res.length(), cs); break; case HASH_PARTITION: tmp_res.length(0); if (part_info->linear_hash_ind) tmp_res.append(partition_keywords[PKW_LINEAR].str, partition_keywords[PKW_LINEAR].length); if (part_info->list_of_part_fields) tmp_res.append(partition_keywords[PKW_KEY].str, partition_keywords[PKW_KEY].length); else tmp_res.append(partition_keywords[PKW_HASH].str, partition_keywords[PKW_HASH].length); table->field[7]->store(tmp_res.ptr(), tmp_res.length(), cs); break; default: DBUG_ASSERT(0); my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR)); DBUG_RETURN(1); } table->field[7]->set_notnull(); /* Partition expression */ if (part_info->part_expr) { table->field[9]->store(part_info->part_func_string, part_info->part_func_len, cs); } else if (part_info->list_of_part_fields) { collect_partition_expr(thd, part_info->part_field_list, &tmp_str); table->field[9]->store(tmp_str.ptr(), tmp_str.length(), cs); } table->field[9]->set_notnull(); if (part_info->is_sub_partitioned()) { /* Subpartition method */ tmp_res.length(0); if (part_info->linear_hash_ind) tmp_res.append(partition_keywords[PKW_LINEAR].str, partition_keywords[PKW_LINEAR].length); if (part_info->list_of_subpart_fields) tmp_res.append(partition_keywords[PKW_KEY].str, partition_keywords[PKW_KEY].length); else tmp_res.append(partition_keywords[PKW_HASH].str, partition_keywords[PKW_HASH].length); table->field[8]->store(tmp_res.ptr(), tmp_res.length(), cs); table->field[8]->set_notnull(); /* Subpartition expression */ if (part_info->subpart_expr) { table->field[10]->store(part_info->subpart_func_string, part_info->subpart_func_len, cs); } else if (part_info->list_of_subpart_fields) { collect_partition_expr(thd, part_info->subpart_field_list, &tmp_str); table->field[10]->store(tmp_str.ptr(), tmp_str.length(), cs); } table->field[10]->set_notnull(); } while ((part_elem= part_it++)) { table->field[3]->store(part_elem->partition_name, strlen(part_elem->partition_name), cs); table->field[3]->set_notnull(); /* PARTITION_ORDINAL_POSITION */ table->field[5]->store((longlong) ++part_pos, TRUE); table->field[5]->set_notnull(); /* Partition description */ if (part_info->part_type == RANGE_PARTITION) { if (part_info->column_list) { List_iterator<part_elem_value> list_val_it(part_elem->list_val_list); part_elem_value *list_value= list_val_it++; tmp_str.length(0); if (get_partition_column_description(thd, part_info, list_value, tmp_str)) { DBUG_RETURN(1); } table->field[11]->store(tmp_str.ptr(), tmp_str.length(), cs); } else { if (part_elem->range_value != LONGLONG_MAX) table->field[11]->store((longlong) part_elem->range_value, FALSE); else table->field[11]->store(partition_keywords[PKW_MAXVALUE].str, partition_keywords[PKW_MAXVALUE].length, cs); } table->field[11]->set_notnull(); } else if (part_info->part_type == LIST_PARTITION) { List_iterator<part_elem_value> list_val_it(part_elem->list_val_list); part_elem_value *list_value; uint num_items= part_elem->list_val_list.elements; tmp_str.length(0); tmp_res.length(0); if (part_elem->has_null_value) { tmp_str.append("NULL"); if (num_items > 0) tmp_str.append(","); } while ((list_value= list_val_it++)) { if (part_info->column_list) { if (part_info->part_field_list.elements > 1U) tmp_str.append("("); if (get_partition_column_description(thd, part_info, list_value, tmp_str)) { DBUG_RETURN(1); } if (part_info->part_field_list.elements > 1U) tmp_str.append(")"); } else { if (!list_value->unsigned_flag) tmp_res.set(list_value->value, cs); else tmp_res.set((ulonglong)list_value->value, cs); tmp_str.append(tmp_res); } if (--num_items != 0) tmp_str.append(","); } table->field[11]->store(tmp_str.ptr(), tmp_str.length(), cs); table->field[11]->set_notnull(); } if (part_elem->subpartitions.elements) { List_iterator<partition_element> sub_it(part_elem->subpartitions); partition_element *subpart_elem; uint subpart_pos= 0; while ((subpart_elem= sub_it++)) { table->field[4]->store(subpart_elem->partition_name, strlen(subpart_elem->partition_name), cs); table->field[4]->set_notnull(); /* SUBPARTITION_ORDINAL_POSITION */ table->field[6]->store((longlong) ++subpart_pos, TRUE); table->field[6]->set_notnull(); store_schema_partitions_record(thd, table, show_table, subpart_elem, file, part_id); part_id++; if(schema_table_store_record(thd, table)) DBUG_RETURN(1); } } else { store_schema_partitions_record(thd, table, show_table, part_elem, file, part_id); part_id++; if(schema_table_store_record(thd, table)) DBUG_RETURN(1); } } DBUG_RETURN(0); } else #endif { store_schema_partitions_record(thd, table, show_table, 0, file, 0); if(schema_table_store_record(thd, table)) DBUG_RETURN(1); } DBUG_RETURN(0); } #ifdef HAVE_EVENT_SCHEDULER /* Loads an event from mysql.event and copies it's data to a row of I_S.EVENTS Synopsis copy_event_to_schema_table() thd Thread sch_table The schema table (information_schema.event) event_table The event table to use for loading (mysql.event). Returns 0 OK 1 Error */ int copy_event_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table) { const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; CHARSET_INFO *scs= system_charset_info; MYSQL_TIME time; Event_timed et; DBUG_ENTER("copy_event_to_schema_table"); restore_record(sch_table, s->default_values); if (et.load_from_row(thd, event_table)) { my_error(ER_CANNOT_LOAD_FROM_TABLE, MYF(0), event_table->alias); DBUG_RETURN(1); } if (!(!wild || !wild[0] || !wild_case_compare(scs, et.name.str, wild))) DBUG_RETURN(0); /* Skip events in schemas one does not have access to. The check is optimized. It's guaranteed in case of SHOW EVENTS that the user has access. */ if (thd->lex->sql_command != SQLCOM_SHOW_EVENTS && check_access(thd, EVENT_ACL, et.dbname.str, NULL, NULL, 0, 1)) DBUG_RETURN(0); sch_table->field[ISE_EVENT_CATALOG]->store(STRING_WITH_LEN("def"), scs); sch_table->field[ISE_EVENT_SCHEMA]-> store(et.dbname.str, et.dbname.length,scs); sch_table->field[ISE_EVENT_NAME]-> store(et.name.str, et.name.length, scs); sch_table->field[ISE_DEFINER]-> store(et.definer.str, et.definer.length, scs); const String *tz_name= et.time_zone->get_name(); sch_table->field[ISE_TIME_ZONE]-> store(tz_name->ptr(), tz_name->length(), scs); sch_table->field[ISE_EVENT_BODY]-> store(STRING_WITH_LEN("SQL"), scs); sch_table->field[ISE_EVENT_DEFINITION]->store( et.body_utf8.str, et.body_utf8.length, scs); /* SQL_MODE */ { LEX_STRING sql_mode; sql_mode_string_representation(thd, et.sql_mode, &sql_mode); sch_table->field[ISE_SQL_MODE]-> store(sql_mode.str, sql_mode.length, scs); } int not_used=0; if (et.expression) { String show_str; /* type */ sch_table->field[ISE_EVENT_TYPE]->store(STRING_WITH_LEN("RECURRING"), scs); if (Events::reconstruct_interval_expression(&show_str, et.interval, et.expression)) DBUG_RETURN(1); sch_table->field[ISE_INTERVAL_VALUE]->set_notnull(); sch_table->field[ISE_INTERVAL_VALUE]-> store(show_str.ptr(), show_str.length(), scs); LEX_STRING *ival= &interval_type_to_name[et.interval]; sch_table->field[ISE_INTERVAL_FIELD]->set_notnull(); sch_table->field[ISE_INTERVAL_FIELD]->store(ival->str, ival->length, scs); /* starts & ends . STARTS is always set - see sql_yacc.yy */ et.time_zone->gmt_sec_to_TIME(&time, et.starts); sch_table->field[ISE_STARTS]->set_notnull(); sch_table->field[ISE_STARTS]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); if (!et.ends_null) { et.time_zone->gmt_sec_to_TIME(&time, et.ends); sch_table->field[ISE_ENDS]->set_notnull(); sch_table->field[ISE_ENDS]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); } } else { /* type */ sch_table->field[ISE_EVENT_TYPE]->store(STRING_WITH_LEN("ONE TIME"), scs); et.time_zone->gmt_sec_to_TIME(&time, et.execute_at); sch_table->field[ISE_EXECUTE_AT]->set_notnull(); sch_table->field[ISE_EXECUTE_AT]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); } /* status */ switch (et.status) { case Event_parse_data::ENABLED: sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("ENABLED"), scs); break; case Event_parse_data::SLAVESIDE_DISABLED: sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("SLAVESIDE_DISABLED"), scs); break; case Event_parse_data::DISABLED: sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("DISABLED"), scs); break; default: DBUG_ASSERT(0); } sch_table->field[ISE_ORIGINATOR]->store(et.originator, TRUE); /* on_completion */ if (et.on_completion == Event_parse_data::ON_COMPLETION_DROP) sch_table->field[ISE_ON_COMPLETION]-> store(STRING_WITH_LEN("NOT PRESERVE"), scs); else sch_table->field[ISE_ON_COMPLETION]-> store(STRING_WITH_LEN("PRESERVE"), scs); number_to_datetime(et.created, &time, 0, &not_used); DBUG_ASSERT(not_used==0); sch_table->field[ISE_CREATED]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); number_to_datetime(et.modified, &time, 0, &not_used); DBUG_ASSERT(not_used==0); sch_table->field[ISE_LAST_ALTERED]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); if (et.last_executed) { et.time_zone->gmt_sec_to_TIME(&time, et.last_executed); sch_table->field[ISE_LAST_EXECUTED]->set_notnull(); sch_table->field[ISE_LAST_EXECUTED]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); } sch_table->field[ISE_EVENT_COMMENT]-> store(et.comment.str, et.comment.length, scs); sch_table->field[ISE_CLIENT_CS]->set_notnull(); sch_table->field[ISE_CLIENT_CS]->store( et.creation_ctx->get_client_cs()->csname, strlen(et.creation_ctx->get_client_cs()->csname), scs); sch_table->field[ISE_CONNECTION_CL]->set_notnull(); sch_table->field[ISE_CONNECTION_CL]->store( et.creation_ctx->get_connection_cl()->name, strlen(et.creation_ctx->get_connection_cl()->name), scs); sch_table->field[ISE_DB_CL]->set_notnull(); sch_table->field[ISE_DB_CL]->store( et.creation_ctx->get_db_cl()->name, strlen(et.creation_ctx->get_db_cl()->name), scs); if (schema_table_store_record(thd, sch_table)) DBUG_RETURN(1); DBUG_RETURN(0); } #endif int fill_open_tables(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_open_tables"); const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; TABLE *table= tables->table; CHARSET_INFO *cs= system_charset_info; OPEN_TABLE_LIST *open_list; if (!(open_list=list_open_tables(thd,thd->lex->select_lex.db, wild)) && thd->is_fatal_error) DBUG_RETURN(1); for (; open_list ; open_list=open_list->next) { restore_record(table, s->default_values); table->field[0]->store(open_list->db, strlen(open_list->db), cs); table->field[1]->store(open_list->table, strlen(open_list->table), cs); table->field[2]->store((longlong) open_list->in_use, TRUE); table->field[3]->store((longlong) open_list->locked, TRUE); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } DBUG_RETURN(0); } int fill_variables(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_variables"); int res= 0; LEX *lex= thd->lex; const char *wild= lex->wild ? lex->wild->ptr() : NullS; enum enum_schema_tables schema_table_idx= get_schema_table_idx(tables->schema_table); enum enum_var_type option_type= OPT_SESSION; bool upper_case_names= (schema_table_idx != SCH_VARIABLES); bool sorted_vars= (schema_table_idx == SCH_VARIABLES); if (lex->option_type == OPT_GLOBAL || schema_table_idx == SCH_GLOBAL_VARIABLES) option_type= OPT_GLOBAL; mysql_rwlock_rdlock(&LOCK_system_variables_hash); res= show_status_array(thd, wild, enumerate_sys_vars(thd, sorted_vars, option_type), option_type, NULL, "", tables->table, upper_case_names, cond); mysql_rwlock_unlock(&LOCK_system_variables_hash); DBUG_RETURN(res); } int fill_status(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_status"); LEX *lex= thd->lex; const char *wild= lex->wild ? lex->wild->ptr() : NullS; int res= 0; STATUS_VAR *tmp1, tmp; enum enum_schema_tables schema_table_idx= get_schema_table_idx(tables->schema_table); enum enum_var_type option_type; bool upper_case_names= (schema_table_idx != SCH_STATUS); if (schema_table_idx == SCH_STATUS) { option_type= lex->option_type; if (option_type == OPT_GLOBAL) tmp1= &tmp; else tmp1= thd->initial_status_var; } else if (schema_table_idx == SCH_GLOBAL_STATUS) { option_type= OPT_GLOBAL; tmp1= &tmp; } else { option_type= OPT_SESSION; tmp1= &thd->status_var; } /* Avoid recursive acquisition of LOCK_status in cases when WHERE clause represented by "cond" contains subquery on I_S.SESSION/GLOBAL_STATUS. */ if (thd->fill_status_recursion_level++ == 0) mysql_mutex_lock(&LOCK_status); if (option_type == OPT_GLOBAL) calc_sum_of_all_status(&tmp); res= show_status_array(thd, wild, (SHOW_VAR *)all_status_vars.buffer, option_type, tmp1, "", tables->table, upper_case_names, cond); if (thd->fill_status_recursion_level-- == 1) mysql_mutex_unlock(&LOCK_status); DBUG_RETURN(res); } /* Fill and store records into I_S.referential_constraints table SYNOPSIS get_referential_constraints_record() thd thread handle tables table list struct(processed table) table I_S table res 1 means the error during opening of the processed table 0 means processed table is opened without error base_name db name file_name table name RETURN 0 ok # error */ static int get_referential_constraints_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { CHARSET_INFO *cs= system_charset_info; DBUG_ENTER("get_referential_constraints_record"); if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } if (!tables->view) { List<FOREIGN_KEY_INFO> f_key_list; TABLE *show_table= tables->table; show_table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME); show_table->file->get_foreign_key_list(thd, &f_key_list); FOREIGN_KEY_INFO *f_key_info; List_iterator_fast<FOREIGN_KEY_INFO> it(f_key_list); while ((f_key_info= it++)) { restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[9]->store(table_name->str, table_name->length, cs); table->field[2]->store(f_key_info->foreign_id->str, f_key_info->foreign_id->length, cs); table->field[3]->store(STRING_WITH_LEN("def"), cs); table->field[4]->store(f_key_info->referenced_db->str, f_key_info->referenced_db->length, cs); table->field[10]->store(f_key_info->referenced_table->str, f_key_info->referenced_table->length, cs); if (f_key_info->referenced_key_name) { table->field[5]->store(f_key_info->referenced_key_name->str, f_key_info->referenced_key_name->length, cs); table->field[5]->set_notnull(); } else table->field[5]->set_null(); table->field[6]->store(STRING_WITH_LEN("NONE"), cs); table->field[7]->store(f_key_info->update_method->str, f_key_info->update_method->length, cs); table->field[8]->store(f_key_info->delete_method->str, f_key_info->delete_method->length, cs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } DBUG_RETURN(0); } struct schema_table_ref { const char *table_name; ST_SCHEMA_TABLE *schema_table; }; /* Find schema_tables elment by name SYNOPSIS find_schema_table_in_plugin() thd thread handler plugin plugin table_name table name RETURN 0 table not found 1 found the schema table */ static my_bool find_schema_table_in_plugin(THD *thd, plugin_ref plugin, void* p_table) { schema_table_ref *p_schema_table= (schema_table_ref *)p_table; const char* table_name= p_schema_table->table_name; ST_SCHEMA_TABLE *schema_table= plugin_data(plugin, ST_SCHEMA_TABLE *); DBUG_ENTER("find_schema_table_in_plugin"); if (!my_strcasecmp(system_charset_info, schema_table->table_name, table_name)) { p_schema_table->schema_table= schema_table; DBUG_RETURN(1); } DBUG_RETURN(0); } /* Find schema_tables elment by name SYNOPSIS find_schema_table() thd thread handler table_name table name RETURN 0 table not found # pointer to 'schema_tables' element */ ST_SCHEMA_TABLE *find_schema_table(THD *thd, const char* table_name) { schema_table_ref schema_table_a; ST_SCHEMA_TABLE *schema_table= schema_tables; DBUG_ENTER("find_schema_table"); for (; schema_table->table_name; schema_table++) { if (!my_strcasecmp(system_charset_info, schema_table->table_name, table_name)) DBUG_RETURN(schema_table); } schema_table_a.table_name= table_name; if (plugin_foreach(thd, find_schema_table_in_plugin, MYSQL_INFORMATION_SCHEMA_PLUGIN, &schema_table_a)) DBUG_RETURN(schema_table_a.schema_table); DBUG_RETURN(NULL); } ST_SCHEMA_TABLE *get_schema_table(enum enum_schema_tables schema_table_idx) { return &schema_tables[schema_table_idx]; } /** Create information_schema table using schema_table data. @note For MYSQL_TYPE_DECIMAL fields only, the field_length member has encoded into it two numbers, based on modulus of base-10 numbers. In the ones position is the number of decimals. Tens position is unused. In the hundreds and thousands position is a two-digit decimal number representing length. Encode this value with (decimals*100)+length , where 0<decimals<10 and 0<=length<100 . @param thd thread handler @param table_list Used to pass I_S table information(fields info, tables parameters etc) and table name. @retval \# Pointer to created table @retval NULL Can't create table */ TABLE *create_schema_table(THD *thd, TABLE_LIST *table_list) { int field_count= 0; Item *item; TABLE *table; List<Item> field_list; ST_SCHEMA_TABLE *schema_table= table_list->schema_table; ST_FIELD_INFO *fields_info= schema_table->fields_info; CHARSET_INFO *cs= system_charset_info; DBUG_ENTER("create_schema_table"); for (; fields_info->field_name; fields_info++) { switch (fields_info->field_type) { case MYSQL_TYPE_TINY: case MYSQL_TYPE_LONG: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_INT24: if (!(item= new Item_return_int(fields_info->field_name, fields_info->field_length, fields_info->field_type, fields_info->value))) { DBUG_RETURN(0); } item->unsigned_flag= (fields_info->field_flags & MY_I_S_UNSIGNED); break; case MYSQL_TYPE_DATE: case MYSQL_TYPE_TIME: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: if (!(item=new Item_return_date_time(fields_info->field_name, fields_info->field_type))) { DBUG_RETURN(0); } break; case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: if ((item= new Item_float(fields_info->field_name, 0.0, NOT_FIXED_DEC, fields_info->field_length)) == NULL) DBUG_RETURN(NULL); break; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: if (!(item= new Item_decimal((longlong) fields_info->value, false))) { DBUG_RETURN(0); } item->unsigned_flag= (fields_info->field_flags & MY_I_S_UNSIGNED); item->decimals= fields_info->field_length%10; item->max_length= (fields_info->field_length/100)%100; if (item->unsigned_flag == 0) item->max_length+= 1; if (item->decimals > 0) item->max_length+= 1; item->set_name(fields_info->field_name, strlen(fields_info->field_name), cs); break; case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: if (!(item= new Item_blob(fields_info->field_name, fields_info->field_length))) { DBUG_RETURN(0); } break; default: /* Don't let unimplemented types pass through. Could be a grave error. */ DBUG_ASSERT(fields_info->field_type == MYSQL_TYPE_STRING); if (!(item= new Item_empty_string("", fields_info->field_length, cs))) { DBUG_RETURN(0); } item->set_name(fields_info->field_name, strlen(fields_info->field_name), cs); break; } field_list.push_back(item); item->maybe_null= (fields_info->field_flags & MY_I_S_MAYBE_NULL); field_count++; } TMP_TABLE_PARAM *tmp_table_param = (TMP_TABLE_PARAM*) (thd->alloc(sizeof(TMP_TABLE_PARAM))); tmp_table_param->init(); tmp_table_param->table_charset= cs; tmp_table_param->field_count= field_count; tmp_table_param->schema_table= 1; SELECT_LEX *select_lex= thd->lex->current_select; if (!(table= create_tmp_table(thd, tmp_table_param, field_list, (ORDER*) 0, 0, 0, (select_lex->options | thd->variables.option_bits | TMP_TABLE_ALL_COLUMNS), HA_POS_ERROR, table_list->alias))) DBUG_RETURN(0); my_bitmap_map* bitmaps= (my_bitmap_map*) thd->alloc(bitmap_buffer_size(field_count)); bitmap_init(&table->def_read_set, (my_bitmap_map*) bitmaps, field_count, FALSE); table->read_set= &table->def_read_set; bitmap_clear_all(table->read_set); table_list->schema_table_param= tmp_table_param; DBUG_RETURN(table); } /* For old SHOW compatibility. It is used when old SHOW doesn't have generated column names Make list of fields for SHOW SYNOPSIS make_old_format() thd thread handler schema_table pointer to 'schema_tables' element RETURN 1 error 0 success */ int make_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { ST_FIELD_INFO *field_info= schema_table->fields_info; Name_resolution_context *context= &thd->lex->select_lex.context; for (; field_info->field_name; field_info++) { if (field_info->old_name) { Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (field) { field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); if (add_item_to_list(thd, field)) return 1; } } } return 0; } int make_schemata_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { char tmp[128]; LEX *lex= thd->lex; SELECT_LEX *sel= lex->current_select; Name_resolution_context *context= &sel->context; if (!sel->item_list.elements) { ST_FIELD_INFO *field_info= &schema_table->fields_info[1]; String buffer(tmp,sizeof(tmp), system_charset_info); Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (!field || add_item_to_list(thd, field)) return 1; buffer.length(0); buffer.append(field_info->old_name); if (lex->wild && lex->wild->ptr()) { buffer.append(STRING_WITH_LEN(" (")); buffer.append(lex->wild->ptr()); buffer.append(')'); } field->set_name(buffer.ptr(), buffer.length(), system_charset_info); } return 0; } int make_table_names_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { char tmp[128]; String buffer(tmp,sizeof(tmp), thd->charset()); LEX *lex= thd->lex; Name_resolution_context *context= &lex->select_lex.context; ST_FIELD_INFO *field_info= &schema_table->fields_info[2]; buffer.length(0); buffer.append(field_info->old_name); buffer.append(lex->select_lex.db); if (lex->wild && lex->wild->ptr()) { buffer.append(STRING_WITH_LEN(" (")); buffer.append(lex->wild->ptr()); buffer.append(')'); } Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (add_item_to_list(thd, field)) return 1; field->set_name(buffer.ptr(), buffer.length(), system_charset_info); if (thd->lex->verbose) { field->set_name(buffer.ptr(), buffer.length(), system_charset_info); field_info= &schema_table->fields_info[3]; field= new Item_field(context, NullS, NullS, field_info->field_name); if (add_item_to_list(thd, field)) return 1; field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); } return 0; } int make_columns_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { int fields_arr[]= {3, 14, 13, 6, 15, 5, 16, 17, 18, -1}; int *field_num= fields_arr; ST_FIELD_INFO *field_info; Name_resolution_context *context= &thd->lex->select_lex.context; for (; *field_num >= 0; field_num++) { field_info= &schema_table->fields_info[*field_num]; if (!thd->lex->verbose && (*field_num == 13 || *field_num == 17 || *field_num == 18)) continue; Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (field) { field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); if (add_item_to_list(thd, field)) return 1; } } return 0; } int make_character_sets_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { int fields_arr[]= {0, 2, 1, 3, -1}; int *field_num= fields_arr; ST_FIELD_INFO *field_info; Name_resolution_context *context= &thd->lex->select_lex.context; for (; *field_num >= 0; field_num++) { field_info= &schema_table->fields_info[*field_num]; Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (field) { field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); if (add_item_to_list(thd, field)) return 1; } } return 0; } int make_proc_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { int fields_arr[]= {2, 3, 4, 26, 23, 22, 21, 25, 27, 28, 29, -1}; int *field_num= fields_arr; ST_FIELD_INFO *field_info; Name_resolution_context *context= &thd->lex->select_lex.context; for (; *field_num >= 0; field_num++) { field_info= &schema_table->fields_info[*field_num]; Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (field) { field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); if (add_item_to_list(thd, field)) return 1; } } return 0; } /* Create information_schema table SYNOPSIS mysql_schema_table() thd thread handler lex pointer to LEX table_list pointer to table_list RETURN 0 success 1 error */ int mysql_schema_table(THD *thd, LEX *lex, TABLE_LIST *table_list) { TABLE *table; DBUG_ENTER("mysql_schema_table"); if (!(table= table_list->schema_table->create_table(thd, table_list))) DBUG_RETURN(1); table->s->tmp_table= SYSTEM_TMP_TABLE; table->grant.privilege= SELECT_ACL; /* This test is necessary to make case insensitive file systems + upper case table names(information schema tables) + views working correctly */ if (table_list->schema_table_name) table->alias_name_used= my_strcasecmp(table_alias_charset, table_list->schema_table_name, table_list->alias); table_list->table_name= table->s->table_name.str; table_list->table_name_length= table->s->table_name.length; table_list->table= table; table->next= thd->derived_tables; thd->derived_tables= table; table_list->select_lex->options |= OPTION_SCHEMA_TABLE; lex->safe_to_cache_query= 0; if (table_list->schema_table_reformed) // show command { SELECT_LEX *sel= lex->current_select; Item *item; Field_translator *transl, *org_transl; if (table_list->field_translation) { Field_translator *end= table_list->field_translation_end; for (transl= table_list->field_translation; transl < end; transl++) { if (!transl->item->fixed && transl->item->fix_fields(thd, &transl->item)) DBUG_RETURN(1); } DBUG_RETURN(0); } List_iterator_fast<Item> it(sel->item_list); if (!(transl= (Field_translator*)(thd->stmt_arena-> alloc(sel->item_list.elements * sizeof(Field_translator))))) { DBUG_RETURN(1); } for (org_transl= transl; (item= it++); transl++) { transl->item= item; transl->name= item->name; if (!item->fixed && item->fix_fields(thd, &transl->item)) { DBUG_RETURN(1); } } table_list->field_translation= org_transl; table_list->field_translation_end= transl; } DBUG_RETURN(0); } /* Generate select from information_schema table SYNOPSIS make_schema_select() thd thread handler sel pointer to SELECT_LEX schema_table_idx index of 'schema_tables' element RETURN 0 success 1 error */ int make_schema_select(THD *thd, SELECT_LEX *sel, enum enum_schema_tables schema_table_idx) { ST_SCHEMA_TABLE *schema_table= get_schema_table(schema_table_idx); LEX_STRING db, table; DBUG_ENTER("make_schema_select"); DBUG_PRINT("enter", ("mysql_schema_select: %s", schema_table->table_name)); /* We have to make non const db_name & table_name because of lower_case_table_names */ thd->make_lex_string(&db, INFORMATION_SCHEMA_NAME.str, INFORMATION_SCHEMA_NAME.length, 0); thd->make_lex_string(&table, schema_table->table_name, strlen(schema_table->table_name), 0); if (schema_table->old_format(thd, schema_table) || /* Handle old syntax */ !sel->add_table_to_list(thd, new Table_ident(thd, db, table, 0), 0, 0, TL_READ, MDL_SHARED_READ)) { DBUG_RETURN(1); } DBUG_RETURN(0); } /** Fill INFORMATION_SCHEMA-table, leave correct Diagnostics_area / Warning_info state after itself. This function is a wrapper around ST_SCHEMA_TABLE::fill_table(), which may "partially silence" some errors. The thing is that during fill_table() many errors might be emitted. These errors stem from the nature of fill_table(). For example, SELECT ... FROM INFORMATION_SCHEMA.xxx WHERE TABLE_NAME = 'xxx' results in a number of 'Table <db name>.xxx does not exist' errors, because fill_table() tries to open the 'xxx' table in every possible database. Those errors are cleared (the error status is cleared from Diagnostics_area) inside fill_table(), but they remain in Warning_info (Warning_info is not cleared because it may contain useful warnings). This function is responsible for making sure that Warning_info does not contain warnings corresponding to the cleared errors. @note: THD::no_warnings_for_error used to be set before calling fill_table(), thus those errors didn't go to Warning_info. This is not the case now (THD::no_warnings_for_error was eliminated as a hack), so we need to take care of those warnings here. @param thd Thread context. @param table_list I_S table. @param join_table JOIN/SELECT table. @return Error status. @retval TRUE Error. @retval FALSE Success. */ static bool do_fill_table(THD *thd, TABLE_LIST *table_list, JOIN_TAB *join_table) { // NOTE: fill_table() may generate many "useless" warnings, which will be // ignored afterwards. On the other hand, there might be "useful" // warnings, which should be presented to the user. Warning_info usually // stores no more than THD::variables.max_error_count warnings. // The problem is that "useless warnings" may occupy all the slots in the // Warning_info, so "useful warnings" get rejected. In order to avoid // that problem we create a Warning_info instance, which is capable of // storing "unlimited" number of warnings. Warning_info wi(thd->query_id, true); Warning_info *wi_saved= thd->warning_info; thd->warning_info= &wi; bool res= table_list->schema_table->fill_table( thd, table_list, join_table->select_cond); thd->warning_info= wi_saved; // Pass an error if any. if (thd->stmt_da->is_error()) { thd->warning_info->push_warning(thd, thd->stmt_da->sql_errno(), thd->stmt_da->get_sqlstate(), MYSQL_ERROR::WARN_LEVEL_ERROR, thd->stmt_da->message()); } // Pass warnings (if any). // // Filter out warnings with WARN_LEVEL_ERROR level, because they // correspond to the errors which were filtered out in fill_table(). List_iterator_fast<MYSQL_ERROR> it(wi.warn_list()); MYSQL_ERROR *err; while ((err= it++)) { if (err->get_level() != MYSQL_ERROR::WARN_LEVEL_ERROR) thd->warning_info->push_warning(thd, err); } return res; } /* Fill temporary schema tables before SELECT SYNOPSIS get_schema_tables_result() join join which use schema tables executed_place place where I_S table processed RETURN FALSE success TRUE error */ bool get_schema_tables_result(JOIN *join, enum enum_schema_table_state executed_place) { JOIN_TAB *tmp_join_tab= join->join_tab+join->tables; THD *thd= join->thd; LEX *lex= thd->lex; bool result= 0; DBUG_ENTER("get_schema_tables_result"); for (JOIN_TAB *tab= join->join_tab; tab < tmp_join_tab; tab++) { if (!tab->table || !tab->table->pos_in_table_list) break; TABLE_LIST *table_list= tab->table->pos_in_table_list; if (table_list->schema_table && thd->fill_information_schema_tables()) { bool is_subselect= (&lex->unit != lex->current_select->master_unit() && lex->current_select->master_unit()->item); /* A value of 0 indicates a dummy implementation */ if (table_list->schema_table->fill_table == 0) continue; /* skip I_S optimizations specific to get_all_tables */ if (thd->lex->describe && (table_list->schema_table->fill_table != get_all_tables)) continue; /* If schema table is already processed and the statement is not a subselect then we don't need to fill this table again. If schema table is already processed and schema_table_state != executed_place then table is already processed and we should skip second data processing. */ if (table_list->schema_table_state && (!is_subselect || table_list->schema_table_state != executed_place)) continue; /* if table is used in a subselect and table has been processed earlier with the same 'executed_place' value then we should refresh the table. */ if (table_list->schema_table_state && is_subselect) { table_list->table->file->extra(HA_EXTRA_NO_CACHE); table_list->table->file->extra(HA_EXTRA_RESET_STATE); table_list->table->file->ha_delete_all_rows(); free_io_cache(table_list->table); filesort_free_buffers(table_list->table,1); table_list->table->null_row= 0; } else table_list->table->file->stats.records= 0; if (do_fill_table(thd, table_list, tab)) { result= 1; join->error= 1; tab->read_record.file= table_list->table->file; table_list->schema_table_state= executed_place; break; } tab->read_record.file= table_list->table->file; table_list->schema_table_state= executed_place; } } DBUG_RETURN(result); } struct run_hton_fill_schema_table_args { TABLE_LIST *tables; COND *cond; }; static my_bool run_hton_fill_schema_table(THD *thd, plugin_ref plugin, void *arg) { struct run_hton_fill_schema_table_args *args= (run_hton_fill_schema_table_args *) arg; handlerton *hton= plugin_data(plugin, handlerton *); if (hton->fill_is_table && hton->state == SHOW_OPTION_YES) hton->fill_is_table(hton, thd, args->tables, args->cond, get_schema_table_idx(args->tables->schema_table)); return false; } int hton_fill_schema_table(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("hton_fill_schema_table"); struct run_hton_fill_schema_table_args args; args.tables= tables; args.cond= cond; plugin_foreach(thd, run_hton_fill_schema_table, MYSQL_STORAGE_ENGINE_PLUGIN, &args); DBUG_RETURN(0); } ST_FIELD_INFO schema_fields_info[]= { {"CATALOG_NAME", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"SCHEMA_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Database", SKIP_OPEN_TABLE}, {"DEFAULT_CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"DEFAULT_COLLATION_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"SQL_PATH", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO tables_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name", SKIP_OPEN_TABLE}, {"TABLE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"ENGINE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Engine", OPEN_FRM_ONLY}, {"VERSION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Version", OPEN_FRM_ONLY}, {"ROW_FORMAT", 10, MYSQL_TYPE_STRING, 0, 1, "Row_format", OPEN_FULL_TABLE}, {"TABLE_ROWS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Rows", OPEN_FULL_TABLE}, {"AVG_ROW_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Avg_row_length", OPEN_FULL_TABLE}, {"DATA_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_length", OPEN_FULL_TABLE}, {"MAX_DATA_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Max_data_length", OPEN_FULL_TABLE}, {"INDEX_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Index_length", OPEN_FULL_TABLE}, {"DATA_FREE", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_free", OPEN_FULL_TABLE}, {"AUTO_INCREMENT", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Auto_increment", OPEN_FULL_TABLE}, {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Create_time", OPEN_FULL_TABLE}, {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Update_time", OPEN_FULL_TABLE}, {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Check_time", OPEN_FULL_TABLE}, {"TABLE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 1, "Collation", OPEN_FRM_ONLY}, {"CHECKSUM", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Checksum", OPEN_FULL_TABLE}, {"CREATE_OPTIONS", 255, MYSQL_TYPE_STRING, 0, 1, "Create_options", OPEN_FRM_ONLY}, {"TABLE_COMMENT", TABLE_COMMENT_MAXLEN, MYSQL_TYPE_STRING, 0, 0, "Comment", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO columns_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Field", OPEN_FRM_ONLY}, {"ORDINAL_POSITION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FRM_ONLY}, {"COLUMN_DEFAULT", MAX_FIELD_VARCHARLENGTH, MYSQL_TYPE_STRING, 0, 1, "Default", OPEN_FRM_ONLY}, {"IS_NULLABLE", 3, MYSQL_TYPE_STRING, 0, 0, "Null", OPEN_FRM_ONLY}, {"DATA_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"CHARACTER_MAXIMUM_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FRM_ONLY}, {"CHARACTER_OCTET_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FRM_ONLY}, {"NUMERIC_PRECISION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FRM_ONLY}, {"NUMERIC_SCALE", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FRM_ONLY}, {"CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FRM_ONLY}, {"COLLATION_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 1, "Collation", OPEN_FRM_ONLY}, {"COLUMN_TYPE", 65535, MYSQL_TYPE_STRING, 0, 0, "Type", OPEN_FRM_ONLY}, {"COLUMN_KEY", 3, MYSQL_TYPE_STRING, 0, 0, "Key", OPEN_FRM_ONLY}, {"EXTRA", 27, MYSQL_TYPE_STRING, 0, 0, "Extra", OPEN_FRM_ONLY}, {"PRIVILEGES", 80, MYSQL_TYPE_STRING, 0, 0, "Privileges", OPEN_FRM_ONLY}, {"COLUMN_COMMENT", COLUMN_COMMENT_MAXLEN, MYSQL_TYPE_STRING, 0, 0, "Comment", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO charsets_fields_info[]= { {"CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Charset", SKIP_OPEN_TABLE}, {"DEFAULT_COLLATE_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Default collation", SKIP_OPEN_TABLE}, {"DESCRIPTION", 60, MYSQL_TYPE_STRING, 0, 0, "Description", SKIP_OPEN_TABLE}, {"MAXLEN", 3, MYSQL_TYPE_LONGLONG, 0, 0, "Maxlen", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO collation_fields_info[]= { {"COLLATION_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Collation", SKIP_OPEN_TABLE}, {"CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Charset", SKIP_OPEN_TABLE}, {"ID", MY_INT32_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 0, "Id", SKIP_OPEN_TABLE}, {"IS_DEFAULT", 3, MYSQL_TYPE_STRING, 0, 0, "Default", SKIP_OPEN_TABLE}, {"IS_COMPILED", 3, MYSQL_TYPE_STRING, 0, 0, "Compiled", SKIP_OPEN_TABLE}, {"SORTLEN", 3, MYSQL_TYPE_LONGLONG, 0, 0, "Sortlen", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO engines_fields_info[]= { {"ENGINE", 64, MYSQL_TYPE_STRING, 0, 0, "Engine", SKIP_OPEN_TABLE}, {"SUPPORT", 8, MYSQL_TYPE_STRING, 0, 0, "Support", SKIP_OPEN_TABLE}, {"COMMENT", 80, MYSQL_TYPE_STRING, 0, 0, "Comment", SKIP_OPEN_TABLE}, {"TRANSACTIONS", 3, MYSQL_TYPE_STRING, 0, 1, "Transactions", SKIP_OPEN_TABLE}, {"XA", 3, MYSQL_TYPE_STRING, 0, 1, "XA", SKIP_OPEN_TABLE}, {"SAVEPOINTS", 3 ,MYSQL_TYPE_STRING, 0, 1, "Savepoints", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO events_fields_info[]= { {"EVENT_CATALOG", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"EVENT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Db", SKIP_OPEN_TABLE}, {"EVENT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name", SKIP_OPEN_TABLE}, {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer", SKIP_OPEN_TABLE}, {"TIME_ZONE", 64, MYSQL_TYPE_STRING, 0, 0, "Time zone", SKIP_OPEN_TABLE}, {"EVENT_BODY", 8, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"EVENT_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"EVENT_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, "Type", SKIP_OPEN_TABLE}, {"EXECUTE_AT", 0, MYSQL_TYPE_DATETIME, 0, 1, "Execute at", SKIP_OPEN_TABLE}, {"INTERVAL_VALUE", 256, MYSQL_TYPE_STRING, 0, 1, "Interval value", SKIP_OPEN_TABLE}, {"INTERVAL_FIELD", 18, MYSQL_TYPE_STRING, 0, 1, "Interval field", SKIP_OPEN_TABLE}, {"SQL_MODE", 32*256, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"STARTS", 0, MYSQL_TYPE_DATETIME, 0, 1, "Starts", SKIP_OPEN_TABLE}, {"ENDS", 0, MYSQL_TYPE_DATETIME, 0, 1, "Ends", SKIP_OPEN_TABLE}, {"STATUS", 18, MYSQL_TYPE_STRING, 0, 0, "Status", SKIP_OPEN_TABLE}, {"ON_COMPLETION", 12, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 0, 0, SKIP_OPEN_TABLE}, {"LAST_ALTERED", 0, MYSQL_TYPE_DATETIME, 0, 0, 0, SKIP_OPEN_TABLE}, {"LAST_EXECUTED", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, SKIP_OPEN_TABLE}, {"EVENT_COMMENT", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ORIGINATOR", 10, MYSQL_TYPE_LONGLONG, 0, 0, "Originator", SKIP_OPEN_TABLE}, {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "character_set_client", SKIP_OPEN_TABLE}, {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "collation_connection", SKIP_OPEN_TABLE}, {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Database Collation", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO coll_charset_app_fields_info[]= { {"COLLATION_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO proc_fields_info[]= { {"SPECIFIC_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ROUTINE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ROUTINE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Db", SKIP_OPEN_TABLE}, {"ROUTINE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name", SKIP_OPEN_TABLE}, {"ROUTINE_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, "Type", SKIP_OPEN_TABLE}, {"DATA_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"CHARACTER_MAXIMUM_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"CHARACTER_OCTET_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"NUMERIC_PRECISION", 21 , MYSQL_TYPE_LONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"NUMERIC_SCALE", 21 , MYSQL_TYPE_LONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"DTD_IDENTIFIER", 65535, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"ROUTINE_BODY", 8, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ROUTINE_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"EXTERNAL_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"EXTERNAL_LANGUAGE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"PARAMETER_STYLE", 8, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_DETERMINISTIC", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"SQL_DATA_ACCESS", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"SQL_PATH", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"SECURITY_TYPE", 7, MYSQL_TYPE_STRING, 0, 0, "Security_type", SKIP_OPEN_TABLE}, {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 0, "Created", SKIP_OPEN_TABLE}, {"LAST_ALTERED", 0, MYSQL_TYPE_DATETIME, 0, 0, "Modified", SKIP_OPEN_TABLE}, {"SQL_MODE", 32*256, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ROUTINE_COMMENT", 65535, MYSQL_TYPE_STRING, 0, 0, "Comment", SKIP_OPEN_TABLE}, {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer", SKIP_OPEN_TABLE}, {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "character_set_client", SKIP_OPEN_TABLE}, {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "collation_connection", SKIP_OPEN_TABLE}, {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Database Collation", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO stat_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table", OPEN_FRM_ONLY}, {"NON_UNIQUE", 1, MYSQL_TYPE_LONGLONG, 0, 0, "Non_unique", OPEN_FRM_ONLY}, {"INDEX_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"INDEX_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Key_name", OPEN_FRM_ONLY}, {"SEQ_IN_INDEX", 2, MYSQL_TYPE_LONGLONG, 0, 0, "Seq_in_index", OPEN_FRM_ONLY}, {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Column_name", OPEN_FRM_ONLY}, {"COLLATION", 1, MYSQL_TYPE_STRING, 0, 1, "Collation", OPEN_FRM_ONLY}, {"CARDINALITY", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 1, "Cardinality", OPEN_FULL_TABLE}, {"SUB_PART", 3, MYSQL_TYPE_LONGLONG, 0, 1, "Sub_part", OPEN_FRM_ONLY}, {"PACKED", 10, MYSQL_TYPE_STRING, 0, 1, "Packed", OPEN_FRM_ONLY}, {"NULLABLE", 3, MYSQL_TYPE_STRING, 0, 0, "Null", OPEN_FRM_ONLY}, {"INDEX_TYPE", 16, MYSQL_TYPE_STRING, 0, 0, "Index_type", OPEN_FULL_TABLE}, {"COMMENT", 16, MYSQL_TYPE_STRING, 0, 1, "Comment", OPEN_FRM_ONLY}, {"INDEX_COMMENT", INDEX_COMMENT_MAXLEN, MYSQL_TYPE_STRING, 0, 0, "Index_comment", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO view_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"VIEW_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"CHECK_OPTION", 8, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"IS_UPDATABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"SECURITY_TYPE", 7, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO user_privileges_fields_info[]= { {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO schema_privileges_fields_info[]= { {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO table_privileges_fields_info[]= { {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO column_privileges_fields_info[]= { {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO table_constraints_fields_info[]= { {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO key_column_usage_fields_info[]= { {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"ORDINAL_POSITION", 10 ,MYSQL_TYPE_LONGLONG, 0, 0, 0, OPEN_FULL_TABLE}, {"POSITION_IN_UNIQUE_CONSTRAINT", 10 ,MYSQL_TYPE_LONGLONG, 0, 1, 0, OPEN_FULL_TABLE}, {"REFERENCED_TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"REFERENCED_TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"REFERENCED_COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO table_names_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Tables_in_", SKIP_OPEN_TABLE}, {"TABLE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table_type", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO open_tables_fields_info[]= { {"Database", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Database", SKIP_OPEN_TABLE}, {"Table",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table", SKIP_OPEN_TABLE}, {"In_use", 1, MYSQL_TYPE_LONGLONG, 0, 0, "In_use", SKIP_OPEN_TABLE}, {"Name_locked", 4, MYSQL_TYPE_LONGLONG, 0, 0, "Name_locked", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO triggers_fields_info[]= { {"TRIGGER_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TRIGGER_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TRIGGER_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Trigger", OPEN_FRM_ONLY}, {"EVENT_MANIPULATION", 6, MYSQL_TYPE_STRING, 0, 0, "Event", OPEN_FRM_ONLY}, {"EVENT_OBJECT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"EVENT_OBJECT_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"EVENT_OBJECT_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table", OPEN_FRM_ONLY}, {"ACTION_ORDER", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0, OPEN_FRM_ONLY}, {"ACTION_CONDITION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FRM_ONLY}, {"ACTION_STATEMENT", 65535, MYSQL_TYPE_STRING, 0, 0, "Statement", OPEN_FRM_ONLY}, {"ACTION_ORIENTATION", 9, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"ACTION_TIMING", 6, MYSQL_TYPE_STRING, 0, 0, "Timing", OPEN_FRM_ONLY}, {"ACTION_REFERENCE_OLD_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FRM_ONLY}, {"ACTION_REFERENCE_NEW_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FRM_ONLY}, {"ACTION_REFERENCE_OLD_ROW", 3, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"ACTION_REFERENCE_NEW_ROW", 3, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 1, "Created", OPEN_FRM_ONLY}, {"SQL_MODE", 32*256, MYSQL_TYPE_STRING, 0, 0, "sql_mode", OPEN_FRM_ONLY}, {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer", OPEN_FRM_ONLY}, {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "character_set_client", OPEN_FRM_ONLY}, {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "collation_connection", OPEN_FRM_ONLY}, {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Database Collation", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO partitions_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"PARTITION_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"SUBPARTITION_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"PARTITION_ORDINAL_POSITION", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FULL_TABLE}, {"SUBPARTITION_ORDINAL_POSITION", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FULL_TABLE}, {"PARTITION_METHOD", 18, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"SUBPARTITION_METHOD", 12, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"PARTITION_EXPRESSION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"SUBPARTITION_EXPRESSION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"PARTITION_DESCRIPTION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"TABLE_ROWS", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"AVG_ROW_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"MAX_DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FULL_TABLE}, {"INDEX_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"DATA_FREE", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, OPEN_FULL_TABLE}, {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, OPEN_FULL_TABLE}, {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, OPEN_FULL_TABLE}, {"CHECKSUM", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FULL_TABLE}, {"PARTITION_COMMENT", 80, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"NODEGROUP", 12 , MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLESPACE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO variables_fields_info[]= { {"VARIABLE_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Variable_name", SKIP_OPEN_TABLE}, {"VARIABLE_VALUE", 1024, MYSQL_TYPE_STRING, 0, 1, "Value", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO processlist_fields_info[]= { {"ID", 4, MYSQL_TYPE_LONGLONG, 0, 0, "Id", SKIP_OPEN_TABLE}, {"USER", 16, MYSQL_TYPE_STRING, 0, 0, "User", SKIP_OPEN_TABLE}, {"HOST", LIST_PROCESS_HOST_LEN, MYSQL_TYPE_STRING, 0, 0, "Host", SKIP_OPEN_TABLE}, {"DB", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Db", SKIP_OPEN_TABLE}, {"COMMAND", 16, MYSQL_TYPE_STRING, 0, 0, "Command", SKIP_OPEN_TABLE}, {"TIME", 7, MYSQL_TYPE_LONG, 0, 0, "Time", SKIP_OPEN_TABLE}, {"STATE", 64, MYSQL_TYPE_STRING, 0, 1, "State", SKIP_OPEN_TABLE}, {"INFO", PROCESS_LIST_INFO_WIDTH, MYSQL_TYPE_STRING, 0, 1, "Info", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO plugin_fields_info[]= { {"PLUGIN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name", SKIP_OPEN_TABLE}, {"PLUGIN_VERSION", 20, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PLUGIN_STATUS", 10, MYSQL_TYPE_STRING, 0, 0, "Status", SKIP_OPEN_TABLE}, {"PLUGIN_TYPE", 80, MYSQL_TYPE_STRING, 0, 0, "Type", SKIP_OPEN_TABLE}, {"PLUGIN_TYPE_VERSION", 20, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PLUGIN_LIBRARY", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Library", SKIP_OPEN_TABLE}, {"PLUGIN_LIBRARY_VERSION", 20, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"PLUGIN_AUTHOR", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"PLUGIN_DESCRIPTION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"PLUGIN_LICENSE", 80, MYSQL_TYPE_STRING, 0, 1, "License", SKIP_OPEN_TABLE}, {"LOAD_OPTION", 64, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO files_fields_info[]= { {"FILE_ID", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0, SKIP_OPEN_TABLE}, {"FILE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"FILE_TYPE", 20, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLESPACE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"LOGFILE_GROUP_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"LOGFILE_GROUP_NUMBER", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"ENGINE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"FULLTEXT_KEYS", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"DELETED_ROWS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"UPDATE_COUNT", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"FREE_EXTENTS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"TOTAL_EXTENTS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"EXTENT_SIZE", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0, SKIP_OPEN_TABLE}, {"INITIAL_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, SKIP_OPEN_TABLE}, {"MAXIMUM_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, SKIP_OPEN_TABLE}, {"AUTOEXTEND_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, SKIP_OPEN_TABLE}, {"CREATION_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, SKIP_OPEN_TABLE}, {"LAST_UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, SKIP_OPEN_TABLE}, {"LAST_ACCESS_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, SKIP_OPEN_TABLE}, {"RECOVER_TIME", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"TRANSACTION_COUNTER", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"VERSION", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Version", SKIP_OPEN_TABLE}, {"ROW_FORMAT", 10, MYSQL_TYPE_STRING, 0, 1, "Row_format", SKIP_OPEN_TABLE}, {"TABLE_ROWS", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Rows", SKIP_OPEN_TABLE}, {"AVG_ROW_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Avg_row_length", SKIP_OPEN_TABLE}, {"DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_length", SKIP_OPEN_TABLE}, {"MAX_DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Max_data_length", SKIP_OPEN_TABLE}, {"INDEX_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Index_length", SKIP_OPEN_TABLE}, {"DATA_FREE", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_free", SKIP_OPEN_TABLE}, {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Create_time", SKIP_OPEN_TABLE}, {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Update_time", SKIP_OPEN_TABLE}, {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Check_time", SKIP_OPEN_TABLE}, {"CHECKSUM", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Checksum", SKIP_OPEN_TABLE}, {"STATUS", 20, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"EXTRA", 255, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; void init_fill_schema_files_row(TABLE* table) { int i; for(i=0; files_fields_info[i].field_name!=NULL; i++) table->field[i]->set_null(); table->field[IS_FILES_STATUS]->set_notnull(); table->field[IS_FILES_STATUS]->store("NORMAL", 6, system_charset_info); } ST_FIELD_INFO referential_constraints_fields_info[]= { {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"UNIQUE_CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"UNIQUE_CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"UNIQUE_CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, MY_I_S_MAYBE_NULL, 0, OPEN_FULL_TABLE}, {"MATCH_OPTION", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"UPDATE_RULE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"DELETE_RULE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"REFERENCED_TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO parameters_fields_info[]= { {"SPECIFIC_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"SPECIFIC_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"SPECIFIC_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"ORDINAL_POSITION", 21 , MYSQL_TYPE_LONG, 0, 0, 0, OPEN_FULL_TABLE}, {"PARAMETER_MODE", 5, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"PARAMETER_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"DATA_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CHARACTER_MAXIMUM_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0, OPEN_FULL_TABLE}, {"CHARACTER_OCTET_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0, OPEN_FULL_TABLE}, {"NUMERIC_PRECISION", 21 , MYSQL_TYPE_LONG, 0, 1, 0, OPEN_FULL_TABLE}, {"NUMERIC_SCALE", 21 , MYSQL_TYPE_LONG, 0, 1, 0, OPEN_FULL_TABLE}, {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"DTD_IDENTIFIER", 65535, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"ROUTINE_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE} }; ST_FIELD_INFO tablespaces_fields_info[]= { {"TABLESPACE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ENGINE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLESPACE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, MY_I_S_MAYBE_NULL, 0, SKIP_OPEN_TABLE}, {"LOGFILE_GROUP_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, MY_I_S_MAYBE_NULL, 0, SKIP_OPEN_TABLE}, {"EXTENT_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED, 0, SKIP_OPEN_TABLE}, {"AUTOEXTEND_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED, 0, SKIP_OPEN_TABLE}, {"MAXIMUM_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED, 0, SKIP_OPEN_TABLE}, {"NODEGROUP_ID", 21, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED, 0, SKIP_OPEN_TABLE}, {"TABLESPACE_COMMENT", 2048, MYSQL_TYPE_STRING, 0, MY_I_S_MAYBE_NULL, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; /* Description of ST_FIELD_INFO in table.h Make sure that the order of schema_tables and enum_schema_tables are the same. */ ST_SCHEMA_TABLE schema_tables[]= { {"CHARACTER_SETS", charsets_fields_info, create_schema_table, fill_schema_charsets, make_character_sets_old_format, 0, -1, -1, 0, 0}, {"COLLATIONS", collation_fields_info, create_schema_table, fill_schema_collation, make_old_format, 0, -1, -1, 0, 0}, {"COLLATION_CHARACTER_SET_APPLICABILITY", coll_charset_app_fields_info, create_schema_table, fill_schema_coll_charset_app, 0, 0, -1, -1, 0, 0}, {"COLUMNS", columns_fields_info, create_schema_table, get_all_tables, make_columns_old_format, get_schema_column_record, 1, 2, 0, OPTIMIZE_I_S_TABLE|OPEN_VIEW_FULL}, {"COLUMN_PRIVILEGES", column_privileges_fields_info, create_schema_table, fill_schema_column_privileges, 0, 0, -1, -1, 0, 0}, {"ENGINES", engines_fields_info, create_schema_table, fill_schema_engines, make_old_format, 0, -1, -1, 0, 0}, #ifdef HAVE_EVENT_SCHEDULER {"EVENTS", events_fields_info, create_schema_table, Events::fill_schema_events, make_old_format, 0, -1, -1, 0, 0}, #else {"EVENTS", events_fields_info, create_schema_table, 0, make_old_format, 0, -1, -1, 0, 0}, #endif {"FILES", files_fields_info, create_schema_table, hton_fill_schema_table, 0, 0, -1, -1, 0, 0}, {"GLOBAL_STATUS", variables_fields_info, create_schema_table, fill_status, make_old_format, 0, 0, -1, 0, 0}, {"GLOBAL_VARIABLES", variables_fields_info, create_schema_table, fill_variables, make_old_format, 0, 0, -1, 0, 0}, {"KEY_COLUMN_USAGE", key_column_usage_fields_info, create_schema_table, get_all_tables, 0, get_schema_key_column_usage_record, 4, 5, 0, OPTIMIZE_I_S_TABLE|OPEN_TABLE_ONLY}, {"OPEN_TABLES", open_tables_fields_info, create_schema_table, fill_open_tables, make_old_format, 0, -1, -1, 1, 0}, {"PARAMETERS", parameters_fields_info, create_schema_table, fill_schema_proc, 0, 0, -1, -1, 0, 0}, {"PARTITIONS", partitions_fields_info, create_schema_table, get_all_tables, 0, get_schema_partitions_record, 1, 2, 0, OPTIMIZE_I_S_TABLE|OPEN_TABLE_ONLY}, {"PLUGINS", plugin_fields_info, create_schema_table, fill_plugins, make_old_format, 0, -1, -1, 0, 0}, {"PROCESSLIST", processlist_fields_info, create_schema_table, fill_schema_processlist, make_old_format, 0, -1, -1, 0, 0}, {"PROFILING", query_profile_statistics_info, create_schema_table, fill_query_profile_statistics_info, make_profile_table_for_show, NULL, -1, -1, false, 0}, {"REFERENTIAL_CONSTRAINTS", referential_constraints_fields_info, create_schema_table, get_all_tables, 0, get_referential_constraints_record, 1, 9, 0, OPTIMIZE_I_S_TABLE|OPEN_TABLE_ONLY}, {"ROUTINES", proc_fields_info, create_schema_table, fill_schema_proc, make_proc_old_format, 0, -1, -1, 0, 0}, {"SCHEMATA", schema_fields_info, create_schema_table, fill_schema_schemata, make_schemata_old_format, 0, 1, -1, 0, 0}, {"SCHEMA_PRIVILEGES", schema_privileges_fields_info, create_schema_table, fill_schema_schema_privileges, 0, 0, -1, -1, 0, 0}, {"SESSION_STATUS", variables_fields_info, create_schema_table, fill_status, make_old_format, 0, 0, -1, 0, 0}, {"SESSION_VARIABLES", variables_fields_info, create_schema_table, fill_variables, make_old_format, 0, 0, -1, 0, 0}, {"STATISTICS", stat_fields_info, create_schema_table, get_all_tables, make_old_format, get_schema_stat_record, 1, 2, 0, OPEN_TABLE_ONLY|OPTIMIZE_I_S_TABLE}, {"STATUS", variables_fields_info, create_schema_table, fill_status, make_old_format, 0, 0, -1, 1, 0}, {"TABLES", tables_fields_info, create_schema_table, get_all_tables, make_old_format, get_schema_tables_record, 1, 2, 0, OPTIMIZE_I_S_TABLE}, {"TABLESPACES", tablespaces_fields_info, create_schema_table, hton_fill_schema_table, 0, 0, -1, -1, 0, 0}, {"TABLE_CONSTRAINTS", table_constraints_fields_info, create_schema_table, get_all_tables, 0, get_schema_constraints_record, 3, 4, 0, OPTIMIZE_I_S_TABLE|OPEN_TABLE_ONLY}, {"TABLE_NAMES", table_names_fields_info, create_schema_table, get_all_tables, make_table_names_old_format, 0, 1, 2, 1, 0}, {"TABLE_PRIVILEGES", table_privileges_fields_info, create_schema_table, fill_schema_table_privileges, 0, 0, -1, -1, 0, 0}, {"TRIGGERS", triggers_fields_info, create_schema_table, get_all_tables, make_old_format, get_schema_triggers_record, 5, 6, 0, OPEN_TRIGGER_ONLY|OPTIMIZE_I_S_TABLE}, {"USER_PRIVILEGES", user_privileges_fields_info, create_schema_table, fill_schema_user_privileges, 0, 0, -1, -1, 0, 0}, {"VARIABLES", variables_fields_info, create_schema_table, fill_variables, make_old_format, 0, 0, -1, 1, 0}, {"VIEWS", view_fields_info, create_schema_table, get_all_tables, 0, get_schema_views_record, 1, 2, 0, OPEN_VIEW_ONLY|OPTIMIZE_I_S_TABLE}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; #ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION template class List_iterator_fast<char>; template class List<char>; #endif int initialize_schema_table(st_plugin_int *plugin) { ST_SCHEMA_TABLE *schema_table; DBUG_ENTER("initialize_schema_table"); if (!(schema_table= (ST_SCHEMA_TABLE *)my_malloc(sizeof(ST_SCHEMA_TABLE), MYF(MY_WME | MY_ZEROFILL)))) DBUG_RETURN(1); /* Historical Requirement */ plugin->data= schema_table; // shortcut for the future if (plugin->plugin->init) { schema_table->create_table= create_schema_table; schema_table->old_format= make_old_format; schema_table->idx_field1= -1, schema_table->idx_field2= -1; /* Make the name available to the init() function. */ schema_table->table_name= plugin->name.str; if (plugin->plugin->init(schema_table)) { sql_print_error("Plugin '%s' init function returned error.", plugin->name.str); plugin->data= NULL; my_free(schema_table); DBUG_RETURN(1); } /* Make sure the plugin name is not set inside the init() function. */ schema_table->table_name= plugin->name.str; } DBUG_RETURN(0); } int finalize_schema_table(st_plugin_int *plugin) { ST_SCHEMA_TABLE *schema_table= (ST_SCHEMA_TABLE *)plugin->data; DBUG_ENTER("finalize_schema_table"); if (schema_table) { if (plugin->plugin->deinit) { DBUG_PRINT("info", ("Deinitializing plugin: '%s'", plugin->name.str)); if (plugin->plugin->deinit(NULL)) { DBUG_PRINT("warning", ("Plugin '%s' deinit function returned error.", plugin->name.str)); } } my_free(schema_table); } DBUG_RETURN(0); } /** Output trigger information (SHOW CREATE TRIGGER) to the client. @param thd Thread context. @param triggers List of triggers for the table. @param trigger_idx Index of the trigger to dump. @return Operation status @retval TRUE Error. @retval FALSE Success. */ static bool show_create_trigger_impl(THD *thd, Table_triggers_list *triggers, int trigger_idx) { int ret_code; Protocol *p= thd->protocol; List<Item> fields; LEX_STRING trg_name; ulonglong trg_sql_mode; LEX_STRING trg_sql_mode_str; LEX_STRING trg_sql_original_stmt; LEX_STRING trg_client_cs_name; LEX_STRING trg_connection_cl_name; LEX_STRING trg_db_cl_name; CHARSET_INFO *trg_client_cs; /* TODO: Check privileges here. This functionality will be added by implementation of the following WL items: - WL#2227: New privileges for new objects - WL#3482: Protect SHOW CREATE PROCEDURE | FUNCTION | VIEW | TRIGGER properly SHOW TRIGGERS and I_S.TRIGGERS will be affected too. */ /* Prepare trigger "object". */ triggers->get_trigger_info(thd, trigger_idx, &trg_name, &trg_sql_mode, &trg_sql_original_stmt, &trg_client_cs_name, &trg_connection_cl_name, &trg_db_cl_name); sql_mode_string_representation(thd, trg_sql_mode, &trg_sql_mode_str); /* Resolve trigger client character set. */ if (resolve_charset(trg_client_cs_name.str, NULL, &trg_client_cs)) return TRUE; /* Send header. */ fields.push_back(new Item_empty_string("Trigger", NAME_LEN)); fields.push_back(new Item_empty_string("sql_mode", trg_sql_mode_str.length)); { /* NOTE: SQL statement field must be not less than 1024 in order not to confuse old clients. */ Item_empty_string *stmt_fld= new Item_empty_string("SQL Original Statement", max(trg_sql_original_stmt.length, 1024)); stmt_fld->maybe_null= TRUE; fields.push_back(stmt_fld); } fields.push_back(new Item_empty_string("character_set_client", MY_CS_NAME_SIZE)); fields.push_back(new Item_empty_string("collation_connection", MY_CS_NAME_SIZE)); fields.push_back(new Item_empty_string("Database Collation", MY_CS_NAME_SIZE)); if (p->send_result_set_metadata(&fields, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) return TRUE; /* Send data. */ p->prepare_for_resend(); p->store(trg_name.str, trg_name.length, system_charset_info); p->store(trg_sql_mode_str.str, trg_sql_mode_str.length, system_charset_info); p->store(trg_sql_original_stmt.str, trg_sql_original_stmt.length, trg_client_cs); p->store(trg_client_cs_name.str, trg_client_cs_name.length, system_charset_info); p->store(trg_connection_cl_name.str, trg_connection_cl_name.length, system_charset_info); p->store(trg_db_cl_name.str, trg_db_cl_name.length, system_charset_info); ret_code= p->write(); if (!ret_code) my_eof(thd); return ret_code != 0; } /** Read TRN and TRG files to obtain base table name for the specified trigger name and construct TABE_LIST object for the base table. @param thd Thread context. @param trg_name Trigger name. @return TABLE_LIST object corresponding to the base table. TODO: This function is a copy&paste from add_table_to_list() and sp_add_to_query_tables(). The problem is that in order to be compatible with Stored Programs (Prepared Statements), we should not touch thd->lex. The "source" functions also add created TABLE_LIST object to the thd->lex->query_tables. The plan to eliminate this copy&paste is to: - get rid of sp_add_to_query_tables() and use Lex::add_table_to_list(). Only add_table_to_list() must be used to add tables from the parser into Lex::query_tables list. - do not update Lex::query_tables in add_table_to_list(). */ static TABLE_LIST *get_trigger_table(THD *thd, const sp_name *trg_name) { char trn_path_buff[FN_REFLEN]; LEX_STRING trn_path= { trn_path_buff, 0 }; LEX_STRING db; LEX_STRING tbl_name; TABLE_LIST *table; build_trn_path(thd, trg_name, &trn_path); if (check_trn_exists(&trn_path)) { my_error(ER_TRG_DOES_NOT_EXIST, MYF(0)); return NULL; } if (load_table_name_for_trigger(thd, trg_name, &trn_path, &tbl_name)) return NULL; /* We need to reset statement table list to be PS/SP friendly. */ if (!(table= (TABLE_LIST*) thd->alloc(sizeof(TABLE_LIST)))) return NULL; db= trg_name->m_db; db.str= thd->strmake(db.str, db.length); tbl_name.str= thd->strmake(tbl_name.str, tbl_name.length); if (db.str == NULL || tbl_name.str == NULL) return NULL; table->init_one_table(db.str, db.length, tbl_name.str, tbl_name.length, tbl_name.str, TL_IGNORE); return table; } /** SHOW CREATE TRIGGER high-level implementation. @param thd Thread context. @param trg_name Trigger name. @return Operation status @retval TRUE Error. @retval FALSE Success. */ bool show_create_trigger(THD *thd, const sp_name *trg_name) { TABLE_LIST *lst= get_trigger_table(thd, trg_name); uint num_tables; /* NOTE: unused, only to pass to open_tables(). */ Table_triggers_list *triggers; int trigger_idx; bool error= TRUE; if (!lst) return TRUE; if (check_table_access(thd, TRIGGER_ACL, lst, FALSE, 1, TRUE)) { my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "TRIGGER"); return TRUE; } /* Metadata locks taken during SHOW CREATE TRIGGER should be released when the statement completes as it is an information statement. */ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint(); /* Open the table by name in order to load Table_triggers_list object. */ if (open_tables(thd, &lst, &num_tables, MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL)) { my_error(ER_TRG_CANT_OPEN_TABLE, MYF(0), (const char *) trg_name->m_db.str, (const char *) lst->table_name); goto exit; /* Perform closing actions and return error status. */ } triggers= lst->table->triggers; if (!triggers) { my_error(ER_TRG_DOES_NOT_EXIST, MYF(0)); goto exit; } trigger_idx= triggers->find_trigger_by_name(&trg_name->m_name); if (trigger_idx < 0) { my_error(ER_TRG_CORRUPTED_FILE, MYF(0), (const char *) trg_name->m_db.str, (const char *) lst->table_name); goto exit; } error= show_create_trigger_impl(thd, triggers, trigger_idx); /* NOTE: if show_create_trigger_impl() failed, that means we could not send data to the client. In this case we simply raise the error status and client connection will be closed. */ exit: close_thread_tables(thd); /* Release any metadata locks taken during SHOW CREATE TRIGGER. */ thd->mdl_context.rollback_to_savepoint(mdl_savepoint); return error; } class IS_internal_schema_access : public ACL_internal_schema_access { public: IS_internal_schema_access() {} ~IS_internal_schema_access() {} ACL_internal_access_result check(ulong want_access, ulong *save_priv) const; const ACL_internal_table_access *lookup(const char *name) const; }; ACL_internal_access_result IS_internal_schema_access::check(ulong want_access, ulong *save_priv) const { want_access &= ~SELECT_ACL; /* We don't allow any simple privileges but SELECT_ACL on the information_schema database. */ if (unlikely(want_access & DB_ACLS)) return ACL_INTERNAL_ACCESS_DENIED; /* Always grant SELECT for the information schema. */ *save_priv|= SELECT_ACL; return want_access ? ACL_INTERNAL_ACCESS_CHECK_GRANT : ACL_INTERNAL_ACCESS_GRANTED; } const ACL_internal_table_access * IS_internal_schema_access::lookup(const char *name) const { /* There are no per table rules for the information schema. */ return NULL; } static IS_internal_schema_access is_internal_schema_access; void initialize_information_schema_acl() { ACL_internal_schema_registry::register_schema(&INFORMATION_SCHEMA_NAME, &is_internal_schema_access); } #ifdef WITH_PARTITION_STORAGE_ENGINE /* Convert a string in character set in column character set format to utf8 character set if possible, the utf8 character set string will later possibly be converted to character set used by client. Thus we attempt conversion from column character set to both utf8 and to character set client. Examples of strings that should fail conversion to utf8 are unassigned characters as e.g. 0x81 in cp1250 (Windows character set for for countries like Czech and Poland). Example of string that should fail conversion to character set on client (e.g. if this is latin1) is 0x2020 (daggger) in ucs2. If the conversion fails we will as a fall back convert the string to hex encoded format. The caller of the function can also ask for hex encoded format of output string unconditionally. SYNOPSIS get_cs_converted_string_value() thd Thread object input_str Input string in cs character set output_str Output string to be produced in utf8 cs Character set of input string use_hex Use hex string unconditionally RETURN VALUES No return value */ static void get_cs_converted_string_value(THD *thd, String *input_str, String *output_str, CHARSET_INFO *cs, bool use_hex) { output_str->length(0); if (input_str->length() == 0) { output_str->append("''"); return; } if (!use_hex) { String try_val; uint try_conv_error= 0; try_val.copy(input_str->ptr(), input_str->length(), cs, thd->variables.character_set_client, &try_conv_error); if (!try_conv_error) { String val; uint conv_error= 0; val.copy(input_str->ptr(), input_str->length(), cs, system_charset_info, &conv_error); if (!conv_error) { append_unescaped(output_str, val.ptr(), val.length()); return; } } /* We had a conversion error, use hex encoded string for safety */ } { const uchar *ptr; uint i, len; char buf[3]; output_str->append("_"); output_str->append(cs->csname); output_str->append(" "); output_str->append("0x"); len= input_str->length(); ptr= (uchar*)input_str->ptr(); for (i= 0; i < len; i++) { uint high, low; high= (*ptr) >> 4; low= (*ptr) & 0x0F; buf[0]= _dig_vec_upper[high]; buf[1]= _dig_vec_upper[low]; buf[2]= 0; output_str->append((const char*)buf); ptr++; } } return; } #endif Bug#18319790 QUERY TO INFORMATION_SCHEMA CRASHES SERVER Before this fix, specially crafted queries using the INFORMATION_SCHEMA could crash the server. The root cause was a buffer overflow, see the (private) bug comments for details. With this fix, the buffer overflow condition is properly handled, and the queries involved do return the expected result. /* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Function with list databases, tables or fields */ #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */ #include "sql_priv.h" #include "unireg.h" #include "sql_acl.h" // fill_schema_*_privileges #include "sql_select.h" // For select_describe #include "sql_base.h" // close_tables_for_reopen #include "sql_show.h" #include "sql_table.h" // filename_to_tablename, // primary_key_name, // build_table_filename #include "repl_failsafe.h" #include "sql_parse.h" // check_access, check_table_access #include "sql_partition.h" // partition_element #include "sql_derived.h" // mysql_derived_prepare, // mysql_handle_derived, #include "sql_db.h" // check_db_dir_existence, load_db_opt_by_name #include "sql_time.h" // interval_type_to_name #include "tztime.h" // struct Time_zone #include "sql_acl.h" // TABLE_ACLS, check_grant, DB_ACLS, acl_get, // check_grant_db #include "filesort.h" // filesort_free_buffers #include "sp.h" #include "sp_head.h" #include "sp_pcontext.h" #include "set_var.h" #include "sql_trigger.h" #include "authors.h" #include "contributors.h" #include "sql_partition.h" #ifdef HAVE_EVENT_SCHEDULER #include "events.h" #include "event_data_objects.h" #endif #include <my_dir.h> #include "lock.h" // MYSQL_OPEN_IGNORE_FLUSH #include "debug_sync.h" #include "datadict.h" // dd_frm_type() #define STR_OR_NIL(S) ((S) ? (S) : "<nil>") #ifdef WITH_PARTITION_STORAGE_ENGINE #include "ha_partition.h" #endif enum enum_i_s_events_fields { ISE_EVENT_CATALOG= 0, ISE_EVENT_SCHEMA, ISE_EVENT_NAME, ISE_DEFINER, ISE_TIME_ZONE, ISE_EVENT_BODY, ISE_EVENT_DEFINITION, ISE_EVENT_TYPE, ISE_EXECUTE_AT, ISE_INTERVAL_VALUE, ISE_INTERVAL_FIELD, ISE_SQL_MODE, ISE_STARTS, ISE_ENDS, ISE_STATUS, ISE_ON_COMPLETION, ISE_CREATED, ISE_LAST_ALTERED, ISE_LAST_EXECUTED, ISE_EVENT_COMMENT, ISE_ORIGINATOR, ISE_CLIENT_CS, ISE_CONNECTION_CL, ISE_DB_CL }; #ifndef NO_EMBEDDED_ACCESS_CHECKS static const char *grant_names[]={ "select","insert","update","delete","create","drop","reload","shutdown", "process","file","grant","references","index","alter"}; static TYPELIB grant_types = { sizeof(grant_names)/sizeof(char **), "grant_types", grant_names, NULL}; #endif static void store_key_options(THD *thd, String *packet, TABLE *table, KEY *key_info); #ifdef WITH_PARTITION_STORAGE_ENGINE static void get_cs_converted_string_value(THD *thd, String *input_str, String *output_str, CHARSET_INFO *cs, bool use_hex); #endif static void append_algorithm(TABLE_LIST *table, String *buff); static COND * make_cond_for_info_schema(COND *cond, TABLE_LIST *table); /*************************************************************************** ** List all table types supported ***************************************************************************/ static int make_version_string(char *buf, int buf_length, uint version) { return my_snprintf(buf, buf_length, "%d.%d", version>>8,version&0xff); } static my_bool show_plugins(THD *thd, plugin_ref plugin, void *arg) { TABLE *table= (TABLE*) arg; struct st_mysql_plugin *plug= plugin_decl(plugin); struct st_plugin_dl *plugin_dl= plugin_dlib(plugin); CHARSET_INFO *cs= system_charset_info; char version_buf[20]; restore_record(table, s->default_values); table->field[0]->store(plugin_name(plugin)->str, plugin_name(plugin)->length, cs); table->field[1]->store(version_buf, make_version_string(version_buf, sizeof(version_buf), plug->version), cs); switch (plugin_state(plugin)) { /* case PLUGIN_IS_FREED: does not happen */ case PLUGIN_IS_DELETED: table->field[2]->store(STRING_WITH_LEN("DELETED"), cs); break; case PLUGIN_IS_UNINITIALIZED: table->field[2]->store(STRING_WITH_LEN("INACTIVE"), cs); break; case PLUGIN_IS_READY: table->field[2]->store(STRING_WITH_LEN("ACTIVE"), cs); break; case PLUGIN_IS_DISABLED: table->field[2]->store(STRING_WITH_LEN("DISABLED"), cs); break; default: DBUG_ASSERT(0); } table->field[3]->store(plugin_type_names[plug->type].str, plugin_type_names[plug->type].length, cs); table->field[4]->store(version_buf, make_version_string(version_buf, sizeof(version_buf), *(uint *)plug->info), cs); if (plugin_dl) { table->field[5]->store(plugin_dl->dl.str, plugin_dl->dl.length, cs); table->field[5]->set_notnull(); table->field[6]->store(version_buf, make_version_string(version_buf, sizeof(version_buf), plugin_dl->version), cs); table->field[6]->set_notnull(); } else { table->field[5]->set_null(); table->field[6]->set_null(); } if (plug->author) { table->field[7]->store(plug->author, strlen(plug->author), cs); table->field[7]->set_notnull(); } else table->field[7]->set_null(); if (plug->descr) { table->field[8]->store(plug->descr, strlen(plug->descr), cs); table->field[8]->set_notnull(); } else table->field[8]->set_null(); switch (plug->license) { case PLUGIN_LICENSE_GPL: table->field[9]->store(PLUGIN_LICENSE_GPL_STRING, strlen(PLUGIN_LICENSE_GPL_STRING), cs); break; case PLUGIN_LICENSE_BSD: table->field[9]->store(PLUGIN_LICENSE_BSD_STRING, strlen(PLUGIN_LICENSE_BSD_STRING), cs); break; default: table->field[9]->store(PLUGIN_LICENSE_PROPRIETARY_STRING, strlen(PLUGIN_LICENSE_PROPRIETARY_STRING), cs); break; } table->field[9]->set_notnull(); table->field[10]->store( global_plugin_typelib_names[plugin_load_option(plugin)], strlen(global_plugin_typelib_names[plugin_load_option(plugin)]), cs); return schema_table_store_record(thd, table); } int fill_plugins(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_plugins"); TABLE *table= tables->table; if (plugin_foreach_with_mask(thd, show_plugins, MYSQL_ANY_PLUGIN, ~PLUGIN_IS_FREED, table)) DBUG_RETURN(1); DBUG_RETURN(0); } /*************************************************************************** ** List all Authors. ** If you can update it, you get to be in it :) ***************************************************************************/ bool mysqld_show_authors(THD *thd) { List<Item> field_list; Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_show_authors"); field_list.push_back(new Item_empty_string("Name",40)); field_list.push_back(new Item_empty_string("Location",40)); field_list.push_back(new Item_empty_string("Comment",80)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); show_table_authors_st *authors; for (authors= show_table_authors; authors->name; authors++) { protocol->prepare_for_resend(); protocol->store(authors->name, system_charset_info); protocol->store(authors->location, system_charset_info); protocol->store(authors->comment, system_charset_info); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); } /*************************************************************************** ** List all Contributors. ** Please get permission before updating ***************************************************************************/ bool mysqld_show_contributors(THD *thd) { List<Item> field_list; Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_show_contributors"); field_list.push_back(new Item_empty_string("Name",40)); field_list.push_back(new Item_empty_string("Location",40)); field_list.push_back(new Item_empty_string("Comment",80)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); show_table_contributors_st *contributors; for (contributors= show_table_contributors; contributors->name; contributors++) { protocol->prepare_for_resend(); protocol->store(contributors->name, system_charset_info); protocol->store(contributors->location, system_charset_info); protocol->store(contributors->comment, system_charset_info); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); } /*************************************************************************** List all privileges supported ***************************************************************************/ struct show_privileges_st { const char *privilege; const char *context; const char *comment; }; static struct show_privileges_st sys_privileges[]= { {"Alter", "Tables", "To alter the table"}, {"Alter routine", "Functions,Procedures", "To alter or drop stored functions/procedures"}, {"Create", "Databases,Tables,Indexes", "To create new databases and tables"}, {"Create routine","Databases","To use CREATE FUNCTION/PROCEDURE"}, {"Create temporary tables","Databases","To use CREATE TEMPORARY TABLE"}, {"Create view", "Tables", "To create new views"}, {"Create user", "Server Admin", "To create new users"}, {"Delete", "Tables", "To delete existing rows"}, {"Drop", "Databases,Tables", "To drop databases, tables, and views"}, #ifdef HAVE_EVENT_SCHEDULER {"Event","Server Admin","To create, alter, drop and execute events"}, #endif {"Execute", "Functions,Procedures", "To execute stored routines"}, {"File", "File access on server", "To read and write files on the server"}, {"Grant option", "Databases,Tables,Functions,Procedures", "To give to other users those privileges you possess"}, {"Index", "Tables", "To create or drop indexes"}, {"Insert", "Tables", "To insert data into tables"}, {"Lock tables","Databases","To use LOCK TABLES (together with SELECT privilege)"}, {"Process", "Server Admin", "To view the plain text of currently executing queries"}, {"Proxy", "Server Admin", "To make proxy user possible"}, {"References", "Databases,Tables", "To have references on tables"}, {"Reload", "Server Admin", "To reload or refresh tables, logs and privileges"}, {"Replication client","Server Admin","To ask where the slave or master servers are"}, {"Replication slave","Server Admin","To read binary log events from the master"}, {"Select", "Tables", "To retrieve rows from table"}, {"Show databases","Server Admin","To see all databases with SHOW DATABASES"}, {"Show view","Tables","To see views with SHOW CREATE VIEW"}, {"Shutdown","Server Admin", "To shut down the server"}, {"Super","Server Admin","To use KILL thread, SET GLOBAL, CHANGE MASTER, etc."}, {"Trigger","Tables", "To use triggers"}, {"Create tablespace", "Server Admin", "To create/alter/drop tablespaces"}, {"Update", "Tables", "To update existing rows"}, {"Usage","Server Admin","No privileges - allow connect only"}, {NullS, NullS, NullS} }; bool mysqld_show_privileges(THD *thd) { List<Item> field_list; Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_show_privileges"); field_list.push_back(new Item_empty_string("Privilege",10)); field_list.push_back(new Item_empty_string("Context",15)); field_list.push_back(new Item_empty_string("Comment",NAME_CHAR_LEN)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); show_privileges_st *privilege= sys_privileges; for (privilege= sys_privileges; privilege->privilege ; privilege++) { protocol->prepare_for_resend(); protocol->store(privilege->privilege, system_charset_info); protocol->store(privilege->context, system_charset_info); protocol->store(privilege->comment, system_charset_info); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); } /* find_files() - find files in a given directory. SYNOPSIS find_files() thd thread handler files put found files in this list db database name to set in TABLE_LIST structure path path to database wild filter for found files dir read databases in path if TRUE, read .frm files in database otherwise RETURN FIND_FILES_OK success FIND_FILES_OOM out of memory error FIND_FILES_DIR no such directory, or directory can't be read */ find_files_result find_files(THD *thd, List<LEX_STRING> *files, const char *db, const char *path, const char *wild, bool dir) { uint i; char *ext; MY_DIR *dirp; FILEINFO *file; LEX_STRING *file_name= 0; uint file_name_len; #ifndef NO_EMBEDDED_ACCESS_CHECKS uint col_access=thd->col_access; #endif uint wild_length= 0; TABLE_LIST table_list; DBUG_ENTER("find_files"); if (wild) { if (!wild[0]) wild= 0; else wild_length= strlen(wild); } bzero((char*) &table_list,sizeof(table_list)); if (!(dirp = my_dir(path,MYF(dir ? MY_WANT_STAT : 0)))) { if (my_errno == ENOENT) my_error(ER_BAD_DB_ERROR, MYF(ME_BELL+ME_WAITTANG), db); else my_error(ER_CANT_READ_DIR, MYF(ME_BELL+ME_WAITTANG), path, my_errno); DBUG_RETURN(FIND_FILES_DIR); } for (i=0 ; i < (uint) dirp->number_off_files ; i++) { char uname[NAME_LEN + 1]; /* Unencoded name */ file=dirp->dir_entry+i; if (dir) { /* Return databases */ if ((file->name[0] == '.' && ((file->name[1] == '.' && file->name[2] == '\0') || file->name[1] == '\0'))) continue; /* . or .. */ #ifdef USE_SYMDIR char *ext; char buff[FN_REFLEN]; if (my_use_symdir && !strcmp(ext=fn_ext(file->name), ".sym")) { /* Only show the sym file if it points to a directory */ char *end; *ext=0; /* Remove extension */ unpack_dirname(buff, file->name); end= strend(buff); if (end != buff && end[-1] == FN_LIBCHAR) end[-1]= 0; // Remove end FN_LIBCHAR if (!mysql_file_stat(key_file_misc, buff, file->mystat, MYF(0))) continue; } #endif if (!MY_S_ISDIR(file->mystat->st_mode)) continue; file_name_len= filename_to_tablename(file->name, uname, sizeof(uname)); if (wild) { if (lower_case_table_names) { if (my_wildcmp(files_charset_info, uname, uname + file_name_len, wild, wild + wild_length, wild_prefix, wild_one,wild_many)) continue; } else if (wild_compare(uname, wild, 0)) continue; } } else { // Return only .frm files which aren't temp files. if (my_strcasecmp(system_charset_info, ext=fn_rext(file->name),reg_ext) || is_prefix(file->name, tmp_file_prefix)) continue; *ext=0; file_name_len= filename_to_tablename(file->name, uname, sizeof(uname)); if (wild) { if (lower_case_table_names) { if (my_wildcmp(files_charset_info, uname, uname + file_name_len, wild, wild + wild_length, wild_prefix, wild_one,wild_many)) continue; } else if (wild_compare(uname, wild, 0)) continue; } } #ifndef NO_EMBEDDED_ACCESS_CHECKS /* Don't show tables where we don't have any privileges */ if (db && !(col_access & TABLE_ACLS)) { table_list.db= (char*) db; table_list.db_length= strlen(db); table_list.table_name= uname; table_list.table_name_length= file_name_len; table_list.grant.privilege=col_access; if (check_grant(thd, TABLE_ACLS, &table_list, TRUE, 1, TRUE)) continue; } #endif if (!(file_name= thd->make_lex_string(file_name, uname, file_name_len, TRUE)) || files->push_back(file_name)) { my_dirend(dirp); DBUG_RETURN(FIND_FILES_OOM); } } DBUG_PRINT("info",("found: %d files", files->elements)); my_dirend(dirp); (void) ha_find_files(thd, db, path, wild, dir, files); DBUG_RETURN(FIND_FILES_OK); } /** An Internal_error_handler that suppresses errors regarding views' underlying tables that occur during privilege checking within SHOW CREATE VIEW commands. This happens in the cases when - A view's underlying table (e.g. referenced in its SELECT list) does not exist. There should not be an error as no attempt was made to access it per se. - Access is denied for some table, column, function or stored procedure such as mentioned above. This error gets raised automatically, since we can't untangle its access checking from that of the view itself. */ class Show_create_error_handler : public Internal_error_handler { TABLE_LIST *m_top_view; bool m_handling; Security_context *m_sctx; char m_view_access_denied_message[MYSQL_ERRMSG_SIZE]; char *m_view_access_denied_message_ptr; public: /** Creates a new Show_create_error_handler for the particular security context and view. @thd Thread context, used for security context information if needed. @top_view The view. We do not verify at this point that top_view is in fact a view since, alas, these things do not stay constant. */ explicit Show_create_error_handler(THD *thd, TABLE_LIST *top_view) : m_top_view(top_view), m_handling(FALSE), m_view_access_denied_message_ptr(NULL) { m_sctx = test(m_top_view->security_ctx) ? m_top_view->security_ctx : thd->security_ctx; } /** Lazy instantiation of 'view access denied' message. The purpose of the Show_create_error_handler is to hide details of underlying tables for which we have no privileges behind ER_VIEW_INVALID messages. But this obviously does not apply if we lack privileges on the view itself. Unfortunately the information about for which table privilege checking failed is not available at this point. The only way for us to check is by reconstructing the actual error message and see if it's the same. */ char* get_view_access_denied_message() { if (!m_view_access_denied_message_ptr) { m_view_access_denied_message_ptr= m_view_access_denied_message; my_snprintf(m_view_access_denied_message, MYSQL_ERRMSG_SIZE, ER(ER_TABLEACCESS_DENIED_ERROR), "SHOW VIEW", m_sctx->priv_user, m_sctx->host_or_ip, m_top_view->get_table_name()); } return m_view_access_denied_message_ptr; } bool handle_condition(THD *thd, uint sql_errno, const char * /* sqlstate */, MYSQL_ERROR::enum_warning_level level, const char *message, MYSQL_ERROR ** /* cond_hdl */) { /* The handler does not handle the errors raised by itself. At this point we know if top_view is really a view. */ if (m_handling || !m_top_view->view) return FALSE; m_handling= TRUE; bool is_handled; switch (sql_errno) { case ER_TABLEACCESS_DENIED_ERROR: if (!strcmp(get_view_access_denied_message(), message)) { /* Access to top view is not granted, don't interfere. */ is_handled= FALSE; break; } case ER_COLUMNACCESS_DENIED_ERROR: case ER_VIEW_NO_EXPLAIN: /* Error was anonymized, ignore all the same. */ case ER_PROCACCESS_DENIED_ERROR: is_handled= TRUE; break; case ER_NO_SUCH_TABLE: /* Established behavior: warn if underlying tables are missing. */ push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_VIEW_INVALID, ER(ER_VIEW_INVALID), m_top_view->get_db_name(), m_top_view->get_table_name()); is_handled= TRUE; break; case ER_SP_DOES_NOT_EXIST: /* Established behavior: warn if underlying functions are missing. */ push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_VIEW_INVALID, ER(ER_VIEW_INVALID), m_top_view->get_db_name(), m_top_view->get_table_name()); is_handled= TRUE; break; default: is_handled= FALSE; } m_handling= FALSE; return is_handled; } }; bool mysqld_show_create(THD *thd, TABLE_LIST *table_list) { Protocol *protocol= thd->protocol; char buff[2048]; String buffer(buff, sizeof(buff), system_charset_info); List<Item> field_list; bool error= TRUE; DBUG_ENTER("mysqld_show_create"); DBUG_PRINT("enter",("db: %s table: %s",table_list->db, table_list->table_name)); /* Metadata locks taken during SHOW CREATE should be released when the statmement completes as it is an information statement. */ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint(); /* We want to preserve the tree for views. */ thd->lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW; { /* Use open_tables() directly rather than open_normal_and_derived_tables(). This ensures that close_thread_tables() is not called if open tables fails and the error is ignored. This allows us to handle broken views nicely. */ uint counter; Show_create_error_handler view_error_suppressor(thd, table_list); thd->push_internal_handler(&view_error_suppressor); bool open_error= open_tables(thd, &table_list, &counter, MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL) || mysql_handle_derived(thd->lex, &mysql_derived_prepare); thd->pop_internal_handler(); if (open_error && (thd->killed || thd->is_error())) goto exit; } /* TODO: add environment variables show when it become possible */ if (thd->lex->only_view && !table_list->view) { my_error(ER_WRONG_OBJECT, MYF(0), table_list->db, table_list->table_name, "VIEW"); goto exit; } buffer.length(0); if (table_list->view) buffer.set_charset(table_list->view_creation_ctx->get_client_cs()); if ((table_list->view ? view_store_create_info(thd, table_list, &buffer) : store_create_info(thd, table_list, &buffer, NULL, FALSE /* show_database */))) goto exit; if (table_list->view) { field_list.push_back(new Item_empty_string("View",NAME_CHAR_LEN)); field_list.push_back(new Item_empty_string("Create View", max(buffer.length(),1024))); field_list.push_back(new Item_empty_string("character_set_client", MY_CS_NAME_SIZE)); field_list.push_back(new Item_empty_string("collation_connection", MY_CS_NAME_SIZE)); } else { field_list.push_back(new Item_empty_string("Table",NAME_CHAR_LEN)); // 1024 is for not to confuse old clients field_list.push_back(new Item_empty_string("Create Table", max(buffer.length(),1024))); } if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) goto exit; protocol->prepare_for_resend(); if (table_list->view) protocol->store(table_list->view_name.str, system_charset_info); else { if (table_list->schema_table) protocol->store(table_list->schema_table->table_name, system_charset_info); else protocol->store(table_list->table->alias, system_charset_info); } if (table_list->view) { protocol->store(buffer.ptr(), buffer.length(), table_list->view_creation_ctx->get_client_cs()); protocol->store(table_list->view_creation_ctx->get_client_cs()->csname, system_charset_info); protocol->store(table_list->view_creation_ctx->get_connection_cl()->name, system_charset_info); } else protocol->store(buffer.ptr(), buffer.length(), buffer.charset()); if (protocol->write()) goto exit; error= FALSE; my_eof(thd); exit: close_thread_tables(thd); /* Release any metadata locks taken during SHOW CREATE. */ thd->mdl_context.rollback_to_savepoint(mdl_savepoint); DBUG_RETURN(error); } bool mysqld_show_create_db(THD *thd, char *dbname, HA_CREATE_INFO *create_info) { char buff[2048]; String buffer(buff, sizeof(buff), system_charset_info); #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *sctx= thd->security_ctx; uint db_access; #endif HA_CREATE_INFO create; uint create_options = create_info ? create_info->options : 0; Protocol *protocol=thd->protocol; DBUG_ENTER("mysql_show_create_db"); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (test_all_bits(sctx->master_access, DB_ACLS)) db_access=DB_ACLS; else db_access= (acl_get(sctx->get_host()->ptr(), sctx->get_ip()->ptr(), sctx->priv_user, dbname, 0) | sctx->master_access); if (!(db_access & DB_ACLS) && check_grant_db(thd,dbname)) { my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), sctx->priv_user, sctx->host_or_ip, dbname); general_log_print(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR), sctx->priv_user, sctx->host_or_ip, dbname); DBUG_RETURN(TRUE); } #endif if (is_infoschema_db(dbname)) { dbname= INFORMATION_SCHEMA_NAME.str; create.default_table_charset= system_charset_info; } else { if (check_db_dir_existence(dbname)) { my_error(ER_BAD_DB_ERROR, MYF(0), dbname); DBUG_RETURN(TRUE); } load_db_opt_by_name(thd, dbname, &create); } List<Item> field_list; field_list.push_back(new Item_empty_string("Database",NAME_CHAR_LEN)); field_list.push_back(new Item_empty_string("Create Database",1024)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); protocol->prepare_for_resend(); protocol->store(dbname, strlen(dbname), system_charset_info); buffer.length(0); buffer.append(STRING_WITH_LEN("CREATE DATABASE ")); if (create_options & HA_LEX_CREATE_IF_NOT_EXISTS) buffer.append(STRING_WITH_LEN("/*!32312 IF NOT EXISTS*/ ")); append_identifier(thd, &buffer, dbname, strlen(dbname)); if (create.default_table_charset) { buffer.append(STRING_WITH_LEN(" /*!40100")); buffer.append(STRING_WITH_LEN(" DEFAULT CHARACTER SET ")); buffer.append(create.default_table_charset->csname); if (!(create.default_table_charset->state & MY_CS_PRIMARY)) { buffer.append(STRING_WITH_LEN(" COLLATE ")); buffer.append(create.default_table_charset->name); } buffer.append(STRING_WITH_LEN(" */")); } protocol->store(buffer.ptr(), buffer.length(), buffer.charset()); if (protocol->write()) DBUG_RETURN(TRUE); my_eof(thd); DBUG_RETURN(FALSE); } /**************************************************************************** Return only fields for API mysql_list_fields Use "show table wildcard" in mysql instead of this ****************************************************************************/ void mysqld_list_fields(THD *thd, TABLE_LIST *table_list, const char *wild) { TABLE *table; DBUG_ENTER("mysqld_list_fields"); DBUG_PRINT("enter",("table: %s",table_list->table_name)); if (open_normal_and_derived_tables(thd, table_list, MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL)) DBUG_VOID_RETURN; table= table_list->table; List<Item> field_list; Field **ptr,*field; for (ptr=table->field ; (field= *ptr); ptr++) { if (!wild || !wild[0] || !wild_case_compare(system_charset_info, field->field_name,wild)) { if (table_list->view) field_list.push_back(new Item_ident_for_show(field, table_list->view_db.str, table_list->view_name.str)); else field_list.push_back(new Item_field(field)); } } restore_record(table, s->default_values); // Get empty record table->use_all_columns(); if (thd->protocol->send_result_set_metadata(&field_list, Protocol::SEND_DEFAULTS)) DBUG_VOID_RETURN; my_eof(thd); DBUG_VOID_RETURN; } /* Go through all character combinations and ensure that sql_lex.cc can parse it as an identifier. SYNOPSIS require_quotes() name attribute name name_length length of name RETURN # Pointer to conflicting character 0 No conflicting character */ static const char *require_quotes(const char *name, uint name_length) { uint length; bool pure_digit= TRUE; const char *end= name + name_length; for (; name < end ; name++) { uchar chr= (uchar) *name; length= my_mbcharlen(system_charset_info, chr); if (length == 1 && !system_charset_info->ident_map[chr]) return name; if (length == 1 && (chr < '0' || chr > '9')) pure_digit= FALSE; } if (pure_digit) return name; return 0; } /* Quote the given identifier if needed and append it to the target string. If the given identifier is empty, it will be quoted. SYNOPSIS append_identifier() thd thread handler packet target string name the identifier to be appended name_length length of the appending identifier */ void append_identifier(THD *thd, String *packet, const char *name, uint length) { const char *name_end; char quote_char; int q; q= thd ? get_quote_char_for_identifier(thd, name, length) : '`'; if (q == EOF) { packet->append(name, length, packet->charset()); return; } /* The identifier must be quoted as it includes a quote character or it's a keyword */ (void) packet->reserve(length*2 + 2); quote_char= (char) q; packet->append(&quote_char, 1, system_charset_info); for (name_end= name+length ; name < name_end ; name+= length) { uchar chr= (uchar) *name; length= my_mbcharlen(system_charset_info, chr); /* my_mbcharlen can return 0 on a wrong multibyte sequence. It is possible when upgrading from 4.0, and identifier contains some accented characters. The manual says it does not work. So we'll just change length to 1 not to hang in the endless loop. */ if (!length) length= 1; if (length == 1 && chr == (uchar) quote_char) packet->append(&quote_char, 1, system_charset_info); packet->append(name, length, system_charset_info); } packet->append(&quote_char, 1, system_charset_info); } /* Get the quote character for displaying an identifier. SYNOPSIS get_quote_char_for_identifier() thd Thread handler name name to quote length length of name IMPLEMENTATION Force quoting in the following cases: - name is empty (for one, it is possible when we use this function for quoting user and host names for DEFINER clause); - name is a keyword; - name includes a special character; Otherwise identifier is quoted only if the option OPTION_QUOTE_SHOW_CREATE is set. RETURN EOF No quote character is needed # Quote character */ int get_quote_char_for_identifier(THD *thd, const char *name, uint length) { if (length && !is_keyword(name,length) && !require_quotes(name, length) && !(thd->variables.option_bits & OPTION_QUOTE_SHOW_CREATE)) return EOF; if (thd->variables.sql_mode & MODE_ANSI_QUOTES) return '"'; return '`'; } /* Append directory name (if exists) to CREATE INFO */ static void append_directory(THD *thd, String *packet, const char *dir_type, const char *filename) { if (filename && !(thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE)) { uint length= dirname_length(filename); packet->append(' '); packet->append(dir_type); packet->append(STRING_WITH_LEN(" DIRECTORY='")); #ifdef __WIN__ /* Convert \ to / to be able to create table on unix */ char *winfilename= (char*) thd->memdup(filename, length); char *pos, *end; for (pos= winfilename, end= pos+length ; pos < end ; pos++) { if (*pos == '\\') *pos = '/'; } filename= winfilename; #endif packet->append(filename, length); packet->append('\''); } } #define LIST_PROCESS_HOST_LEN 64 static bool get_field_default_value(THD *thd, Field *timestamp_field, Field *field, String *def_value, bool quoted) { bool has_default; bool has_now_default; enum enum_field_types field_type= field->type(); /* We are using CURRENT_TIMESTAMP instead of NOW because it is more standard */ has_now_default= (timestamp_field == field && field->unireg_check != Field::TIMESTAMP_UN_FIELD); has_default= (field_type != FIELD_TYPE_BLOB && !(field->flags & NO_DEFAULT_VALUE_FLAG) && field->unireg_check != Field::NEXT_NUMBER && !((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) && has_now_default)); def_value->length(0); if (has_default) { if (has_now_default) def_value->append(STRING_WITH_LEN("CURRENT_TIMESTAMP")); else if (!field->is_null()) { // Not null by default char tmp[MAX_FIELD_WIDTH]; String type(tmp, sizeof(tmp), field->charset()); if (field_type == MYSQL_TYPE_BIT) { longlong dec= field->val_int(); char *ptr= longlong2str(dec, tmp + 2, 2); uint32 length= (uint32) (ptr - tmp); tmp[0]= 'b'; tmp[1]= '\''; tmp[length]= '\''; type.length(length + 1); quoted= 0; } else field->val_str(&type); if (type.length()) { String def_val; uint dummy_errors; /* convert to system_charset_info == utf8 */ def_val.copy(type.ptr(), type.length(), field->charset(), system_charset_info, &dummy_errors); if (quoted) append_unescaped(def_value, def_val.ptr(), def_val.length()); else def_value->append(def_val.ptr(), def_val.length()); } else if (quoted) def_value->append(STRING_WITH_LEN("''")); } else if (field->maybe_null() && quoted) def_value->append(STRING_WITH_LEN("NULL")); // Null as default else return 0; } return has_default; } /* Build a CREATE TABLE statement for a table. SYNOPSIS store_create_info() thd The thread table_list A list containing one table to write statement for. packet Pointer to a string where statement will be written. create_info_arg Pointer to create information that can be used to tailor the format of the statement. Can be NULL, in which case only SQL_MODE is considered when building the statement. NOTE Currently always return 0, but might return error code in the future. RETURN 0 OK */ int store_create_info(THD *thd, TABLE_LIST *table_list, String *packet, HA_CREATE_INFO *create_info_arg, bool show_database) { List<Item> field_list; char tmp[MAX_FIELD_WIDTH], *for_str, buff[128], def_value_buf[MAX_FIELD_WIDTH]; const char *alias; String type(tmp, sizeof(tmp), system_charset_info); String def_value(def_value_buf, sizeof(def_value_buf), system_charset_info); Field **ptr,*field; uint primary_key; KEY *key_info; TABLE *table= table_list->table; handler *file= table->file; TABLE_SHARE *share= table->s; HA_CREATE_INFO create_info; #ifdef WITH_PARTITION_STORAGE_ENGINE bool show_table_options= FALSE; #endif /* WITH_PARTITION_STORAGE_ENGINE */ bool foreign_db_mode= (thd->variables.sql_mode & (MODE_POSTGRESQL | MODE_ORACLE | MODE_MSSQL | MODE_DB2 | MODE_MAXDB | MODE_ANSI)) != 0; bool limited_mysql_mode= (thd->variables.sql_mode & (MODE_NO_FIELD_OPTIONS | MODE_MYSQL323 | MODE_MYSQL40)) != 0; my_bitmap_map *old_map; int error= 0; DBUG_ENTER("store_create_info"); DBUG_PRINT("enter",("table: %s", table->s->table_name.str)); restore_record(table, s->default_values); // Get empty record if (share->tmp_table) packet->append(STRING_WITH_LEN("CREATE TEMPORARY TABLE ")); else packet->append(STRING_WITH_LEN("CREATE TABLE ")); if (create_info_arg && (create_info_arg->options & HA_LEX_CREATE_IF_NOT_EXISTS)) packet->append(STRING_WITH_LEN("IF NOT EXISTS ")); if (table_list->schema_table) alias= table_list->schema_table->table_name; else { if (lower_case_table_names == 2) alias= table->alias; else { alias= share->table_name.str; } } /* Print the database before the table name if told to do that. The database name is only printed in the event that it is different from the current database. The main reason for doing this is to avoid having to update gazillions of tests and result files, but it also saves a few bytes of the binary log. */ if (show_database) { const LEX_STRING *const db= table_list->schema_table ? &INFORMATION_SCHEMA_NAME : &table->s->db; if (!thd->db || strcmp(db->str, thd->db)) { append_identifier(thd, packet, db->str, db->length); packet->append(STRING_WITH_LEN(".")); } } append_identifier(thd, packet, alias, strlen(alias)); packet->append(STRING_WITH_LEN(" (\n")); /* We need this to get default values from the table We have to restore the read_set if we are called from insert in case of row based replication. */ old_map= tmp_use_all_columns(table, table->read_set); for (ptr=table->field ; (field= *ptr); ptr++) { uint flags = field->flags; if (ptr != table->field) packet->append(STRING_WITH_LEN(",\n")); packet->append(STRING_WITH_LEN(" ")); append_identifier(thd,packet,field->field_name, strlen(field->field_name)); packet->append(' '); // check for surprises from the previous call to Field::sql_type() if (type.ptr() != tmp) type.set(tmp, sizeof(tmp), system_charset_info); else type.set_charset(system_charset_info); field->sql_type(type); packet->append(type.ptr(), type.length(), system_charset_info); if (field->has_charset() && !(thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40))) { if (field->charset() != share->table_charset) { packet->append(STRING_WITH_LEN(" CHARACTER SET ")); packet->append(field->charset()->csname); } /* For string types dump collation name only if collation is not primary for the given charset */ if (!(field->charset()->state & MY_CS_PRIMARY)) { packet->append(STRING_WITH_LEN(" COLLATE ")); packet->append(field->charset()->name); } } if (flags & NOT_NULL_FLAG) packet->append(STRING_WITH_LEN(" NOT NULL")); else if (field->type() == MYSQL_TYPE_TIMESTAMP) { /* TIMESTAMP field require explicit NULL flag, because unlike all other fields they are treated as NOT NULL by default. */ packet->append(STRING_WITH_LEN(" NULL")); } if (get_field_default_value(thd, table->timestamp_field, field, &def_value, 1)) { packet->append(STRING_WITH_LEN(" DEFAULT ")); packet->append(def_value.ptr(), def_value.length(), system_charset_info); } if (!limited_mysql_mode && table->timestamp_field == field && field->unireg_check != Field::TIMESTAMP_DN_FIELD) packet->append(STRING_WITH_LEN(" ON UPDATE CURRENT_TIMESTAMP")); if (field->unireg_check == Field::NEXT_NUMBER && !(thd->variables.sql_mode & MODE_NO_FIELD_OPTIONS)) packet->append(STRING_WITH_LEN(" AUTO_INCREMENT")); if (field->comment.length) { packet->append(STRING_WITH_LEN(" COMMENT ")); append_unescaped(packet, field->comment.str, field->comment.length); } } key_info= table->key_info; bzero((char*) &create_info, sizeof(create_info)); /* Allow update_create_info to update row type */ create_info.row_type= share->row_type; file->update_create_info(&create_info); primary_key= share->primary_key; for (uint i=0 ; i < share->keys ; i++,key_info++) { KEY_PART_INFO *key_part= key_info->key_part; bool found_primary=0; packet->append(STRING_WITH_LEN(",\n ")); if (i == primary_key && !strcmp(key_info->name, primary_key_name)) { found_primary=1; /* No space at end, because a space will be added after where the identifier would go, but that is not added for primary key. */ packet->append(STRING_WITH_LEN("PRIMARY KEY")); } else if (key_info->flags & HA_NOSAME) packet->append(STRING_WITH_LEN("UNIQUE KEY ")); else if (key_info->flags & HA_FULLTEXT) packet->append(STRING_WITH_LEN("FULLTEXT KEY ")); else if (key_info->flags & HA_SPATIAL) packet->append(STRING_WITH_LEN("SPATIAL KEY ")); else packet->append(STRING_WITH_LEN("KEY ")); if (!found_primary) append_identifier(thd, packet, key_info->name, strlen(key_info->name)); packet->append(STRING_WITH_LEN(" (")); for (uint j=0 ; j < key_info->key_parts ; j++,key_part++) { if (j) packet->append(','); if (key_part->field) append_identifier(thd,packet,key_part->field->field_name, strlen(key_part->field->field_name)); if (key_part->field && (key_part->length != table->field[key_part->fieldnr-1]->key_length() && !(key_info->flags & (HA_FULLTEXT | HA_SPATIAL)))) { char *end; buff[0] = '('; end= int10_to_str((long) key_part->length / key_part->field->charset()->mbmaxlen, buff + 1,10); *end++ = ')'; packet->append(buff,(uint) (end-buff)); } } packet->append(')'); store_key_options(thd, packet, table, key_info); if (key_info->parser) { LEX_STRING *parser_name= plugin_name(key_info->parser); packet->append(STRING_WITH_LEN(" /*!50100 WITH PARSER ")); append_identifier(thd, packet, parser_name->str, parser_name->length); packet->append(STRING_WITH_LEN(" */ ")); } } /* Get possible foreign key definitions stored in InnoDB and append them to the CREATE TABLE statement */ if ((for_str= file->get_foreign_key_create_info())) { packet->append(for_str, strlen(for_str)); file->free_foreign_key_create_info(for_str); } packet->append(STRING_WITH_LEN("\n)")); if (!(thd->variables.sql_mode & MODE_NO_TABLE_OPTIONS) && !foreign_db_mode) { #ifdef WITH_PARTITION_STORAGE_ENGINE show_table_options= TRUE; #endif /* WITH_PARTITION_STORAGE_ENGINE */ /* TABLESPACE and STORAGE */ if (share->tablespace || share->default_storage_media != HA_SM_DEFAULT) { packet->append(STRING_WITH_LEN(" /*!50100")); if (share->tablespace) { packet->append(STRING_WITH_LEN(" TABLESPACE ")); packet->append(share->tablespace, strlen(share->tablespace)); } if (share->default_storage_media == HA_SM_DISK) packet->append(STRING_WITH_LEN(" STORAGE DISK")); if (share->default_storage_media == HA_SM_MEMORY) packet->append(STRING_WITH_LEN(" STORAGE MEMORY")); packet->append(STRING_WITH_LEN(" */")); } /* IF check_create_info THEN add ENGINE only if it was used when creating the table */ if (!create_info_arg || (create_info_arg->used_fields & HA_CREATE_USED_ENGINE)) { if (thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) packet->append(STRING_WITH_LEN(" TYPE=")); else packet->append(STRING_WITH_LEN(" ENGINE=")); #ifdef WITH_PARTITION_STORAGE_ENGINE if (table->part_info) packet->append(ha_resolve_storage_engine_name( table->part_info->default_engine_type)); else packet->append(file->table_type()); #else packet->append(file->table_type()); #endif } /* Add AUTO_INCREMENT=... if there is an AUTO_INCREMENT column, and NEXT_ID > 1 (the default). We must not print the clause for engines that do not support this as it would break the import of dumps, but as of this writing, the test for whether AUTO_INCREMENT columns are allowed and wether AUTO_INCREMENT=... is supported is identical, !(file->table_flags() & HA_NO_AUTO_INCREMENT)) Because of that, we do not explicitly test for the feature, but may extrapolate its existence from that of an AUTO_INCREMENT column. */ if (create_info.auto_increment_value > 1) { char *end; packet->append(STRING_WITH_LEN(" AUTO_INCREMENT=")); end= longlong10_to_str(create_info.auto_increment_value, buff,10); packet->append(buff, (uint) (end - buff)); } if (share->table_charset && !(thd->variables.sql_mode & MODE_MYSQL323) && !(thd->variables.sql_mode & MODE_MYSQL40)) { /* IF check_create_info THEN add DEFAULT CHARSET only if it was used when creating the table */ if (!create_info_arg || (create_info_arg->used_fields & HA_CREATE_USED_DEFAULT_CHARSET)) { packet->append(STRING_WITH_LEN(" DEFAULT CHARSET=")); packet->append(share->table_charset->csname); if (!(share->table_charset->state & MY_CS_PRIMARY)) { packet->append(STRING_WITH_LEN(" COLLATE=")); packet->append(table->s->table_charset->name); } } } if (share->min_rows) { char *end; packet->append(STRING_WITH_LEN(" MIN_ROWS=")); end= longlong10_to_str(share->min_rows, buff, 10); packet->append(buff, (uint) (end- buff)); } if (share->max_rows && !table_list->schema_table) { char *end; packet->append(STRING_WITH_LEN(" MAX_ROWS=")); end= longlong10_to_str(share->max_rows, buff, 10); packet->append(buff, (uint) (end - buff)); } if (share->avg_row_length) { char *end; packet->append(STRING_WITH_LEN(" AVG_ROW_LENGTH=")); end= longlong10_to_str(share->avg_row_length, buff,10); packet->append(buff, (uint) (end - buff)); } if (share->db_create_options & HA_OPTION_PACK_KEYS) packet->append(STRING_WITH_LEN(" PACK_KEYS=1")); if (share->db_create_options & HA_OPTION_NO_PACK_KEYS) packet->append(STRING_WITH_LEN(" PACK_KEYS=0")); /* We use CHECKSUM, instead of TABLE_CHECKSUM, for backward compability */ if (share->db_create_options & HA_OPTION_CHECKSUM) packet->append(STRING_WITH_LEN(" CHECKSUM=1")); if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE) packet->append(STRING_WITH_LEN(" DELAY_KEY_WRITE=1")); if (create_info.row_type != ROW_TYPE_DEFAULT) { packet->append(STRING_WITH_LEN(" ROW_FORMAT=")); packet->append(ha_row_type[(uint) create_info.row_type]); } if (table->s->key_block_size) { char *end; packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE=")); end= longlong10_to_str(table->s->key_block_size, buff, 10); packet->append(buff, (uint) (end - buff)); } table->file->append_create_info(packet); if (share->comment.length) { packet->append(STRING_WITH_LEN(" COMMENT=")); append_unescaped(packet, share->comment.str, share->comment.length); } if (share->connect_string.length) { packet->append(STRING_WITH_LEN(" CONNECTION=")); append_unescaped(packet, share->connect_string.str, share->connect_string.length); } append_directory(thd, packet, "DATA", create_info.data_file_name); append_directory(thd, packet, "INDEX", create_info.index_file_name); } #ifdef WITH_PARTITION_STORAGE_ENGINE { if (table->part_info && !((table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION) && table->part_info->is_auto_partitioned)) { /* Partition syntax for CREATE TABLE is at the end of the syntax. */ uint part_syntax_len; char *part_syntax; String comment_start; table->part_info->set_show_version_string(&comment_start); if ((part_syntax= generate_partition_syntax(table->part_info, &part_syntax_len, FALSE, show_table_options, NULL, NULL, comment_start.c_ptr()))) { packet->append(comment_start); if (packet->append(part_syntax, part_syntax_len) || packet->append(STRING_WITH_LEN(" */"))) error= 1; my_free(part_syntax); } } } #endif tmp_restore_column_map(table->read_set, old_map); DBUG_RETURN(error); } static void store_key_options(THD *thd, String *packet, TABLE *table, KEY *key_info) { bool limited_mysql_mode= (thd->variables.sql_mode & (MODE_NO_FIELD_OPTIONS | MODE_MYSQL323 | MODE_MYSQL40)) != 0; bool foreign_db_mode= (thd->variables.sql_mode & (MODE_POSTGRESQL | MODE_ORACLE | MODE_MSSQL | MODE_DB2 | MODE_MAXDB | MODE_ANSI)) != 0; char *end, buff[32]; if (!(thd->variables.sql_mode & MODE_NO_KEY_OPTIONS) && !limited_mysql_mode && !foreign_db_mode) { if (key_info->algorithm == HA_KEY_ALG_BTREE) packet->append(STRING_WITH_LEN(" USING BTREE")); if (key_info->algorithm == HA_KEY_ALG_HASH) packet->append(STRING_WITH_LEN(" USING HASH")); /* send USING only in non-default case: non-spatial rtree */ if ((key_info->algorithm == HA_KEY_ALG_RTREE) && !(key_info->flags & HA_SPATIAL)) packet->append(STRING_WITH_LEN(" USING RTREE")); if ((key_info->flags & HA_USES_BLOCK_SIZE) && table->s->key_block_size != key_info->block_size) { packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE=")); end= longlong10_to_str(key_info->block_size, buff, 10); packet->append(buff, (uint) (end - buff)); } DBUG_ASSERT(test(key_info->flags & HA_USES_COMMENT) == (key_info->comment.length > 0)); if (key_info->flags & HA_USES_COMMENT) { packet->append(STRING_WITH_LEN(" COMMENT ")); append_unescaped(packet, key_info->comment.str, key_info->comment.length); } } } void view_store_options(THD *thd, TABLE_LIST *table, String *buff) { append_algorithm(table, buff); append_definer(thd, buff, &table->definer.user, &table->definer.host); if (table->view_suid) buff->append(STRING_WITH_LEN("SQL SECURITY DEFINER ")); else buff->append(STRING_WITH_LEN("SQL SECURITY INVOKER ")); } /* Append DEFINER clause to the given buffer. SYNOPSIS append_definer() thd [in] thread handle buffer [inout] buffer to hold DEFINER clause definer_user [in] user name part of definer definer_host [in] host name part of definer */ static void append_algorithm(TABLE_LIST *table, String *buff) { buff->append(STRING_WITH_LEN("ALGORITHM=")); switch ((int8)table->algorithm) { case VIEW_ALGORITHM_UNDEFINED: buff->append(STRING_WITH_LEN("UNDEFINED ")); break; case VIEW_ALGORITHM_TMPTABLE: buff->append(STRING_WITH_LEN("TEMPTABLE ")); break; case VIEW_ALGORITHM_MERGE: buff->append(STRING_WITH_LEN("MERGE ")); break; default: DBUG_ASSERT(0); // never should happen } } /* Append DEFINER clause to the given buffer. SYNOPSIS append_definer() thd [in] thread handle buffer [inout] buffer to hold DEFINER clause definer_user [in] user name part of definer definer_host [in] host name part of definer */ void append_definer(THD *thd, String *buffer, const LEX_STRING *definer_user, const LEX_STRING *definer_host) { buffer->append(STRING_WITH_LEN("DEFINER=")); append_identifier(thd, buffer, definer_user->str, definer_user->length); buffer->append('@'); append_identifier(thd, buffer, definer_host->str, definer_host->length); buffer->append(' '); } int view_store_create_info(THD *thd, TABLE_LIST *table, String *buff) { my_bool compact_view_name= TRUE; my_bool foreign_db_mode= (thd->variables.sql_mode & (MODE_POSTGRESQL | MODE_ORACLE | MODE_MSSQL | MODE_DB2 | MODE_MAXDB | MODE_ANSI)) != 0; if (!thd->db || strcmp(thd->db, table->view_db.str)) /* print compact view name if the view belongs to the current database */ compact_view_name= table->compact_view_format= FALSE; else { /* Compact output format for view body can be used if this view only references table inside it's own db */ TABLE_LIST *tbl; table->compact_view_format= TRUE; for (tbl= thd->lex->query_tables; tbl; tbl= tbl->next_global) { if (strcmp(table->view_db.str, tbl->view ? tbl->view_db.str :tbl->db)!= 0) { table->compact_view_format= FALSE; break; } } } buff->append(STRING_WITH_LEN("CREATE ")); if (!foreign_db_mode) { view_store_options(thd, table, buff); } buff->append(STRING_WITH_LEN("VIEW ")); if (!compact_view_name) { append_identifier(thd, buff, table->view_db.str, table->view_db.length); buff->append('.'); } append_identifier(thd, buff, table->view_name.str, table->view_name.length); buff->append(STRING_WITH_LEN(" AS ")); /* We can't just use table->query, because our SQL_MODE may trigger a different syntax, like when ANSI_QUOTES is defined. */ table->view->unit.print(buff, QT_ORDINARY); if (table->with_check != VIEW_CHECK_NONE) { if (table->with_check == VIEW_CHECK_LOCAL) buff->append(STRING_WITH_LEN(" WITH LOCAL CHECK OPTION")); else buff->append(STRING_WITH_LEN(" WITH CASCADED CHECK OPTION")); } return 0; } /**************************************************************************** Return info about all processes returns for each thread: thread id, user, host, db, command, info ****************************************************************************/ class thread_info :public ilink { public: static void *operator new(size_t size) { return (void*) sql_alloc((uint) size); } static void operator delete(void *ptr __attribute__((unused)), size_t size __attribute__((unused))) { TRASH(ptr, size); } ulong thread_id; time_t start_time; uint command; const char *user,*host,*db,*proc_info,*state_info; CSET_STRING query_string; }; #ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION template class I_List<thread_info>; #endif static const char *thread_state_info(THD *tmp) { #ifndef EMBEDDED_LIBRARY if (tmp->net.reading_or_writing) { if (tmp->net.reading_or_writing == 2) return "Writing to net"; else if (tmp->command == COM_SLEEP) return ""; else return "Reading from net"; } else #endif { if (tmp->proc_info) return tmp->proc_info; else if (tmp->mysys_var && tmp->mysys_var->current_cond) return "Waiting on cond"; else return NULL; } } void mysqld_list_processes(THD *thd,const char *user, bool verbose) { Item *field; List<Item> field_list; I_List<thread_info> thread_infos; ulong max_query_length= (verbose ? thd->variables.max_allowed_packet : PROCESS_LIST_WIDTH); Protocol *protocol= thd->protocol; DBUG_ENTER("mysqld_list_processes"); field_list.push_back(new Item_int("Id", 0, MY_INT32_NUM_DECIMAL_DIGITS)); field_list.push_back(new Item_empty_string("User",16)); field_list.push_back(new Item_empty_string("Host",LIST_PROCESS_HOST_LEN)); field_list.push_back(field=new Item_empty_string("db",NAME_CHAR_LEN)); field->maybe_null=1; field_list.push_back(new Item_empty_string("Command",16)); field_list.push_back(field= new Item_return_int("Time",7, MYSQL_TYPE_LONG)); field->unsigned_flag= 0; field_list.push_back(field=new Item_empty_string("State",30)); field->maybe_null=1; field_list.push_back(field=new Item_empty_string("Info",max_query_length)); field->maybe_null=1; if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_VOID_RETURN; mysql_mutex_lock(&LOCK_thread_count); // For unlink from list if (!thd->killed) { I_List_iterator<THD> it(threads); THD *tmp; while ((tmp=it++)) { Security_context *tmp_sctx= tmp->security_ctx; struct st_my_thread_var *mysys_var; if ((tmp->vio_ok() || tmp->system_thread) && (!user || (tmp_sctx->user && !strcmp(tmp_sctx->user, user)))) { thread_info *thd_info= new thread_info; thd_info->thread_id=tmp->thread_id; thd_info->user= thd->strdup(tmp_sctx->user ? tmp_sctx->user : (tmp->system_thread ? "system user" : "unauthenticated user")); if (tmp->peer_port && (tmp_sctx->get_host()->length() || tmp_sctx->get_ip()->length()) && thd->security_ctx->host_or_ip[0]) { if ((thd_info->host= (char*) thd->alloc(LIST_PROCESS_HOST_LEN+1))) my_snprintf((char *) thd_info->host, LIST_PROCESS_HOST_LEN, "%s:%u", tmp_sctx->host_or_ip, tmp->peer_port); } else thd_info->host= thd->strdup(tmp_sctx->host_or_ip[0] ? tmp_sctx->host_or_ip : tmp_sctx->get_host()->length() ? tmp_sctx->get_host()->ptr() : ""); thd_info->command=(int) tmp->command; mysql_mutex_lock(&tmp->LOCK_thd_data); if ((thd_info->db= tmp->db)) // Safe test thd_info->db= thd->strdup(thd_info->db); if ((mysys_var= tmp->mysys_var)) mysql_mutex_lock(&mysys_var->mutex); thd_info->proc_info= (char*) (tmp->killed == THD::KILL_CONNECTION? "Killed" : 0); thd_info->state_info= thread_state_info(tmp); if (mysys_var) mysql_mutex_unlock(&mysys_var->mutex); /* Lock THD mutex that protects its data when looking at it. */ if (tmp->query()) { uint length= min(max_query_length, tmp->query_length()); char *q= thd->strmake(tmp->query(),length); /* Safety: in case strmake failed, we set length to 0. */ thd_info->query_string= CSET_STRING(q, q ? length : 0, tmp->query_charset()); } mysql_mutex_unlock(&tmp->LOCK_thd_data); thd_info->start_time= tmp->start_time; thread_infos.append(thd_info); } } } mysql_mutex_unlock(&LOCK_thread_count); thread_info *thd_info; time_t now= my_time(0); while ((thd_info=thread_infos.get())) { protocol->prepare_for_resend(); protocol->store((ulonglong) thd_info->thread_id); protocol->store(thd_info->user, system_charset_info); protocol->store(thd_info->host, system_charset_info); protocol->store(thd_info->db, system_charset_info); if (thd_info->proc_info) protocol->store(thd_info->proc_info, system_charset_info); else protocol->store(command_name[thd_info->command].str, system_charset_info); if (thd_info->start_time) protocol->store_long ((longlong) (now - thd_info->start_time)); else protocol->store_null(); protocol->store(thd_info->state_info, system_charset_info); protocol->store(thd_info->query_string.str(), thd_info->query_string.charset()); if (protocol->write()) break; /* purecov: inspected */ } my_eof(thd); DBUG_VOID_RETURN; } int fill_schema_processlist(THD* thd, TABLE_LIST* tables, COND* cond) { TABLE *table= tables->table; CHARSET_INFO *cs= system_charset_info; char *user; time_t now= my_time(0); DBUG_ENTER("fill_process_list"); user= thd->security_ctx->master_access & PROCESS_ACL ? NullS : thd->security_ctx->priv_user; mysql_mutex_lock(&LOCK_thread_count); if (!thd->killed) { I_List_iterator<THD> it(threads); THD* tmp; while ((tmp= it++)) { Security_context *tmp_sctx= tmp->security_ctx; struct st_my_thread_var *mysys_var; const char *val, *db; if ((!tmp->vio_ok() && !tmp->system_thread) || (user && (!tmp_sctx->user || strcmp(tmp_sctx->user, user)))) continue; restore_record(table, s->default_values); /* ID */ table->field[0]->store((longlong) tmp->thread_id, TRUE); /* USER */ val= tmp_sctx->user ? tmp_sctx->user : (tmp->system_thread ? "system user" : "unauthenticated user"); table->field[1]->store(val, strlen(val), cs); /* HOST */ if (tmp->peer_port && (tmp_sctx->get_host()->length() || tmp_sctx->get_ip()->length()) && thd->security_ctx->host_or_ip[0]) { char host[LIST_PROCESS_HOST_LEN + 1]; my_snprintf(host, LIST_PROCESS_HOST_LEN, "%s:%u", tmp_sctx->host_or_ip, tmp->peer_port); table->field[2]->store(host, strlen(host), cs); } else table->field[2]->store(tmp_sctx->host_or_ip, strlen(tmp_sctx->host_or_ip), cs); /* DB */ mysql_mutex_lock(&tmp->LOCK_thd_data); if ((db= tmp->db)) { table->field[3]->store(db, strlen(db), cs); table->field[3]->set_notnull(); } if ((mysys_var= tmp->mysys_var)) mysql_mutex_lock(&mysys_var->mutex); /* COMMAND */ if ((val= (char *) (tmp->killed == THD::KILL_CONNECTION? "Killed" : 0))) table->field[4]->store(val, strlen(val), cs); else table->field[4]->store(command_name[tmp->command].str, command_name[tmp->command].length, cs); /* MYSQL_TIME */ table->field[5]->store((longlong)(tmp->start_time ? now - tmp->start_time : 0), FALSE); /* STATE */ if ((val= thread_state_info(tmp))) { table->field[6]->store(val, strlen(val), cs); table->field[6]->set_notnull(); } if (mysys_var) mysql_mutex_unlock(&mysys_var->mutex); mysql_mutex_unlock(&tmp->LOCK_thd_data); /* INFO */ /* Lock THD mutex that protects its data when looking at it. */ mysql_mutex_lock(&tmp->LOCK_thd_data); if (tmp->query()) { table->field[7]->store(tmp->query(), min(PROCESS_LIST_INFO_WIDTH, tmp->query_length()), cs); table->field[7]->set_notnull(); } mysql_mutex_unlock(&tmp->LOCK_thd_data); if (schema_table_store_record(thd, table)) { mysql_mutex_unlock(&LOCK_thread_count); DBUG_RETURN(1); } } } mysql_mutex_unlock(&LOCK_thread_count); DBUG_RETURN(0); } /***************************************************************************** Status functions *****************************************************************************/ static DYNAMIC_ARRAY all_status_vars; static bool status_vars_inited= 0; C_MODE_START static int show_var_cmp(const void *var1, const void *var2) { return strcmp(((SHOW_VAR*)var1)->name, ((SHOW_VAR*)var2)->name); } C_MODE_END /* deletes all the SHOW_UNDEF elements from the array and calls delete_dynamic() if it's completely empty. */ static void shrink_var_array(DYNAMIC_ARRAY *array) { uint a,b; SHOW_VAR *all= dynamic_element(array, 0, SHOW_VAR *); for (a= b= 0; b < array->elements; b++) if (all[b].type != SHOW_UNDEF) all[a++]= all[b]; if (a) { bzero(all+a, sizeof(SHOW_VAR)); // writing NULL-element to the end array->elements= a; } else // array is completely empty - delete it delete_dynamic(array); } /* Adds an array of SHOW_VAR entries to the output of SHOW STATUS SYNOPSIS add_status_vars(SHOW_VAR *list) list - an array of SHOW_VAR entries to add to all_status_vars the last entry must be {0,0,SHOW_UNDEF} NOTE The handling of all_status_vars[] is completely internal, it's allocated automatically when something is added to it, and deleted completely when the last entry is removed. As a special optimization, if add_status_vars() is called before init_status_vars(), it assumes "startup mode" - neither concurrent access to the array nor SHOW STATUS are possible (thus it skips locks and qsort) The last entry of the all_status_vars[] should always be {0,0,SHOW_UNDEF} */ int add_status_vars(SHOW_VAR *list) { int res= 0; if (status_vars_inited) mysql_mutex_lock(&LOCK_status); if (!all_status_vars.buffer && // array is not allocated yet - do it now my_init_dynamic_array(&all_status_vars, sizeof(SHOW_VAR), 200, 20)) { res= 1; goto err; } while (list->name) res|= insert_dynamic(&all_status_vars, (uchar*)list++); res|= insert_dynamic(&all_status_vars, (uchar*)list); // appending NULL-element all_status_vars.elements--; // but next insert_dynamic should overwite it if (status_vars_inited) sort_dynamic(&all_status_vars, show_var_cmp); err: if (status_vars_inited) mysql_mutex_unlock(&LOCK_status); return res; } /* Make all_status_vars[] usable for SHOW STATUS NOTE See add_status_vars(). Before init_status_vars() call, add_status_vars() works in a special fast "startup" mode. Thus init_status_vars() should be called as late as possible but before enabling multi-threading. */ void init_status_vars() { status_vars_inited=1; sort_dynamic(&all_status_vars, show_var_cmp); } void reset_status_vars() { SHOW_VAR *ptr= (SHOW_VAR*) all_status_vars.buffer; SHOW_VAR *last= ptr + all_status_vars.elements; for (; ptr < last; ptr++) { /* Note that SHOW_LONG_NOFLUSH variables are not reset */ if (ptr->type == SHOW_LONG) *(ulong*) ptr->value= 0; } } /* catch-all cleanup function, cleans up everything no matter what DESCRIPTION This function is not strictly required if all add_to_status/ remove_status_vars are properly paired, but it's a safety measure that deletes everything from the all_status_vars[] even if some remove_status_vars were forgotten */ void free_status_vars() { delete_dynamic(&all_status_vars); } /* Removes an array of SHOW_VAR entries from the output of SHOW STATUS SYNOPSIS remove_status_vars(SHOW_VAR *list) list - an array of SHOW_VAR entries to remove to all_status_vars the last entry must be {0,0,SHOW_UNDEF} NOTE there's lots of room for optimizing this, especially in non-sorted mode, but nobody cares - it may be called only in case of failed plugin initialization in the mysqld startup. */ void remove_status_vars(SHOW_VAR *list) { if (status_vars_inited) { mysql_mutex_lock(&LOCK_status); SHOW_VAR *all= dynamic_element(&all_status_vars, 0, SHOW_VAR *); int a= 0, b= all_status_vars.elements, c= (a+b)/2; for (; list->name; list++) { int res= 0; for (a= 0, b= all_status_vars.elements; b-a > 1; c= (a+b)/2) { res= show_var_cmp(list, all+c); if (res < 0) b= c; else if (res > 0) a= c; else break; } if (res == 0) all[c].type= SHOW_UNDEF; } shrink_var_array(&all_status_vars); mysql_mutex_unlock(&LOCK_status); } else { SHOW_VAR *all= dynamic_element(&all_status_vars, 0, SHOW_VAR *); uint i; for (; list->name; list++) { for (i= 0; i < all_status_vars.elements; i++) { if (show_var_cmp(list, all+i)) continue; all[i].type= SHOW_UNDEF; break; } } shrink_var_array(&all_status_vars); } } inline void make_upper(char *buf) { for (; *buf; buf++) *buf= my_toupper(system_charset_info, *buf); } static bool show_status_array(THD *thd, const char *wild, SHOW_VAR *variables, enum enum_var_type value_type, struct system_status_var *status_var, const char *prefix, TABLE *table, bool ucase_names, COND *cond) { my_aligned_storage<SHOW_VAR_FUNC_BUFF_SIZE, MY_ALIGNOF(long)> buffer; char * const buff= buffer.data; char *prefix_end; /* the variable name should not be longer than 64 characters */ char name_buffer[64]; int len; LEX_STRING null_lex_str; SHOW_VAR tmp, *var; COND *partial_cond= 0; enum_check_fields save_count_cuted_fields= thd->count_cuted_fields; bool res= FALSE; CHARSET_INFO *charset= system_charset_info; DBUG_ENTER("show_status_array"); thd->count_cuted_fields= CHECK_FIELD_WARN; null_lex_str.str= 0; // For sys_var->value_ptr() null_lex_str.length= 0; prefix_end=strnmov(name_buffer, prefix, sizeof(name_buffer)-1); if (*prefix) *prefix_end++= '_'; len=name_buffer + sizeof(name_buffer) - prefix_end; partial_cond= make_cond_for_info_schema(cond, table->pos_in_table_list); for (; variables->name; variables++) { strnmov(prefix_end, variables->name, len); name_buffer[sizeof(name_buffer)-1]=0; /* Safety */ if (ucase_names) make_upper(name_buffer); restore_record(table, s->default_values); table->field[0]->store(name_buffer, strlen(name_buffer), system_charset_info); /* if var->type is SHOW_FUNC, call the function. Repeat as necessary, if new var is again SHOW_FUNC */ for (var=variables; var->type == SHOW_FUNC; var= &tmp) ((mysql_show_var_func)(var->value))(thd, &tmp, buff); SHOW_TYPE show_type=var->type; if (show_type == SHOW_ARRAY) { show_status_array(thd, wild, (SHOW_VAR *) var->value, value_type, status_var, name_buffer, table, ucase_names, partial_cond); } else { if (!(wild && wild[0] && wild_case_compare(system_charset_info, name_buffer, wild)) && (!partial_cond || partial_cond->val_int())) { char *value=var->value; const char *pos, *end; // We assign a lot of const's mysql_mutex_lock(&LOCK_global_system_variables); if (show_type == SHOW_SYS) { sys_var *var= ((sys_var *) value); show_type= var->show_type(); value= (char*) var->value_ptr(thd, value_type, &null_lex_str); charset= var->charset(thd); } pos= end= buff; /* note that value may be == buff. All SHOW_xxx code below should still work in this case */ switch (show_type) { case SHOW_DOUBLE_STATUS: value= ((char *) status_var + (ulong) value); /* fall through */ case SHOW_DOUBLE: /* 6 is the default precision for '%f' in sprintf() */ end= buff + my_fcvt(*(double *) value, 6, buff, NULL); break; case SHOW_LONG_STATUS: value= ((char *) status_var + (ulong) value); /* fall through */ case SHOW_LONG: case SHOW_LONG_NOFLUSH: // the difference lies in refresh_status() end= int10_to_str(*(long*) value, buff, 10); break; case SHOW_LONGLONG_STATUS: value= ((char *) status_var + (ulong) value); /* fall through */ case SHOW_LONGLONG: end= longlong10_to_str(*(longlong*) value, buff, 10); break; case SHOW_HA_ROWS: end= longlong10_to_str((longlong) *(ha_rows*) value, buff, 10); break; case SHOW_BOOL: end= strmov(buff, *(bool*) value ? "ON" : "OFF"); break; case SHOW_MY_BOOL: end= strmov(buff, *(my_bool*) value ? "ON" : "OFF"); break; case SHOW_INT: end= int10_to_str((long) *(uint32*) value, buff, 10); break; case SHOW_HAVE: { SHOW_COMP_OPTION tmp= *(SHOW_COMP_OPTION*) value; pos= show_comp_option_name[(int) tmp]; end= strend(pos); break; } case SHOW_CHAR: { if (!(pos= value)) pos= ""; end= strend(pos); break; } case SHOW_CHAR_PTR: { if (!(pos= *(char**) value)) pos= ""; DBUG_EXECUTE_IF("alter_server_version_str", if (!my_strcasecmp(system_charset_info, variables->name, "version")) { pos= "some-other-version"; }); end= strend(pos); break; } case SHOW_LEX_STRING: { LEX_STRING *ls=(LEX_STRING*)value; if (!(pos= ls->str)) end= pos= ""; else end= pos + ls->length; break; } case SHOW_KEY_CACHE_LONG: value= (char*) dflt_key_cache + (ulong)value; end= int10_to_str(*(long*) value, buff, 10); break; case SHOW_KEY_CACHE_LONGLONG: value= (char*) dflt_key_cache + (ulong)value; end= longlong10_to_str(*(longlong*) value, buff, 10); break; case SHOW_UNDEF: break; // Return empty string case SHOW_SYS: // Cannot happen default: DBUG_ASSERT(0); break; } table->field[1]->store(pos, (uint32) (end - pos), charset); thd->count_cuted_fields= CHECK_FIELD_IGNORE; table->field[1]->set_notnull(); mysql_mutex_unlock(&LOCK_global_system_variables); if (schema_table_store_record(thd, table)) { res= TRUE; goto end; } } } } end: thd->count_cuted_fields= save_count_cuted_fields; DBUG_RETURN(res); } /* collect status for all running threads */ void calc_sum_of_all_status(STATUS_VAR *to) { DBUG_ENTER("calc_sum_of_all_status"); /* Ensure that thread id not killed during loop */ mysql_mutex_lock(&LOCK_thread_count); // For unlink from list I_List_iterator<THD> it(threads); THD *tmp; /* Get global values as base */ *to= global_status_var; /* Add to this status from existing threads */ while ((tmp= it++)) add_to_status(to, &tmp->status_var); mysql_mutex_unlock(&LOCK_thread_count); DBUG_VOID_RETURN; } /* This is only used internally, but we need it here as a forward reference */ extern ST_SCHEMA_TABLE schema_tables[]; /** Condition pushdown used for INFORMATION_SCHEMA / SHOW queries. This structure is to implement an optimization when accessing data dictionary data in the INFORMATION_SCHEMA or SHOW commands. When the query contain a TABLE_SCHEMA or TABLE_NAME clause, narrow the search for data based on the constraints given. */ typedef struct st_lookup_field_values { /** Value of a TABLE_SCHEMA clause. Note that this value length may exceed @c NAME_LEN. @sa wild_db_value */ LEX_STRING db_value; /** Value of a TABLE_NAME clause. Note that this value length may exceed @c NAME_LEN. @sa wild_table_value */ LEX_STRING table_value; /** True when @c db_value is a LIKE clause, false when @c db_value is an '=' clause. */ bool wild_db_value; /** True when @c table_value is a LIKE clause, false when @c table_value is an '=' clause. */ bool wild_table_value; } LOOKUP_FIELD_VALUES; /* Store record to I_S table, convert HEAP table to MyISAM if necessary SYNOPSIS schema_table_store_record() thd thread handler table Information schema table to be updated RETURN 0 success 1 error */ bool schema_table_store_record(THD *thd, TABLE *table) { int error; if ((error= table->file->ha_write_row(table->record[0]))) { if (create_myisam_from_heap(thd, table, table->pos_in_table_list->schema_table_param, error, 0)) return 1; } return 0; } static int make_table_list(THD *thd, SELECT_LEX *sel, LEX_STRING *db_name, LEX_STRING *table_name) { Table_ident *table_ident; table_ident= new Table_ident(thd, *db_name, *table_name, 1); if (!sel->add_table_to_list(thd, table_ident, 0, 0, TL_READ, MDL_SHARED_READ)) return 1; return 0; } /** @brief Get lookup value from the part of 'WHERE' condition @details This function gets lookup value from the part of 'WHERE' condition if it's possible and fill appropriate lookup_field_vals struct field with this value. @param[in] thd thread handler @param[in] item_func part of WHERE condition @param[in] table I_S table @param[in, out] lookup_field_vals Struct which holds lookup values @return 0 success 1 error, there can be no matching records for the condition */ bool get_lookup_value(THD *thd, Item_func *item_func, TABLE_LIST *table, LOOKUP_FIELD_VALUES *lookup_field_vals) { ST_SCHEMA_TABLE *schema_table= table->schema_table; ST_FIELD_INFO *field_info= schema_table->fields_info; const char *field_name1= schema_table->idx_field1 >= 0 ? field_info[schema_table->idx_field1].field_name : ""; const char *field_name2= schema_table->idx_field2 >= 0 ? field_info[schema_table->idx_field2].field_name : ""; if (item_func->functype() == Item_func::EQ_FUNC || item_func->functype() == Item_func::EQUAL_FUNC) { int idx_field, idx_val; char tmp[MAX_FIELD_WIDTH]; String *tmp_str, str_buff(tmp, sizeof(tmp), system_charset_info); Item_field *item_field; CHARSET_INFO *cs= system_charset_info; if (item_func->arguments()[0]->type() == Item::FIELD_ITEM && item_func->arguments()[1]->const_item()) { idx_field= 0; idx_val= 1; } else if (item_func->arguments()[1]->type() == Item::FIELD_ITEM && item_func->arguments()[0]->const_item()) { idx_field= 1; idx_val= 0; } else return 0; item_field= (Item_field*) item_func->arguments()[idx_field]; if (table->table != item_field->field->table) return 0; tmp_str= item_func->arguments()[idx_val]->val_str(&str_buff); /* impossible value */ if (!tmp_str) return 1; /* Lookup value is database name */ if (!cs->coll->strnncollsp(cs, (uchar *) field_name1, strlen(field_name1), (uchar *) item_field->field_name, strlen(item_field->field_name), 0)) { thd->make_lex_string(&lookup_field_vals->db_value, tmp_str->ptr(), tmp_str->length(), FALSE); } /* Lookup value is table name */ else if (!cs->coll->strnncollsp(cs, (uchar *) field_name2, strlen(field_name2), (uchar *) item_field->field_name, strlen(item_field->field_name), 0)) { thd->make_lex_string(&lookup_field_vals->table_value, tmp_str->ptr(), tmp_str->length(), FALSE); } } return 0; } /** @brief Calculates lookup values from 'WHERE' condition @details This function calculates lookup value(database name, table name) from 'WHERE' condition if it's possible and fill lookup_field_vals struct fields with these values. @param[in] thd thread handler @param[in] cond WHERE condition @param[in] table I_S table @param[in, out] lookup_field_vals Struct which holds lookup values @return 0 success 1 error, there can be no matching records for the condition */ bool calc_lookup_values_from_cond(THD *thd, COND *cond, TABLE_LIST *table, LOOKUP_FIELD_VALUES *lookup_field_vals) { if (!cond) return 0; if (cond->type() == Item::COND_ITEM) { if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) { List_iterator<Item> li(*((Item_cond*) cond)->argument_list()); Item *item; while ((item= li++)) { if (item->type() == Item::FUNC_ITEM) { if (get_lookup_value(thd, (Item_func*)item, table, lookup_field_vals)) return 1; } else { if (calc_lookup_values_from_cond(thd, item, table, lookup_field_vals)) return 1; } } } return 0; } else if (cond->type() == Item::FUNC_ITEM && get_lookup_value(thd, (Item_func*) cond, table, lookup_field_vals)) return 1; return 0; } bool uses_only_table_name_fields(Item *item, TABLE_LIST *table) { if (item->type() == Item::FUNC_ITEM) { Item_func *item_func= (Item_func*)item; for (uint i=0; i<item_func->argument_count(); i++) { if (!uses_only_table_name_fields(item_func->arguments()[i], table)) return 0; } } else if (item->type() == Item::FIELD_ITEM) { Item_field *item_field= (Item_field*)item; CHARSET_INFO *cs= system_charset_info; ST_SCHEMA_TABLE *schema_table= table->schema_table; ST_FIELD_INFO *field_info= schema_table->fields_info; const char *field_name1= schema_table->idx_field1 >= 0 ? field_info[schema_table->idx_field1].field_name : ""; const char *field_name2= schema_table->idx_field2 >= 0 ? field_info[schema_table->idx_field2].field_name : ""; if (table->table != item_field->field->table || (cs->coll->strnncollsp(cs, (uchar *) field_name1, strlen(field_name1), (uchar *) item_field->field_name, strlen(item_field->field_name), 0) && cs->coll->strnncollsp(cs, (uchar *) field_name2, strlen(field_name2), (uchar *) item_field->field_name, strlen(item_field->field_name), 0))) return 0; } else if (item->type() == Item::REF_ITEM) return uses_only_table_name_fields(item->real_item(), table); if (item->type() == Item::SUBSELECT_ITEM && !item->const_item()) return 0; return 1; } static COND * make_cond_for_info_schema(COND *cond, TABLE_LIST *table) { if (!cond) return (COND*) 0; if (cond->type() == Item::COND_ITEM) { if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) { /* Create new top level AND item */ Item_cond_and *new_cond=new Item_cond_and; if (!new_cond) return (COND*) 0; List_iterator<Item> li(*((Item_cond*) cond)->argument_list()); Item *item; while ((item=li++)) { Item *fix= make_cond_for_info_schema(item, table); if (fix) new_cond->argument_list()->push_back(fix); } switch (new_cond->argument_list()->elements) { case 0: return (COND*) 0; case 1: return new_cond->argument_list()->head(); default: new_cond->quick_fix_field(); return new_cond; } } else { // Or list Item_cond_or *new_cond=new Item_cond_or; if (!new_cond) return (COND*) 0; List_iterator<Item> li(*((Item_cond*) cond)->argument_list()); Item *item; while ((item=li++)) { Item *fix=make_cond_for_info_schema(item, table); if (!fix) return (COND*) 0; new_cond->argument_list()->push_back(fix); } new_cond->quick_fix_field(); new_cond->top_level_item(); return new_cond; } } if (!uses_only_table_name_fields(cond, table)) return (COND*) 0; return cond; } /** @brief Calculate lookup values(database name, table name) @details This function calculates lookup values(database name, table name) from 'WHERE' condition or wild values (for 'SHOW' commands only) from LEX struct and fill lookup_field_vals struct field with these values. @param[in] thd thread handler @param[in] cond WHERE condition @param[in] tables I_S table @param[in, out] lookup_field_values Struct which holds lookup values @return 0 success 1 error, there can be no matching records for the condition */ bool get_lookup_field_values(THD *thd, COND *cond, TABLE_LIST *tables, LOOKUP_FIELD_VALUES *lookup_field_values) { LEX *lex= thd->lex; const char *wild= lex->wild ? lex->wild->ptr() : NullS; bool rc= 0; bzero((char*) lookup_field_values, sizeof(LOOKUP_FIELD_VALUES)); switch (lex->sql_command) { case SQLCOM_SHOW_DATABASES: if (wild) { thd->make_lex_string(&lookup_field_values->db_value, wild, strlen(wild), 0); lookup_field_values->wild_db_value= 1; } break; case SQLCOM_SHOW_TABLES: case SQLCOM_SHOW_TABLE_STATUS: case SQLCOM_SHOW_TRIGGERS: case SQLCOM_SHOW_EVENTS: thd->make_lex_string(&lookup_field_values->db_value, lex->select_lex.db, strlen(lex->select_lex.db), 0); if (wild) { thd->make_lex_string(&lookup_field_values->table_value, wild, strlen(wild), 0); lookup_field_values->wild_table_value= 1; } break; default: /* The "default" is for queries over I_S. All previous cases handle SHOW commands. */ rc= calc_lookup_values_from_cond(thd, cond, tables, lookup_field_values); break; } if (lower_case_table_names && !rc) { /* We can safely do in-place upgrades here since all of the above cases are allocating a new memory buffer for these strings. */ if (lookup_field_values->db_value.str && lookup_field_values->db_value.str[0]) my_casedn_str(system_charset_info, lookup_field_values->db_value.str); if (lookup_field_values->table_value.str && lookup_field_values->table_value.str[0]) my_casedn_str(system_charset_info, lookup_field_values->table_value.str); } return rc; } enum enum_schema_tables get_schema_table_idx(ST_SCHEMA_TABLE *schema_table) { return (enum enum_schema_tables) (schema_table - &schema_tables[0]); } /* Create db names list. Information schema name always is first in list SYNOPSIS make_db_list() thd thread handler files list of db names wild wild string idx_field_vals idx_field_vals->db_name contains db name or wild string with_i_schema returns 1 if we added 'IS' name to list otherwise returns 0 RETURN zero success non-zero error */ int make_db_list(THD *thd, List<LEX_STRING> *files, LOOKUP_FIELD_VALUES *lookup_field_vals, bool *with_i_schema) { LEX_STRING *i_s_name_copy= 0; i_s_name_copy= thd->make_lex_string(i_s_name_copy, INFORMATION_SCHEMA_NAME.str, INFORMATION_SCHEMA_NAME.length, TRUE); *with_i_schema= 0; if (lookup_field_vals->wild_db_value) { /* This part of code is only for SHOW DATABASES command. idx_field_vals->db_value can be 0 when we don't use LIKE clause (see also get_index_field_values() function) */ if (!lookup_field_vals->db_value.str || !wild_case_compare(system_charset_info, INFORMATION_SCHEMA_NAME.str, lookup_field_vals->db_value.str)) { *with_i_schema= 1; if (files->push_back(i_s_name_copy)) return 1; } return (find_files(thd, files, NullS, mysql_data_home, lookup_field_vals->db_value.str, 1) != FIND_FILES_OK); } /* If we have db lookup value we just add it to list and exit from the function. We don't do this for database names longer than the maximum name length. */ if (lookup_field_vals->db_value.str) { if (lookup_field_vals->db_value.length > NAME_LEN) { /* Impossible value for a database name, found in a WHERE DATABASE_NAME = 'xxx' clause. */ return 0; } if (is_infoschema_db(lookup_field_vals->db_value.str, lookup_field_vals->db_value.length)) { *with_i_schema= 1; if (files->push_back(i_s_name_copy)) return 1; return 0; } if (files->push_back(&lookup_field_vals->db_value)) return 1; return 0; } /* Create list of existing databases. It is used in case of select from information schema table */ if (files->push_back(i_s_name_copy)) return 1; *with_i_schema= 1; return (find_files(thd, files, NullS, mysql_data_home, NullS, 1) != FIND_FILES_OK); } struct st_add_schema_table { List<LEX_STRING> *files; const char *wild; }; static my_bool add_schema_table(THD *thd, plugin_ref plugin, void* p_data) { LEX_STRING *file_name= 0; st_add_schema_table *data= (st_add_schema_table *)p_data; List<LEX_STRING> *file_list= data->files; const char *wild= data->wild; ST_SCHEMA_TABLE *schema_table= plugin_data(plugin, ST_SCHEMA_TABLE *); DBUG_ENTER("add_schema_table"); if (schema_table->hidden) DBUG_RETURN(0); if (wild) { if (lower_case_table_names) { if (wild_case_compare(files_charset_info, schema_table->table_name, wild)) DBUG_RETURN(0); } else if (wild_compare(schema_table->table_name, wild, 0)) DBUG_RETURN(0); } if ((file_name= thd->make_lex_string(file_name, schema_table->table_name, strlen(schema_table->table_name), TRUE)) && !file_list->push_back(file_name)) DBUG_RETURN(0); DBUG_RETURN(1); } int schema_tables_add(THD *thd, List<LEX_STRING> *files, const char *wild) { LEX_STRING *file_name= 0; ST_SCHEMA_TABLE *tmp_schema_table= schema_tables; st_add_schema_table add_data; DBUG_ENTER("schema_tables_add"); for (; tmp_schema_table->table_name; tmp_schema_table++) { if (tmp_schema_table->hidden) continue; if (wild) { if (lower_case_table_names) { if (wild_case_compare(files_charset_info, tmp_schema_table->table_name, wild)) continue; } else if (wild_compare(tmp_schema_table->table_name, wild, 0)) continue; } if ((file_name= thd->make_lex_string(file_name, tmp_schema_table->table_name, strlen(tmp_schema_table->table_name), TRUE)) && !files->push_back(file_name)) continue; DBUG_RETURN(1); } add_data.files= files; add_data.wild= wild; if (plugin_foreach(thd, add_schema_table, MYSQL_INFORMATION_SCHEMA_PLUGIN, &add_data)) DBUG_RETURN(1); DBUG_RETURN(0); } /** @brief Create table names list @details The function creates the list of table names in database @param[in] thd thread handler @param[in] table_names List of table names in database @param[in] lex pointer to LEX struct @param[in] lookup_field_vals pointer to LOOKUP_FIELD_VALUE struct @param[in] with_i_schema TRUE means that we add I_S tables to list @param[in] db_name database name @return Operation status @retval 0 ok @retval 1 fatal error @retval 2 Not fatal error; Safe to ignore this file list */ static int make_table_name_list(THD *thd, List<LEX_STRING> *table_names, LEX *lex, LOOKUP_FIELD_VALUES *lookup_field_vals, bool with_i_schema, LEX_STRING *db_name) { char path[FN_REFLEN + 1]; build_table_filename(path, sizeof(path) - 1, db_name->str, "", "", 0); if (!lookup_field_vals->wild_table_value && lookup_field_vals->table_value.str) { if (lookup_field_vals->table_value.length > NAME_LEN) { /* Impossible value for a table name, found in a WHERE TABLE_NAME = 'xxx' clause. */ return 0; } if (with_i_schema) { LEX_STRING *name; ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, lookup_field_vals->table_value.str); if (schema_table && !schema_table->hidden) { if (!(name= thd->make_lex_string(NULL, schema_table->table_name, strlen(schema_table->table_name), TRUE)) || table_names->push_back(name)) return 1; } } else { if (table_names->push_back(&lookup_field_vals->table_value)) return 1; /* Check that table is relevant in current transaction. (used for ndb engine, see ndbcluster_find_files(), ha_ndbcluster.cc) */ (void) ha_find_files(thd, db_name->str, path, lookup_field_vals->table_value.str, 0, table_names); } return 0; } /* This call will add all matching the wildcards (if specified) IS tables to the list */ if (with_i_schema) return (schema_tables_add(thd, table_names, lookup_field_vals->table_value.str)); find_files_result res= find_files(thd, table_names, db_name->str, path, lookup_field_vals->table_value.str, 0); if (res != FIND_FILES_OK) { /* Downgrade errors about problems with database directory to warnings if this is not a 'SHOW' command. Another thread may have dropped database, and we may still have a name for that directory. */ if (res == FIND_FILES_DIR) { if (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) return 1; thd->clear_error(); return 2; } return 1; } return 0; } /** Fill I_S table with data obtained by performing full-blown table open. @param thd Thread handler. @param is_show_fields_or_keys Indicates whether it is a legacy SHOW COLUMNS or SHOW KEYS statement. @param table TABLE object for I_S table to be filled. @param schema_table I_S table description structure. @param orig_db_name Database name. @param orig_table_name Table name. @param open_tables_state_backup Open_tables_state object which is used to save/restore original status of variables related to open tables state. @param can_deadlock Indicates that deadlocks are possible due to metadata locks, so to avoid them we should not wait in case if conflicting lock is present. @retval FALSE - Success. @retval TRUE - Failure. */ static bool fill_schema_table_by_open(THD *thd, bool is_show_fields_or_keys, TABLE *table, ST_SCHEMA_TABLE *schema_table, LEX_STRING *orig_db_name, LEX_STRING *orig_table_name, Open_tables_backup *open_tables_state_backup, bool can_deadlock) { Query_arena i_s_arena(thd->mem_root, Query_arena::STMT_CONVENTIONAL_EXECUTION), backup_arena, *old_arena; LEX *old_lex= thd->lex, temp_lex, *lex; LEX_STRING db_name, table_name; TABLE_LIST *table_list; bool result= true; DBUG_ENTER("fill_schema_table_by_open"); /* When a view is opened its structures are allocated on a permanent statement arena and linked into the LEX tree for the current statement (this happens even in cases when view is handled through TEMPTABLE algorithm). To prevent this process from unnecessary hogging of memory in the permanent arena of our I_S query and to avoid damaging its LEX we use temporary arena and LEX for table/view opening. Use temporary arena instead of statement permanent arena. Also make it active arena and save original one for successive restoring. */ old_arena= thd->stmt_arena; thd->stmt_arena= &i_s_arena; thd->set_n_backup_active_arena(&i_s_arena, &backup_arena); /* Prepare temporary LEX. */ thd->lex= lex= &temp_lex; lex_start(thd); /* Disable constant subquery evaluation as we won't be locking tables. */ lex->context_analysis_only= CONTEXT_ANALYSIS_ONLY_VIEW; /* Some of process_table() functions rely on wildcard being passed from old LEX (or at least being initialized). */ lex->wild= old_lex->wild; /* Since make_table_list() might change database and table name passed to it we create copies of orig_db_name and orig_table_name here. These copies are used for make_table_list() while unaltered values are passed to process_table() functions. */ if (!thd->make_lex_string(&db_name, orig_db_name->str, orig_db_name->length, FALSE) || !thd->make_lex_string(&table_name, orig_table_name->str, orig_table_name->length, FALSE)) goto end; /* Create table list element for table to be open. Link it with the temporary LEX. The latter is required to correctly open views and produce table describing their structure. */ if (make_table_list(thd, &lex->select_lex, &db_name, &table_name)) goto end; table_list= lex->select_lex.table_list.first; if (is_show_fields_or_keys) { /* Restore thd->temporary_tables to be able to process temporary tables (only for 'show index' & 'show columns'). This should be changed when processing of temporary tables for I_S tables will be done. */ thd->temporary_tables= open_tables_state_backup->temporary_tables; } else { /* Apply optimization flags for table opening which are relevant for this I_S table. We can't do this for SHOW COLUMNS/KEYS because of backward compatibility. */ table_list->i_s_requested_object= schema_table->i_s_requested_object; } /* Let us set fake sql_command so views won't try to merge themselves into main statement. If we don't do this, SELECT * from information_schema.xxxx will cause problems. SQLCOM_SHOW_FIELDS is used because it satisfies 'only_view_structure()'. */ lex->sql_command= SQLCOM_SHOW_FIELDS; result= open_normal_and_derived_tables(thd, table_list, (MYSQL_OPEN_IGNORE_FLUSH | MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL | (can_deadlock ? MYSQL_OPEN_FAIL_ON_MDL_CONFLICT : 0))); /* Restore old value of sql_command back as it is being looked at in process_table() function. */ lex->sql_command= old_lex->sql_command; DEBUG_SYNC(thd, "after_open_table_ignore_flush"); /* XXX: show_table_list has a flag i_is_requested, and when it's set, open_normal_and_derived_tables() can return an error without setting an error message in THD, which is a hack. This is why we have to check for res, then for thd->is_error() and only then for thd->main_da.sql_errno(). Again we don't do this for SHOW COLUMNS/KEYS because of backward compatibility. */ if (!is_show_fields_or_keys && result && thd->is_error() && thd->stmt_da->sql_errno() == ER_NO_SUCH_TABLE) { /* Hide error for a non-existing table. For example, this error can occur when we use a where condition with a db name and table, but the table does not exist. */ result= false; thd->clear_error(); } else { result= schema_table->process_table(thd, table_list, table, result, orig_db_name, orig_table_name); } end: lex->unit.cleanup(); /* Restore original LEX value, statement's arena and THD arena values. */ lex_end(thd->lex); // Free items, before restoring backup_arena below. DBUG_ASSERT(i_s_arena.free_list == NULL); thd->free_items(); /* For safety reset list of open temporary tables before closing all tables open within this Open_tables_state. */ thd->temporary_tables= NULL; close_thread_tables(thd); /* Release metadata lock we might have acquired. See comment in fill_schema_table_from_frm() for details. */ thd->mdl_context.rollback_to_savepoint(open_tables_state_backup->mdl_system_tables_svp); thd->lex= old_lex; thd->stmt_arena= old_arena; thd->restore_active_arena(&i_s_arena, &backup_arena); DBUG_RETURN(result); } /** @brief Fill I_S table for SHOW TABLE NAMES commands @param[in] thd thread handler @param[in] table TABLE struct for I_S table @param[in] db_name database name @param[in] table_name table name @param[in] with_i_schema I_S table if TRUE @return Operation status @retval 0 success @retval 1 error */ static int fill_schema_table_names(THD *thd, TABLE *table, LEX_STRING *db_name, LEX_STRING *table_name, bool with_i_schema, bool need_table_type) { /* Avoid opening FRM files if table type is not needed. */ if (need_table_type) { if (with_i_schema) { table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), system_charset_info); } else { enum legacy_db_type not_used; char path[FN_REFLEN + 1]; (void) build_table_filename(path, sizeof(path) - 1, db_name->str, table_name->str, reg_ext, 0); switch (dd_frm_type(thd, path, &not_used)) { case FRMTYPE_ERROR: table->field[3]->store(STRING_WITH_LEN("ERROR"), system_charset_info); break; case FRMTYPE_TABLE: table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), system_charset_info); break; case FRMTYPE_VIEW: table->field[3]->store(STRING_WITH_LEN("VIEW"), system_charset_info); break; default: DBUG_ASSERT(0); } if (thd->is_error() && thd->stmt_da->sql_errno() == ER_NO_SUCH_TABLE) { thd->clear_error(); return 0; } } } if (schema_table_store_record(thd, table)) return 1; return 0; } /** @brief Get open table method @details The function calculates the method which will be used for table opening: SKIP_OPEN_TABLE - do not open table OPEN_FRM_ONLY - open FRM file only OPEN_FULL_TABLE - open FRM, data, index files @param[in] tables I_S table table_list @param[in] schema_table I_S table struct @param[in] schema_table_idx I_S table index @return return a set of flags @retval SKIP_OPEN_TABLE | OPEN_FRM_ONLY | OPEN_FULL_TABLE */ uint get_table_open_method(TABLE_LIST *tables, ST_SCHEMA_TABLE *schema_table, enum enum_schema_tables schema_table_idx) { /* determine which method will be used for table opening */ if (schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE) { Field **ptr, *field; int table_open_method= 0, field_indx= 0; uint star_table_open_method= OPEN_FULL_TABLE; bool used_star= true; // true if '*' is used in select for (ptr=tables->table->field; (field= *ptr) ; ptr++) { star_table_open_method= min(star_table_open_method, schema_table->fields_info[field_indx].open_method); if (bitmap_is_set(tables->table->read_set, field->field_index)) { used_star= false; table_open_method|= schema_table->fields_info[field_indx].open_method; } field_indx++; } if (used_star) return star_table_open_method; return table_open_method; } /* I_S tables which use get_all_tables but can not be optimized */ return (uint) OPEN_FULL_TABLE; } /** Try acquire high priority share metadata lock on a table (with optional wait for conflicting locks to go away). @param thd Thread context. @param mdl_request Pointer to memory to be used for MDL_request object for a lock request. @param table Table list element for the table @param can_deadlock Indicates that deadlocks are possible due to metadata locks, so to avoid them we should not wait in case if conflicting lock is present. @note This is an auxiliary function to be used in cases when we want to access table's description by looking up info in TABLE_SHARE without going through full-blown table open. @note This function assumes that there are no other metadata lock requests in the current metadata locking context. @retval FALSE No error, if lock was obtained TABLE_LIST::mdl_request::ticket is set to non-NULL value. @retval TRUE Some error occured (probably thread was killed). */ static bool try_acquire_high_prio_shared_mdl_lock(THD *thd, TABLE_LIST *table, bool can_deadlock) { bool error; table->mdl_request.init(MDL_key::TABLE, table->db, table->table_name, MDL_SHARED_HIGH_PRIO, MDL_TRANSACTION); if (can_deadlock) { /* When .FRM is being open in order to get data for an I_S table, we might have some tables not only open but also locked. E.g. this happens when a SHOW or I_S statement is run under LOCK TABLES or inside a stored function. By waiting for the conflicting metadata lock to go away we might create a deadlock which won't entirely belong to the MDL subsystem and thus won't be detectable by this subsystem's deadlock detector. To avoid such situation, when there are other locked tables, we prefer not to wait on a conflicting lock. */ error= thd->mdl_context.try_acquire_lock(&table->mdl_request); } else error= thd->mdl_context.acquire_lock(&table->mdl_request, thd->variables.lock_wait_timeout); return error; } /** @brief Fill I_S table with data from FRM file only @param[in] thd thread handler @param[in] table TABLE struct for I_S table @param[in] schema_table I_S table struct @param[in] db_name database name @param[in] table_name table name @param[in] schema_table_idx I_S table index @param[in] open_tables_state_backup Open_tables_state object which is used to save/restore original state of metadata locks. @param[in] can_deadlock Indicates that deadlocks are possible due to metadata locks, so to avoid them we should not wait in case if conflicting lock is present. @return Operation status @retval 0 Table is processed and we can continue with new table @retval 1 It's view and we have to use open_tables function for this table */ static int fill_schema_table_from_frm(THD *thd, TABLE_LIST *tables, ST_SCHEMA_TABLE *schema_table, LEX_STRING *db_name, LEX_STRING *table_name, enum enum_schema_tables schema_table_idx, Open_tables_backup *open_tables_state_backup, bool can_deadlock) { TABLE *table= tables->table; TABLE_SHARE *share; TABLE tbl; TABLE_LIST table_list; uint res= 0; int not_used; my_hash_value_type hash_value; char key[MAX_DBKEY_LENGTH]; uint key_length; char db_name_buff[NAME_LEN + 1], table_name_buff[NAME_LEN + 1]; bzero((char*) &table_list, sizeof(TABLE_LIST)); bzero((char*) &tbl, sizeof(TABLE)); DBUG_ASSERT(db_name->length <= NAME_LEN); DBUG_ASSERT(table_name->length <= NAME_LEN); if (lower_case_table_names) { /* In lower_case_table_names > 0 metadata locking and table definition cache subsystems require normalized (lowercased) database and table names as input. */ strmov(db_name_buff, db_name->str); strmov(table_name_buff, table_name->str); my_casedn_str(files_charset_info, db_name_buff); my_casedn_str(files_charset_info, table_name_buff); table_list.db= db_name_buff; table_list.table_name= table_name_buff; } else { table_list.table_name= table_name->str; table_list.db= db_name->str; } /* TODO: investigate if in this particular situation we can get by simply obtaining internal lock of the data-dictionary instead of obtaining full-blown metadata lock. */ if (try_acquire_high_prio_shared_mdl_lock(thd, &table_list, can_deadlock)) { /* Some error occured (most probably we have been killed while waiting for conflicting locks to go away), let the caller to handle the situation. */ return 1; } if (! table_list.mdl_request.ticket) { /* We are in situation when we have encountered conflicting metadata lock and deadlocks can occur due to waiting for it to go away. So instead of waiting skip this table with an appropriate warning. */ DBUG_ASSERT(can_deadlock); push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_I_S_SKIPPED_TABLE, ER(ER_WARN_I_S_SKIPPED_TABLE), table_list.db, table_list.table_name); return 0; } if (schema_table->i_s_requested_object & OPEN_TRIGGER_ONLY) { init_sql_alloc(&tbl.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); if (!Table_triggers_list::check_n_load(thd, db_name->str, table_name->str, &tbl, 1)) { table_list.table= &tbl; res= schema_table->process_table(thd, &table_list, table, res, db_name, table_name); delete tbl.triggers; } free_root(&tbl.mem_root, MYF(0)); goto end; } key_length= create_table_def_key(thd, key, &table_list, 0); hash_value= my_calc_hash(&table_def_cache, (uchar*) key, key_length); mysql_mutex_lock(&LOCK_open); share= get_table_share(thd, &table_list, key, key_length, OPEN_VIEW, &not_used, hash_value); if (!share) { res= 0; goto end_unlock; } if (share->is_view) { if (schema_table->i_s_requested_object & OPEN_TABLE_ONLY) { /* skip view processing */ res= 0; goto end_share; } else if (schema_table->i_s_requested_object & OPEN_VIEW_FULL) { /* tell get_all_tables() to fall back to open_normal_and_derived_tables() */ res= 1; goto end_share; } } if (share->is_view) { if (open_new_frm(thd, share, table_name->str, (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE | HA_GET_INDEX | HA_TRY_READ_ONLY), READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD | OPEN_VIEW_NO_PARSE, thd->open_options, &tbl, &table_list, thd->mem_root)) goto end_share; table_list.view= (LEX*) share->is_view; res= schema_table->process_table(thd, &table_list, table, res, db_name, table_name); goto end_share; } if (!open_table_from_share(thd, share, table_name->str, 0, (EXTRA_RECORD | OPEN_FRM_FILE_ONLY), thd->open_options, &tbl, FALSE)) { tbl.s= share; table_list.table= &tbl; table_list.view= (LEX*) share->is_view; res= schema_table->process_table(thd, &table_list, table, res, db_name, table_name); free_root(&tbl.mem_root, MYF(0)); my_free((void *) tbl.alias); } end_share: release_table_share(share); end_unlock: mysql_mutex_unlock(&LOCK_open); end: /* Release metadata lock we might have acquired. Without this step metadata locks acquired for each table processed will be accumulated. In situation when a lot of tables are processed by I_S query this will result in transaction with too many metadata locks. As result performance of acquisition of new lock will suffer. Of course, the fact that we don't hold metadata lock on tables which were processed till the end of I_S query makes execution less isolated from concurrent DDL. Consequently one might get 'dirty' results from such a query. But we have never promised serializability of I_S queries anyway. We don't have any tables open since we took backup, so rolling back to savepoint is safe. */ DBUG_ASSERT(thd->open_tables == NULL); thd->mdl_context.rollback_to_savepoint(open_tables_state_backup->mdl_system_tables_svp); thd->clear_error(); return res; } /** Trigger_error_handler is intended to intercept and silence SQL conditions that might happen during trigger loading for SHOW statements. The potential SQL conditions are: - ER_PARSE_ERROR -- this error is thrown if a trigger definition file is damaged or contains invalid CREATE TRIGGER statement. That should not happen in normal life. - ER_TRG_NO_DEFINER -- this warning is thrown when we're loading a trigger created/imported in/from the version of MySQL, which does not support trigger definers. - ER_TRG_NO_CREATION_CTX -- this warning is thrown when we're loading a trigger created/imported in/from the version of MySQL, which does not support trigger creation contexts. */ class Trigger_error_handler : public Internal_error_handler { public: bool handle_condition(THD *thd, uint sql_errno, const char* sqlstate, MYSQL_ERROR::enum_warning_level level, const char* msg, MYSQL_ERROR ** cond_hdl) { if (sql_errno == ER_PARSE_ERROR || sql_errno == ER_TRG_NO_DEFINER || sql_errno == ER_TRG_NO_CREATION_CTX) return true; return false; } }; /** @brief Fill I_S tables whose data are retrieved from frm files and storage engine @details The information schema tables are internally represented as temporary tables that are filled at query execution time. Those I_S tables whose data are retrieved from frm files and storage engine are filled by the function get_all_tables(). @param[in] thd thread handler @param[in] tables I_S table @param[in] cond 'WHERE' condition @return Operation status @retval 0 success @retval 1 error */ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond) { LEX *lex= thd->lex; TABLE *table= tables->table; SELECT_LEX *lsel= tables->schema_select_lex; ST_SCHEMA_TABLE *schema_table= tables->schema_table; LOOKUP_FIELD_VALUES lookup_field_vals; LEX_STRING *db_name, *table_name; bool with_i_schema; enum enum_schema_tables schema_table_idx; List<LEX_STRING> db_names; List_iterator_fast<LEX_STRING> it(db_names); COND *partial_cond= 0; int error= 1; Open_tables_backup open_tables_state_backup; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *sctx= thd->security_ctx; #endif uint table_open_method; bool can_deadlock; DBUG_ENTER("get_all_tables"); /* In cases when SELECT from I_S table being filled by this call is part of statement which also uses other tables or is being executed under LOCK TABLES or is part of transaction which also uses other tables waiting for metadata locks which happens below might result in deadlocks. To avoid them we don't wait if conflicting metadata lock is encountered and skip table with emitting an appropriate warning. */ can_deadlock= thd->mdl_context.has_locks(); /* We should not introduce deadlocks even if we already have some tables open and locked, since we won't lock tables which we will open and will ignore pending exclusive metadata locks for these tables by using high-priority requests for shared metadata locks. */ thd->reset_n_backup_open_tables_state(&open_tables_state_backup); schema_table_idx= get_schema_table_idx(schema_table); tables->table_open_method= table_open_method= get_table_open_method(tables, schema_table, schema_table_idx); DBUG_PRINT("open_method", ("%d", tables->table_open_method)); /* this branch processes SHOW FIELDS, SHOW INDEXES commands. see sql_parse.cc, prepare_schema_table() function where this values are initialized */ if (lsel && lsel->table_list.first) { LEX_STRING db_name, table_name; db_name.str= lsel->table_list.first->db; db_name.length= lsel->table_list.first->db_length; table_name.str= lsel->table_list.first->table_name; table_name.length= lsel->table_list.first->table_name_length; error= fill_schema_table_by_open(thd, TRUE, table, schema_table, &db_name, &table_name, &open_tables_state_backup, can_deadlock); goto err; } if (get_lookup_field_values(thd, cond, tables, &lookup_field_vals)) { error= 0; goto err; } DBUG_PRINT("INDEX VALUES",("db_name='%s', table_name='%s'", STR_OR_NIL(lookup_field_vals.db_value.str), STR_OR_NIL(lookup_field_vals.table_value.str))); if (!lookup_field_vals.wild_db_value && !lookup_field_vals.wild_table_value) { /* if lookup value is empty string then it's impossible table name or db name */ if ((lookup_field_vals.db_value.str && !lookup_field_vals.db_value.str[0]) || (lookup_field_vals.table_value.str && !lookup_field_vals.table_value.str[0])) { error= 0; goto err; } } if (lookup_field_vals.db_value.length && !lookup_field_vals.wild_db_value) tables->has_db_lookup_value= TRUE; if (lookup_field_vals.table_value.length && !lookup_field_vals.wild_table_value) tables->has_table_lookup_value= TRUE; if (tables->has_db_lookup_value && tables->has_table_lookup_value) partial_cond= 0; else partial_cond= make_cond_for_info_schema(cond, tables); if (lex->describe) { /* EXPLAIN SELECT */ error= 0; goto err; } if (make_db_list(thd, &db_names, &lookup_field_vals, &with_i_schema)) goto err; it.rewind(); /* To get access to new elements in basis list */ while ((db_name= it++)) { DBUG_ASSERT(db_name->length <= NAME_LEN); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (!(check_access(thd, SELECT_ACL, db_name->str, &thd->col_access, NULL, 0, 1) || (!thd->col_access && check_grant_db(thd, db_name->str))) || sctx->master_access & (DB_ACLS | SHOW_DB_ACL) || acl_get(sctx->get_host()->ptr(), sctx->get_ip()->ptr(), sctx->priv_user, db_name->str, 0)) #endif { List<LEX_STRING> table_names; int res= make_table_name_list(thd, &table_names, lex, &lookup_field_vals, with_i_schema, db_name); if (res == 2) /* Not fatal error, continue */ continue; if (res) goto err; List_iterator_fast<LEX_STRING> it_files(table_names); while ((table_name= it_files++)) { DBUG_ASSERT(table_name->length <= NAME_LEN); restore_record(table, s->default_values); table->field[schema_table->idx_field1]-> store(db_name->str, db_name->length, system_charset_info); table->field[schema_table->idx_field2]-> store(table_name->str, table_name->length, system_charset_info); if (!partial_cond || partial_cond->val_int()) { /* If table is I_S.tables and open_table_method is 0 (eg SKIP_OPEN) we can skip table opening and we don't have lookup value for table name or lookup value is wild string(table name list is already created by make_table_name_list() function). */ if (!table_open_method && schema_table_idx == SCH_TABLES && (!lookup_field_vals.table_value.length || lookup_field_vals.wild_table_value)) { table->field[0]->store(STRING_WITH_LEN("def"), system_charset_info); if (schema_table_store_record(thd, table)) goto err; /* Out of space in temporary table */ continue; } /* SHOW TABLE NAMES command */ if (schema_table_idx == SCH_TABLE_NAMES) { if (fill_schema_table_names(thd, tables->table, db_name, table_name, with_i_schema, lex->verbose)) continue; } else { if (!(table_open_method & ~OPEN_FRM_ONLY) && !with_i_schema) { /* Here we need to filter out warnings, which can happen during loading of triggers in fill_schema_table_from_frm(), because we don't need those warnings to pollute output of SELECT from I_S / SHOW-statements. */ Trigger_error_handler err_handler; thd->push_internal_handler(&err_handler); int res= fill_schema_table_from_frm(thd, tables, schema_table, db_name, table_name, schema_table_idx, &open_tables_state_backup, can_deadlock); thd->pop_internal_handler(); if (!res) continue; } DEBUG_SYNC(thd, "before_open_in_get_all_tables"); if (fill_schema_table_by_open(thd, FALSE, table, schema_table, db_name, table_name, &open_tables_state_backup, can_deadlock)) goto err; } } } /* If we have information schema its always the first table and only the first table. Reset for other tables. */ with_i_schema= 0; } } error= 0; err: thd->restore_backup_open_tables_state(&open_tables_state_backup); DBUG_RETURN(error); } bool store_schema_shemata(THD* thd, TABLE *table, LEX_STRING *db_name, CHARSET_INFO *cs) { restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), system_charset_info); table->field[1]->store(db_name->str, db_name->length, system_charset_info); table->field[2]->store(cs->csname, strlen(cs->csname), system_charset_info); table->field[3]->store(cs->name, strlen(cs->name), system_charset_info); return schema_table_store_record(thd, table); } int fill_schema_schemata(THD *thd, TABLE_LIST *tables, COND *cond) { /* TODO: fill_schema_shemata() is called when new client is connected. Returning error status in this case leads to client hangup. */ LOOKUP_FIELD_VALUES lookup_field_vals; List<LEX_STRING> db_names; LEX_STRING *db_name; bool with_i_schema; HA_CREATE_INFO create; TABLE *table= tables->table; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *sctx= thd->security_ctx; #endif DBUG_ENTER("fill_schema_shemata"); if (get_lookup_field_values(thd, cond, tables, &lookup_field_vals)) DBUG_RETURN(0); DBUG_PRINT("INDEX VALUES",("db_name='%s', table_name='%s'", lookup_field_vals.db_value.str, lookup_field_vals.table_value.str)); if (make_db_list(thd, &db_names, &lookup_field_vals, &with_i_schema)) DBUG_RETURN(1); /* If we have lookup db value we should check that the database exists */ if(lookup_field_vals.db_value.str && !lookup_field_vals.wild_db_value && !with_i_schema) { char path[FN_REFLEN+16]; uint path_len; MY_STAT stat_info; if (!lookup_field_vals.db_value.str[0]) DBUG_RETURN(0); path_len= build_table_filename(path, sizeof(path) - 1, lookup_field_vals.db_value.str, "", "", 0); path[path_len-1]= 0; if (!mysql_file_stat(key_file_misc, path, &stat_info, MYF(0))) DBUG_RETURN(0); } List_iterator_fast<LEX_STRING> it(db_names); while ((db_name=it++)) { DBUG_ASSERT(db_name->length <= NAME_LEN); if (with_i_schema) // information schema name is always first in list { if (store_schema_shemata(thd, table, db_name, system_charset_info)) DBUG_RETURN(1); with_i_schema= 0; continue; } #ifndef NO_EMBEDDED_ACCESS_CHECKS if (sctx->master_access & (DB_ACLS | SHOW_DB_ACL) || acl_get(sctx->get_host()->ptr(), sctx->get_ip()->ptr(), sctx->priv_user, db_name->str, 0) || !check_grant_db(thd, db_name->str)) #endif { load_db_opt_by_name(thd, db_name->str, &create); if (store_schema_shemata(thd, table, db_name, create.default_table_charset)) DBUG_RETURN(1); } } DBUG_RETURN(0); } static int get_schema_tables_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { const char *tmp_buff; MYSQL_TIME time; int info_error= 0; CHARSET_INFO *cs= system_charset_info; DBUG_ENTER("get_schema_tables_record"); restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); if (res) { /* There was a table open error, so set the table type and return */ if (tables->view) table->field[3]->store(STRING_WITH_LEN("VIEW"), cs); else if (tables->schema_table) table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), cs); else table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), cs); goto err; } if (tables->view) { table->field[3]->store(STRING_WITH_LEN("VIEW"), cs); table->field[20]->store(STRING_WITH_LEN("VIEW"), cs); } else { char option_buff[350],*ptr; TABLE *show_table= tables->table; TABLE_SHARE *share= show_table->s; handler *file= show_table->file; handlerton *tmp_db_type= share->db_type(); #ifdef WITH_PARTITION_STORAGE_ENGINE bool is_partitioned= FALSE; #endif if (share->tmp_table == SYSTEM_TMP_TABLE) table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), cs); else if (share->tmp_table) table->field[3]->store(STRING_WITH_LEN("LOCAL TEMPORARY"), cs); else table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), cs); for (int i= 4; i < 20; i++) { if (i == 7 || (i > 12 && i < 17) || i == 18) continue; table->field[i]->set_notnull(); } /* Collect table info from the table share */ #ifdef WITH_PARTITION_STORAGE_ENGINE if (share->db_type() == partition_hton && share->partition_info_str_len) { tmp_db_type= share->default_part_db_type; is_partitioned= TRUE; } #endif tmp_buff= (char *) ha_resolve_storage_engine_name(tmp_db_type); table->field[4]->store(tmp_buff, strlen(tmp_buff), cs); table->field[5]->store((longlong) share->frm_version, TRUE); ptr=option_buff; if (share->min_rows) { ptr=strmov(ptr," min_rows="); ptr=longlong10_to_str(share->min_rows,ptr,10); } if (share->max_rows) { ptr=strmov(ptr," max_rows="); ptr=longlong10_to_str(share->max_rows,ptr,10); } if (share->avg_row_length) { ptr=strmov(ptr," avg_row_length="); ptr=longlong10_to_str(share->avg_row_length,ptr,10); } if (share->db_create_options & HA_OPTION_PACK_KEYS) ptr=strmov(ptr," pack_keys=1"); if (share->db_create_options & HA_OPTION_NO_PACK_KEYS) ptr=strmov(ptr," pack_keys=0"); /* We use CHECKSUM, instead of TABLE_CHECKSUM, for backward compability */ if (share->db_create_options & HA_OPTION_CHECKSUM) ptr=strmov(ptr," checksum=1"); if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE) ptr=strmov(ptr," delay_key_write=1"); if (share->row_type != ROW_TYPE_DEFAULT) ptr=strxmov(ptr, " row_format=", ha_row_type[(uint) share->row_type], NullS); if (share->key_block_size) { ptr= strmov(ptr, " KEY_BLOCK_SIZE="); ptr= longlong10_to_str(share->key_block_size, ptr, 10); } #ifdef WITH_PARTITION_STORAGE_ENGINE if (is_partitioned) ptr= strmov(ptr, " partitioned"); #endif table->field[19]->store(option_buff+1, (ptr == option_buff ? 0 : (uint) (ptr-option_buff)-1), cs); tmp_buff= (share->table_charset ? share->table_charset->name : "default"); table->field[17]->store(tmp_buff, strlen(tmp_buff), cs); if (share->comment.str) table->field[20]->store(share->comment.str, share->comment.length, cs); /* Collect table info from the storage engine */ if(file) { /* If info() fails, then there's nothing else to do */ if ((info_error= file->info(HA_STATUS_VARIABLE | HA_STATUS_TIME | HA_STATUS_VARIABLE_EXTRA | HA_STATUS_AUTO)) != 0) goto err; enum row_type row_type = file->get_row_type(); switch (row_type) { case ROW_TYPE_NOT_USED: case ROW_TYPE_DEFAULT: tmp_buff= ((share->db_options_in_use & HA_OPTION_COMPRESS_RECORD) ? "Compressed" : (share->db_options_in_use & HA_OPTION_PACK_RECORD) ? "Dynamic" : "Fixed"); break; case ROW_TYPE_FIXED: tmp_buff= "Fixed"; break; case ROW_TYPE_DYNAMIC: tmp_buff= "Dynamic"; break; case ROW_TYPE_COMPRESSED: tmp_buff= "Compressed"; break; case ROW_TYPE_REDUNDANT: tmp_buff= "Redundant"; break; case ROW_TYPE_COMPACT: tmp_buff= "Compact"; break; case ROW_TYPE_PAGE: tmp_buff= "Paged"; break; } table->field[6]->store(tmp_buff, strlen(tmp_buff), cs); if (!tables->schema_table) { table->field[7]->store((longlong) file->stats.records, TRUE); table->field[7]->set_notnull(); } table->field[8]->store((longlong) file->stats.mean_rec_length, TRUE); table->field[9]->store((longlong) file->stats.data_file_length, TRUE); if (file->stats.max_data_file_length) { table->field[10]->store((longlong) file->stats.max_data_file_length, TRUE); } table->field[11]->store((longlong) file->stats.index_file_length, TRUE); table->field[12]->store((longlong) file->stats.delete_length, TRUE); if (show_table->found_next_number_field) { table->field[13]->store((longlong) file->stats.auto_increment_value, TRUE); table->field[13]->set_notnull(); } if (file->stats.create_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t) file->stats.create_time); table->field[14]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[14]->set_notnull(); } if (file->stats.update_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t) file->stats.update_time); table->field[15]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[15]->set_notnull(); } if (file->stats.check_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t) file->stats.check_time); table->field[16]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[16]->set_notnull(); } if (file->ha_table_flags() & (ulong) HA_HAS_CHECKSUM) { table->field[18]->store((longlong) file->checksum(), TRUE); table->field[18]->set_notnull(); } } } err: if (res || info_error) { /* If an error was encountered, push a warning, set the TABLE COMMENT column with the error text, and clear the error so that the operation can continue. */ const char *error= thd->is_error() ? thd->stmt_da->message() : ""; table->field[20]->store(error, strlen(error), cs); if (thd->is_error()) { push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); } } DBUG_RETURN(schema_table_store_record(thd, table)); } /** @brief Store field characteristics into appropriate I_S table columns @param[in] table I_S table @param[in] field processed field @param[in] cs I_S table charset @param[in] offset offset from beginning of table to DATE_TYPE column in I_S table @return void */ void store_column_type(TABLE *table, Field *field, CHARSET_INFO *cs, uint offset) { bool is_blob; int decimals, field_length; const char *tmp_buff; char column_type_buff[MAX_FIELD_WIDTH]; String column_type(column_type_buff, sizeof(column_type_buff), cs); field->sql_type(column_type); /* DTD_IDENTIFIER column */ table->field[offset + 7]->store(column_type.ptr(), column_type.length(), cs); table->field[offset + 7]->set_notnull(); /* DATA_TYPE column: MySQL column type has the following format: base_type [(dimension)] [unsigned] [zerofill]. For DATA_TYPE column we extract only base type. */ tmp_buff= strchr(column_type.ptr(), '('); if (!tmp_buff) /* if there is no dimention part then check the presence of [unsigned] [zerofill] attributes and cut them of if exist. */ tmp_buff= strchr(column_type.ptr(), ' '); table->field[offset]->store(column_type.ptr(), (tmp_buff ? tmp_buff - column_type.ptr() : column_type.length()), cs); is_blob= (field->type() == MYSQL_TYPE_BLOB); if (field->has_charset() || is_blob || field->real_type() == MYSQL_TYPE_VARCHAR || // For varbinary type field->real_type() == MYSQL_TYPE_STRING) // For binary type { uint32 octet_max_length= field->max_display_length(); if (is_blob && octet_max_length != (uint32) 4294967295U) octet_max_length /= field->charset()->mbmaxlen; longlong char_max_len= is_blob ? (longlong) octet_max_length / field->charset()->mbminlen : (longlong) octet_max_length / field->charset()->mbmaxlen; /* CHARACTER_MAXIMUM_LENGTH column*/ table->field[offset + 1]->store(char_max_len, TRUE); table->field[offset + 1]->set_notnull(); /* CHARACTER_OCTET_LENGTH column */ table->field[offset + 2]->store((longlong) octet_max_length, TRUE); table->field[offset + 2]->set_notnull(); } /* Calculate field_length and decimals. They are set to -1 if they should not be set (we should return NULL) */ decimals= field->decimals(); switch (field->type()) { case MYSQL_TYPE_NEWDECIMAL: field_length= ((Field_new_decimal*) field)->precision; break; case MYSQL_TYPE_DECIMAL: field_length= field->field_length - (decimals ? 2 : 1); break; case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24: field_length= field->max_display_length() - 1; break; case MYSQL_TYPE_LONGLONG: field_length= field->max_display_length() - ((field->flags & UNSIGNED_FLAG) ? 0 : 1); break; case MYSQL_TYPE_BIT: field_length= field->max_display_length(); decimals= -1; // return NULL break; case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: field_length= field->field_length; if (decimals == NOT_FIXED_DEC) decimals= -1; // return NULL break; default: field_length= decimals= -1; break; } /* NUMERIC_PRECISION column */ if (field_length >= 0) { table->field[offset + 3]->store((longlong) field_length, TRUE); table->field[offset + 3]->set_notnull(); } /* NUMERIC_SCALE column */ if (decimals >= 0) { table->field[offset + 4]->store((longlong) decimals, TRUE); table->field[offset + 4]->set_notnull(); } if (field->has_charset()) { /* CHARACTER_SET_NAME column*/ tmp_buff= field->charset()->csname; table->field[offset + 5]->store(tmp_buff, strlen(tmp_buff), cs); table->field[offset + 5]->set_notnull(); /* COLLATION_NAME column */ tmp_buff= field->charset()->name; table->field[offset + 6]->store(tmp_buff, strlen(tmp_buff), cs); table->field[offset + 6]->set_notnull(); } } static int get_schema_column_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { LEX *lex= thd->lex; const char *wild= lex->wild ? lex->wild->ptr() : NullS; CHARSET_INFO *cs= system_charset_info; TABLE *show_table; Field **ptr, *field, *timestamp_field; int count; DBUG_ENTER("get_schema_column_record"); if (res) { if (lex->sql_command != SQLCOM_SHOW_FIELDS) { /* I.e. we are in SELECT FROM INFORMATION_SCHEMA.COLUMS rather than in SHOW COLUMNS */ if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); res= 0; } DBUG_RETURN(res); } show_table= tables->table; count= 0; ptr= show_table->field; timestamp_field= show_table->timestamp_field; show_table->use_all_columns(); // Required for default restore_record(show_table, s->default_values); for (; (field= *ptr) ; ptr++) { uchar *pos; char tmp[MAX_FIELD_WIDTH]; String type(tmp,sizeof(tmp), system_charset_info); DEBUG_SYNC(thd, "get_schema_column"); if (wild && wild[0] && wild_case_compare(system_charset_info, field->field_name,wild)) continue; count++; /* Get default row, with all NULL fields set to NULL */ restore_record(table, s->default_values); #ifndef NO_EMBEDDED_ACCESS_CHECKS uint col_access; check_access(thd,SELECT_ACL, db_name->str, &tables->grant.privilege, 0, 0, test(tables->schema_table)); col_access= get_column_grant(thd, &tables->grant, db_name->str, table_name->str, field->field_name) & COL_ACLS; if (!tables->schema_table && !col_access) continue; char *end= tmp; for (uint bitnr=0; col_access ; col_access>>=1,bitnr++) { if (col_access & 1) { *end++=','; end=strmov(end,grant_types.type_names[bitnr]); } } table->field[17]->store(tmp+1,end == tmp ? 0 : (uint) (end-tmp-1), cs); #endif table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); table->field[3]->store(field->field_name, strlen(field->field_name), cs); table->field[4]->store((longlong) count, TRUE); field->sql_type(type); table->field[14]->store(type.ptr(), type.length(), cs); if (get_field_default_value(thd, timestamp_field, field, &type, 0)) { table->field[5]->store(type.ptr(), type.length(), cs); table->field[5]->set_notnull(); } pos=(uchar*) ((field->flags & NOT_NULL_FLAG) ? "NO" : "YES"); table->field[6]->store((const char*) pos, strlen((const char*) pos), cs); store_column_type(table, field, cs, 7); pos=(uchar*) ((field->flags & PRI_KEY_FLAG) ? "PRI" : (field->flags & UNIQUE_KEY_FLAG) ? "UNI" : (field->flags & MULTIPLE_KEY_FLAG) ? "MUL":""); table->field[15]->store((const char*) pos, strlen((const char*) pos), cs); if (field->unireg_check == Field::NEXT_NUMBER) table->field[16]->store(STRING_WITH_LEN("auto_increment"), cs); if (timestamp_field == field && field->unireg_check != Field::TIMESTAMP_DN_FIELD) table->field[16]->store(STRING_WITH_LEN("on update CURRENT_TIMESTAMP"), cs); table->field[18]->store(field->comment.str, field->comment.length, cs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } DBUG_RETURN(0); } int fill_schema_charsets(THD *thd, TABLE_LIST *tables, COND *cond) { CHARSET_INFO **cs; const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; TABLE *table= tables->table; CHARSET_INFO *scs= system_charset_info; for (cs= all_charsets ; cs < all_charsets + array_elements(all_charsets) ; cs++) { CHARSET_INFO *tmp_cs= cs[0]; if (tmp_cs && (tmp_cs->state & MY_CS_PRIMARY) && (tmp_cs->state & MY_CS_AVAILABLE) && !(tmp_cs->state & MY_CS_HIDDEN) && !(wild && wild[0] && wild_case_compare(scs, tmp_cs->csname,wild))) { const char *comment; restore_record(table, s->default_values); table->field[0]->store(tmp_cs->csname, strlen(tmp_cs->csname), scs); table->field[1]->store(tmp_cs->name, strlen(tmp_cs->name), scs); comment= tmp_cs->comment ? tmp_cs->comment : ""; table->field[2]->store(comment, strlen(comment), scs); table->field[3]->store((longlong) tmp_cs->mbmaxlen, TRUE); if (schema_table_store_record(thd, table)) return 1; } } return 0; } static my_bool iter_schema_engines(THD *thd, plugin_ref plugin, void *ptable) { TABLE *table= (TABLE *) ptable; handlerton *hton= plugin_data(plugin, handlerton *); const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; CHARSET_INFO *scs= system_charset_info; handlerton *default_type= ha_default_handlerton(thd); DBUG_ENTER("iter_schema_engines"); /* Disabled plugins */ if (plugin_state(plugin) != PLUGIN_IS_READY) { struct st_mysql_plugin *plug= plugin_decl(plugin); if (!(wild && wild[0] && wild_case_compare(scs, plug->name,wild))) { restore_record(table, s->default_values); table->field[0]->store(plug->name, strlen(plug->name), scs); table->field[1]->store(C_STRING_WITH_LEN("NO"), scs); table->field[2]->store(plug->descr, strlen(plug->descr), scs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } DBUG_RETURN(0); } if (!(hton->flags & HTON_HIDDEN)) { LEX_STRING *name= plugin_name(plugin); if (!(wild && wild[0] && wild_case_compare(scs, name->str,wild))) { LEX_STRING yesno[2]= {{ C_STRING_WITH_LEN("NO") }, { C_STRING_WITH_LEN("YES") }}; LEX_STRING *tmp; const char *option_name= show_comp_option_name[(int) hton->state]; restore_record(table, s->default_values); table->field[0]->store(name->str, name->length, scs); if (hton->state == SHOW_OPTION_YES && default_type == hton) option_name= "DEFAULT"; table->field[1]->store(option_name, strlen(option_name), scs); table->field[2]->store(plugin_decl(plugin)->descr, strlen(plugin_decl(plugin)->descr), scs); tmp= &yesno[test(hton->commit)]; table->field[3]->store(tmp->str, tmp->length, scs); table->field[3]->set_notnull(); tmp= &yesno[test(hton->prepare)]; table->field[4]->store(tmp->str, tmp->length, scs); table->field[4]->set_notnull(); tmp= &yesno[test(hton->savepoint_set)]; table->field[5]->store(tmp->str, tmp->length, scs); table->field[5]->set_notnull(); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } DBUG_RETURN(0); } int fill_schema_engines(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_schema_engines"); if (plugin_foreach_with_mask(thd, iter_schema_engines, MYSQL_STORAGE_ENGINE_PLUGIN, ~PLUGIN_IS_FREED, tables->table)) DBUG_RETURN(1); DBUG_RETURN(0); } int fill_schema_collation(THD *thd, TABLE_LIST *tables, COND *cond) { CHARSET_INFO **cs; const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; TABLE *table= tables->table; CHARSET_INFO *scs= system_charset_info; for (cs= all_charsets ; cs < all_charsets + array_elements(all_charsets) ; cs++ ) { CHARSET_INFO **cl; CHARSET_INFO *tmp_cs= cs[0]; if (!tmp_cs || !(tmp_cs->state & MY_CS_AVAILABLE) || (tmp_cs->state & MY_CS_HIDDEN) || !(tmp_cs->state & MY_CS_PRIMARY)) continue; for (cl= all_charsets; cl < all_charsets + array_elements(all_charsets) ; cl ++) { CHARSET_INFO *tmp_cl= cl[0]; if (!tmp_cl || !(tmp_cl->state & MY_CS_AVAILABLE) || !my_charset_same(tmp_cs, tmp_cl)) continue; if (!(wild && wild[0] && wild_case_compare(scs, tmp_cl->name,wild))) { const char *tmp_buff; restore_record(table, s->default_values); table->field[0]->store(tmp_cl->name, strlen(tmp_cl->name), scs); table->field[1]->store(tmp_cl->csname , strlen(tmp_cl->csname), scs); table->field[2]->store((longlong) tmp_cl->number, TRUE); tmp_buff= (tmp_cl->state & MY_CS_PRIMARY) ? "Yes" : ""; table->field[3]->store(tmp_buff, strlen(tmp_buff), scs); tmp_buff= (tmp_cl->state & MY_CS_COMPILED)? "Yes" : ""; table->field[4]->store(tmp_buff, strlen(tmp_buff), scs); table->field[5]->store((longlong) tmp_cl->strxfrm_multiply, TRUE); if (schema_table_store_record(thd, table)) return 1; } } } return 0; } int fill_schema_coll_charset_app(THD *thd, TABLE_LIST *tables, COND *cond) { CHARSET_INFO **cs; TABLE *table= tables->table; CHARSET_INFO *scs= system_charset_info; for (cs= all_charsets ; cs < all_charsets + array_elements(all_charsets) ; cs++ ) { CHARSET_INFO **cl; CHARSET_INFO *tmp_cs= cs[0]; if (!tmp_cs || !(tmp_cs->state & MY_CS_AVAILABLE) || !(tmp_cs->state & MY_CS_PRIMARY)) continue; for (cl= all_charsets; cl < all_charsets + array_elements(all_charsets) ; cl ++) { CHARSET_INFO *tmp_cl= cl[0]; if (!tmp_cl || !(tmp_cl->state & MY_CS_AVAILABLE) || (tmp_cl->state & MY_CS_HIDDEN) || !my_charset_same(tmp_cs,tmp_cl)) continue; restore_record(table, s->default_values); table->field[0]->store(tmp_cl->name, strlen(tmp_cl->name), scs); table->field[1]->store(tmp_cl->csname , strlen(tmp_cl->csname), scs); if (schema_table_store_record(thd, table)) return 1; } } return 0; } static inline void copy_field_as_string(Field *to_field, Field *from_field) { char buff[MAX_FIELD_WIDTH]; String tmp_str(buff, sizeof(buff), system_charset_info); from_field->val_str(&tmp_str); to_field->store(tmp_str.ptr(), tmp_str.length(), system_charset_info); } /** @brief Store record into I_S.PARAMETERS table @param[in] thd thread handler @param[in] table I_S table @param[in] proc_table 'mysql.proc' table @param[in] wild wild string, not used for now, will be useful if we add 'SHOW PARAMETERs' @param[in] full_access if 1 user has privileges on the routine @param[in] sp_user user in 'user@host' format @return Operation status @retval 0 ok @retval 1 error */ bool store_schema_params(THD *thd, TABLE *table, TABLE *proc_table, const char *wild, bool full_access, const char *sp_user) { TABLE_SHARE share; TABLE tbl; CHARSET_INFO *cs= system_charset_info; char params_buff[MAX_FIELD_WIDTH], returns_buff[MAX_FIELD_WIDTH], sp_db_buff[NAME_LEN], sp_name_buff[NAME_LEN], path[FN_REFLEN], definer_buff[USERNAME_LENGTH + HOSTNAME_LENGTH + 1]; String params(params_buff, sizeof(params_buff), cs); String returns(returns_buff, sizeof(returns_buff), cs); String sp_db(sp_db_buff, sizeof(sp_db_buff), cs); String sp_name(sp_name_buff, sizeof(sp_name_buff), cs); String definer(definer_buff, sizeof(definer_buff), cs); sp_head *sp; uint routine_type; bool free_sp_head; DBUG_ENTER("store_schema_params"); bzero((char*) &tbl, sizeof(TABLE)); (void) build_table_filename(path, sizeof(path), "", "", "", 0); init_tmp_table_share(thd, &share, "", 0, "", path); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_FIELD_DB], &sp_db); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_FIELD_NAME], &sp_name); get_field(thd->mem_root,proc_table->field[MYSQL_PROC_FIELD_DEFINER],&definer); routine_type= (uint) proc_table->field[MYSQL_PROC_MYSQL_TYPE]->val_int(); if (!full_access) full_access= !strcmp(sp_user, definer.ptr()); if (!full_access && check_some_routine_access(thd, sp_db.ptr(),sp_name.ptr(), routine_type == TYPE_ENUM_PROCEDURE)) DBUG_RETURN(0); params.length(0); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_FIELD_PARAM_LIST], &params); returns.length(0); if (routine_type == TYPE_ENUM_FUNCTION) get_field(thd->mem_root, proc_table->field[MYSQL_PROC_FIELD_RETURNS], &returns); sp= sp_load_for_information_schema(thd, proc_table, &sp_db, &sp_name, (ulong) proc_table-> field[MYSQL_PROC_FIELD_SQL_MODE]->val_int(), routine_type, returns.c_ptr_safe(), params.c_ptr_safe(), &free_sp_head); if (sp) { Field *field; Create_field *field_def; String tmp_string; if (routine_type == TYPE_ENUM_FUNCTION) { restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(sp_db.ptr(), sp_db.length(), cs); table->field[2]->store(sp_name.ptr(), sp_name.length(), cs); table->field[3]->store((longlong) 0, TRUE); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_MYSQL_TYPE], &tmp_string); table->field[14]->store(tmp_string.ptr(), tmp_string.length(), cs); field_def= &sp->m_return_field_def; field= make_field(&share, (uchar*) 0, field_def->length, (uchar*) "", 0, field_def->pack_flag, field_def->sql_type, field_def->charset, field_def->geom_type, Field::NONE, field_def->interval, ""); field->table= &tbl; tbl.in_use= thd; store_column_type(table, field, cs, 6); if (schema_table_store_record(thd, table)) { free_table_share(&share); if (free_sp_head) delete sp; DBUG_RETURN(1); } } sp_pcontext *spcont= sp->get_parse_context(); uint params= spcont->context_var_count(); for (uint i= 0 ; i < params ; i++) { const char *tmp_buff; sp_variable_t *spvar= spcont->find_variable(i); field_def= &spvar->field_def; switch (spvar->mode) { case sp_param_in: tmp_buff= "IN"; break; case sp_param_out: tmp_buff= "OUT"; break; case sp_param_inout: tmp_buff= "INOUT"; break; default: tmp_buff= ""; break; } restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(sp_db.ptr(), sp_db.length(), cs); table->field[2]->store(sp_name.ptr(), sp_name.length(), cs); table->field[3]->store((longlong) i + 1, TRUE); table->field[4]->store(tmp_buff, strlen(tmp_buff), cs); table->field[4]->set_notnull(); table->field[5]->store(spvar->name.str, spvar->name.length, cs); table->field[5]->set_notnull(); get_field(thd->mem_root, proc_table->field[MYSQL_PROC_MYSQL_TYPE], &tmp_string); table->field[14]->store(tmp_string.ptr(), tmp_string.length(), cs); field= make_field(&share, (uchar*) 0, field_def->length, (uchar*) "", 0, field_def->pack_flag, field_def->sql_type, field_def->charset, field_def->geom_type, Field::NONE, field_def->interval, spvar->name.str); field->table= &tbl; tbl.in_use= thd; store_column_type(table, field, cs, 6); if (schema_table_store_record(thd, table)) { free_table_share(&share); if (free_sp_head) delete sp; DBUG_RETURN(1); } } if (free_sp_head) delete sp; } free_table_share(&share); DBUG_RETURN(0); } bool store_schema_proc(THD *thd, TABLE *table, TABLE *proc_table, const char *wild, bool full_access, const char *sp_user) { MYSQL_TIME time; LEX *lex= thd->lex; CHARSET_INFO *cs= system_charset_info; char sp_db_buff[NAME_LEN + 1], sp_name_buff[NAME_LEN + 1], definer_buff[USERNAME_LENGTH + HOSTNAME_LENGTH + 2], returns_buff[MAX_FIELD_WIDTH]; String sp_db(sp_db_buff, sizeof(sp_db_buff), cs); String sp_name(sp_name_buff, sizeof(sp_name_buff), cs); String definer(definer_buff, sizeof(definer_buff), cs); String returns(returns_buff, sizeof(returns_buff), cs); proc_table->field[MYSQL_PROC_FIELD_DB]->val_str(&sp_db); proc_table->field[MYSQL_PROC_FIELD_NAME]->val_str(&sp_name); proc_table->field[MYSQL_PROC_FIELD_DEFINER]->val_str(&definer); if (!full_access) full_access= !strcmp(sp_user, definer.c_ptr_safe()); if (!full_access && check_some_routine_access(thd, sp_db.c_ptr_safe(), sp_name.c_ptr_safe(), proc_table->field[MYSQL_PROC_MYSQL_TYPE]-> val_int() == TYPE_ENUM_PROCEDURE)) return 0; if ((lex->sql_command == SQLCOM_SHOW_STATUS_PROC && proc_table->field[MYSQL_PROC_MYSQL_TYPE]->val_int() == TYPE_ENUM_PROCEDURE) || (lex->sql_command == SQLCOM_SHOW_STATUS_FUNC && proc_table->field[MYSQL_PROC_MYSQL_TYPE]->val_int() == TYPE_ENUM_FUNCTION) || (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0) { restore_record(table, s->default_values); if (!wild || !wild[0] || !wild_case_compare(system_charset_info, sp_name.c_ptr_safe(), wild)) { int enum_idx= (int) proc_table->field[MYSQL_PROC_FIELD_ACCESS]->val_int(); table->field[3]->store(sp_name.ptr(), sp_name.length(), cs); copy_field_as_string(table->field[0], proc_table->field[MYSQL_PROC_FIELD_SPECIFIC_NAME]); table->field[1]->store(STRING_WITH_LEN("def"), cs); table->field[2]->store(sp_db.ptr(), sp_db.length(), cs); copy_field_as_string(table->field[4], proc_table->field[MYSQL_PROC_MYSQL_TYPE]); if (proc_table->field[MYSQL_PROC_MYSQL_TYPE]->val_int() == TYPE_ENUM_FUNCTION) { sp_head *sp; bool free_sp_head; proc_table->field[MYSQL_PROC_FIELD_RETURNS]->val_str(&returns); sp= sp_load_for_information_schema(thd, proc_table, &sp_db, &sp_name, (ulong) proc_table-> field[MYSQL_PROC_FIELD_SQL_MODE]-> val_int(), TYPE_ENUM_FUNCTION, returns.c_ptr_safe(), "", &free_sp_head); if (sp) { char path[FN_REFLEN]; TABLE_SHARE share; TABLE tbl; Field *field; Create_field *field_def= &sp->m_return_field_def; bzero((char*) &tbl, sizeof(TABLE)); (void) build_table_filename(path, sizeof(path), "", "", "", 0); init_tmp_table_share(thd, &share, "", 0, "", path); field= make_field(&share, (uchar*) 0, field_def->length, (uchar*) "", 0, field_def->pack_flag, field_def->sql_type, field_def->charset, field_def->geom_type, Field::NONE, field_def->interval, ""); field->table= &tbl; tbl.in_use= thd; store_column_type(table, field, cs, 5); free_table_share(&share); if (free_sp_head) delete sp; } } if (full_access) { copy_field_as_string(table->field[14], proc_table->field[MYSQL_PROC_FIELD_BODY_UTF8]); table->field[14]->set_notnull(); } table->field[13]->store(STRING_WITH_LEN("SQL"), cs); table->field[17]->store(STRING_WITH_LEN("SQL"), cs); copy_field_as_string(table->field[18], proc_table->field[MYSQL_PROC_FIELD_DETERMINISTIC]); table->field[19]->store(sp_data_access_name[enum_idx].str, sp_data_access_name[enum_idx].length , cs); copy_field_as_string(table->field[21], proc_table->field[MYSQL_PROC_FIELD_SECURITY_TYPE]); bzero((char *)&time, sizeof(time)); ((Field_timestamp *) proc_table->field[MYSQL_PROC_FIELD_CREATED])-> get_time(&time); table->field[22]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); bzero((char *)&time, sizeof(time)); ((Field_timestamp *) proc_table->field[MYSQL_PROC_FIELD_MODIFIED])-> get_time(&time); table->field[23]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); copy_field_as_string(table->field[24], proc_table->field[MYSQL_PROC_FIELD_SQL_MODE]); copy_field_as_string(table->field[25], proc_table->field[MYSQL_PROC_FIELD_COMMENT]); table->field[26]->store(definer.ptr(), definer.length(), cs); copy_field_as_string(table->field[27], proc_table-> field[MYSQL_PROC_FIELD_CHARACTER_SET_CLIENT]); copy_field_as_string(table->field[28], proc_table-> field[MYSQL_PROC_FIELD_COLLATION_CONNECTION]); copy_field_as_string(table->field[29], proc_table->field[MYSQL_PROC_FIELD_DB_COLLATION]); return schema_table_store_record(thd, table); } } return 0; } int fill_schema_proc(THD *thd, TABLE_LIST *tables, COND *cond) { TABLE *proc_table; TABLE_LIST proc_tables; const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; int res= 0; TABLE *table= tables->table; bool full_access; char definer[USER_HOST_BUFF_SIZE]; Open_tables_backup open_tables_state_backup; enum enum_schema_tables schema_table_idx= get_schema_table_idx(tables->schema_table); DBUG_ENTER("fill_schema_proc"); strxmov(definer, thd->security_ctx->priv_user, "@", thd->security_ctx->priv_host, NullS); /* We use this TABLE_LIST instance only for checking of privileges. */ bzero((char*) &proc_tables,sizeof(proc_tables)); proc_tables.db= (char*) "mysql"; proc_tables.db_length= 5; proc_tables.table_name= proc_tables.alias= (char*) "proc"; proc_tables.table_name_length= 4; proc_tables.lock_type= TL_READ; full_access= !check_table_access(thd, SELECT_ACL, &proc_tables, FALSE, 1, TRUE); if (!(proc_table= open_proc_table_for_read(thd, &open_tables_state_backup))) { DBUG_RETURN(1); } if (proc_table->file->ha_index_init(0, 1)) { res= 1; goto err; } if ((res= proc_table->file->index_first(proc_table->record[0]))) { res= (res == HA_ERR_END_OF_FILE) ? 0 : 1; goto err; } if (schema_table_idx == SCH_PROCEDURES ? store_schema_proc(thd, table, proc_table, wild, full_access, definer) : store_schema_params(thd, table, proc_table, wild, full_access, definer)) { res= 1; goto err; } while (!proc_table->file->index_next(proc_table->record[0])) { if (schema_table_idx == SCH_PROCEDURES ? store_schema_proc(thd, table, proc_table, wild, full_access, definer): store_schema_params(thd, table, proc_table, wild, full_access, definer)) { res= 1; goto err; } } err: if (proc_table->file->inited) (void) proc_table->file->ha_index_end(); close_system_tables(thd, &open_tables_state_backup); DBUG_RETURN(res); } static int get_schema_stat_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { CHARSET_INFO *cs= system_charset_info; DBUG_ENTER("get_schema_stat_record"); if (res) { if (thd->lex->sql_command != SQLCOM_SHOW_KEYS) { /* I.e. we are in SELECT FROM INFORMATION_SCHEMA.STATISTICS rather than in SHOW KEYS */ if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); res= 0; } DBUG_RETURN(res); } else if (!tables->view) { TABLE *show_table= tables->table; KEY *key_info=show_table->s->key_info; if (show_table->file) show_table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME); for (uint i=0 ; i < show_table->s->keys ; i++,key_info++) { KEY_PART_INFO *key_part= key_info->key_part; const char *str; for (uint j=0 ; j < key_info->key_parts ; j++,key_part++) { restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); table->field[3]->store((longlong) ((key_info->flags & HA_NOSAME) ? 0 : 1), TRUE); table->field[4]->store(db_name->str, db_name->length, cs); table->field[5]->store(key_info->name, strlen(key_info->name), cs); table->field[6]->store((longlong) (j+1), TRUE); str=(key_part->field ? key_part->field->field_name : "?unknown field?"); table->field[7]->store(str, strlen(str), cs); if (show_table->file) { if (show_table->file->index_flags(i, j, 0) & HA_READ_ORDER) { table->field[8]->store(((key_part->key_part_flag & HA_REVERSE_SORT) ? "D" : "A"), 1, cs); table->field[8]->set_notnull(); } KEY *key=show_table->key_info+i; if (key->rec_per_key[j]) { ha_rows records=(show_table->file->stats.records / key->rec_per_key[j]); table->field[9]->store((longlong) records, TRUE); table->field[9]->set_notnull(); } str= show_table->file->index_type(i); table->field[13]->store(str, strlen(str), cs); } if (!(key_info->flags & HA_FULLTEXT) && (key_part->field && key_part->length != show_table->s->field[key_part->fieldnr-1]->key_length())) { table->field[10]->store((longlong) key_part->length / key_part->field->charset()->mbmaxlen, TRUE); table->field[10]->set_notnull(); } uint flags= key_part->field ? key_part->field->flags : 0; const char *pos=(char*) ((flags & NOT_NULL_FLAG) ? "" : "YES"); table->field[12]->store(pos, strlen(pos), cs); if (!show_table->s->keys_in_use.is_set(i)) table->field[14]->store(STRING_WITH_LEN("disabled"), cs); else table->field[14]->store("", 0, cs); table->field[14]->set_notnull(); DBUG_ASSERT(test(key_info->flags & HA_USES_COMMENT) == (key_info->comment.length > 0)); if (key_info->flags & HA_USES_COMMENT) table->field[15]->store(key_info->comment.str, key_info->comment.length, cs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } } DBUG_RETURN(res); } static int get_schema_views_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { CHARSET_INFO *cs= system_charset_info; char definer[USER_HOST_BUFF_SIZE]; uint definer_len; bool updatable_view; DBUG_ENTER("get_schema_views_record"); if (tables->view) { Security_context *sctx= thd->security_ctx; if (!tables->allowed_show) { if (!my_strcasecmp(system_charset_info, tables->definer.user.str, sctx->priv_user) && !my_strcasecmp(system_charset_info, tables->definer.host.str, sctx->priv_host)) tables->allowed_show= TRUE; #ifndef NO_EMBEDDED_ACCESS_CHECKS else { if ((thd->col_access & (SHOW_VIEW_ACL|SELECT_ACL)) == (SHOW_VIEW_ACL|SELECT_ACL)) tables->allowed_show= TRUE; else { TABLE_LIST table_list; uint view_access; memset(&table_list, 0, sizeof(table_list)); table_list.db= tables->db; table_list.table_name= tables->table_name; table_list.grant.privilege= thd->col_access; view_access= get_table_grant(thd, &table_list); if ((view_access & (SHOW_VIEW_ACL|SELECT_ACL)) == (SHOW_VIEW_ACL|SELECT_ACL)) tables->allowed_show= TRUE; } } #endif } restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); if (tables->allowed_show) { table->field[3]->store(tables->view_body_utf8.str, tables->view_body_utf8.length, cs); } if (tables->with_check != VIEW_CHECK_NONE) { if (tables->with_check == VIEW_CHECK_LOCAL) table->field[4]->store(STRING_WITH_LEN("LOCAL"), cs); else table->field[4]->store(STRING_WITH_LEN("CASCADED"), cs); } else table->field[4]->store(STRING_WITH_LEN("NONE"), cs); /* Only try to fill in the information about view updatability if it is requested as part of the top-level query (i.e. it's select * from i_s.views, as opposed to, say, select security_type from i_s.views). Do not try to access the underlying tables if there was an error when opening the view: all underlying tables are released back to the table definition cache on error inside open_normal_and_derived_tables(). If a field is not assigned explicitly, it defaults to NULL. */ if (res == FALSE && table->pos_in_table_list->table_open_method & OPEN_FULL_TABLE) { updatable_view= 0; if (tables->algorithm != VIEW_ALGORITHM_TMPTABLE) { /* We should use tables->view->select_lex.item_list here and can not use Field_iterator_view because the view always uses temporary algorithm during opening for I_S and TABLE_LIST fields 'field_translation' & 'field_translation_end' are uninitialized is this case. */ List<Item> *fields= &tables->view->select_lex.item_list; List_iterator<Item> it(*fields); Item *item; Item_field *field; /* check that at least one column in view is updatable */ while ((item= it++)) { if ((field= item->filed_for_view_update()) && field->field && !field->field->table->pos_in_table_list->schema_table) { updatable_view= 1; break; } } if (updatable_view && !tables->view->can_be_merged()) updatable_view= 0; } if (updatable_view) table->field[5]->store(STRING_WITH_LEN("YES"), cs); else table->field[5]->store(STRING_WITH_LEN("NO"), cs); } definer_len= (strxmov(definer, tables->definer.user.str, "@", tables->definer.host.str, NullS) - definer); table->field[6]->store(definer, definer_len, cs); if (tables->view_suid) table->field[7]->store(STRING_WITH_LEN("DEFINER"), cs); else table->field[7]->store(STRING_WITH_LEN("INVOKER"), cs); table->field[8]->store(tables->view_creation_ctx->get_client_cs()->csname, strlen(tables->view_creation_ctx-> get_client_cs()->csname), cs); table->field[9]->store(tables->view_creation_ctx-> get_connection_cl()->name, strlen(tables->view_creation_ctx-> get_connection_cl()->name), cs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); if (res && thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); } if (res) thd->clear_error(); DBUG_RETURN(0); } bool store_constraints(THD *thd, TABLE *table, LEX_STRING *db_name, LEX_STRING *table_name, const char *key_name, uint key_len, const char *con_type, uint con_len) { CHARSET_INFO *cs= system_charset_info; restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(key_name, key_len, cs); table->field[3]->store(db_name->str, db_name->length, cs); table->field[4]->store(table_name->str, table_name->length, cs); table->field[5]->store(con_type, con_len, cs); return schema_table_store_record(thd, table); } static int get_schema_constraints_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { DBUG_ENTER("get_schema_constraints_record"); if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } else if (!tables->view) { List<FOREIGN_KEY_INFO> f_key_list; TABLE *show_table= tables->table; KEY *key_info=show_table->key_info; uint primary_key= show_table->s->primary_key; show_table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME); for (uint i=0 ; i < show_table->s->keys ; i++, key_info++) { if (i != primary_key && !(key_info->flags & HA_NOSAME)) continue; if (i == primary_key && !strcmp(key_info->name, primary_key_name)) { if (store_constraints(thd, table, db_name, table_name, key_info->name, strlen(key_info->name), STRING_WITH_LEN("PRIMARY KEY"))) DBUG_RETURN(1); } else if (key_info->flags & HA_NOSAME) { if (store_constraints(thd, table, db_name, table_name, key_info->name, strlen(key_info->name), STRING_WITH_LEN("UNIQUE"))) DBUG_RETURN(1); } } show_table->file->get_foreign_key_list(thd, &f_key_list); FOREIGN_KEY_INFO *f_key_info; List_iterator_fast<FOREIGN_KEY_INFO> it(f_key_list); while ((f_key_info=it++)) { if (store_constraints(thd, table, db_name, table_name, f_key_info->foreign_id->str, strlen(f_key_info->foreign_id->str), "FOREIGN KEY", 11)) DBUG_RETURN(1); } } DBUG_RETURN(res); } static bool store_trigger(THD *thd, TABLE *table, LEX_STRING *db_name, LEX_STRING *table_name, LEX_STRING *trigger_name, enum trg_event_type event, enum trg_action_time_type timing, LEX_STRING *trigger_stmt, ulong sql_mode, LEX_STRING *definer_buffer, LEX_STRING *client_cs_name, LEX_STRING *connection_cl_name, LEX_STRING *db_cl_name) { CHARSET_INFO *cs= system_charset_info; LEX_STRING sql_mode_rep; restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(trigger_name->str, trigger_name->length, cs); table->field[3]->store(trg_event_type_names[event].str, trg_event_type_names[event].length, cs); table->field[4]->store(STRING_WITH_LEN("def"), cs); table->field[5]->store(db_name->str, db_name->length, cs); table->field[6]->store(table_name->str, table_name->length, cs); table->field[9]->store(trigger_stmt->str, trigger_stmt->length, cs); table->field[10]->store(STRING_WITH_LEN("ROW"), cs); table->field[11]->store(trg_action_time_type_names[timing].str, trg_action_time_type_names[timing].length, cs); table->field[14]->store(STRING_WITH_LEN("OLD"), cs); table->field[15]->store(STRING_WITH_LEN("NEW"), cs); sql_mode_string_representation(thd, sql_mode, &sql_mode_rep); table->field[17]->store(sql_mode_rep.str, sql_mode_rep.length, cs); table->field[18]->store(definer_buffer->str, definer_buffer->length, cs); table->field[19]->store(client_cs_name->str, client_cs_name->length, cs); table->field[20]->store(connection_cl_name->str, connection_cl_name->length, cs); table->field[21]->store(db_cl_name->str, db_cl_name->length, cs); return schema_table_store_record(thd, table); } static int get_schema_triggers_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { DBUG_ENTER("get_schema_triggers_record"); /* res can be non zero value when processed table is a view or error happened during opening of processed table. */ if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } if (!tables->view && tables->table->triggers) { Table_triggers_list *triggers= tables->table->triggers; int event, timing; if (check_table_access(thd, TRIGGER_ACL, tables, FALSE, 1, TRUE)) goto ret; for (event= 0; event < (int)TRG_EVENT_MAX; event++) { for (timing= 0; timing < (int)TRG_ACTION_MAX; timing++) { LEX_STRING trigger_name; LEX_STRING trigger_stmt; ulong sql_mode; char definer_holder[USER_HOST_BUFF_SIZE]; LEX_STRING definer_buffer; LEX_STRING client_cs_name; LEX_STRING connection_cl_name; LEX_STRING db_cl_name; definer_buffer.str= definer_holder; if (triggers->get_trigger_info(thd, (enum trg_event_type) event, (enum trg_action_time_type)timing, &trigger_name, &trigger_stmt, &sql_mode, &definer_buffer, &client_cs_name, &connection_cl_name, &db_cl_name)) continue; if (store_trigger(thd, table, db_name, table_name, &trigger_name, (enum trg_event_type) event, (enum trg_action_time_type) timing, &trigger_stmt, sql_mode, &definer_buffer, &client_cs_name, &connection_cl_name, &db_cl_name)) DBUG_RETURN(1); } } } ret: DBUG_RETURN(0); } void store_key_column_usage(TABLE *table, LEX_STRING *db_name, LEX_STRING *table_name, const char *key_name, uint key_len, const char *con_type, uint con_len, longlong idx) { CHARSET_INFO *cs= system_charset_info; table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(key_name, key_len, cs); table->field[3]->store(STRING_WITH_LEN("def"), cs); table->field[4]->store(db_name->str, db_name->length, cs); table->field[5]->store(table_name->str, table_name->length, cs); table->field[6]->store(con_type, con_len, cs); table->field[7]->store((longlong) idx, TRUE); } static int get_schema_key_column_usage_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { DBUG_ENTER("get_schema_key_column_usage_record"); if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } else if (!tables->view) { List<FOREIGN_KEY_INFO> f_key_list; TABLE *show_table= tables->table; KEY *key_info=show_table->key_info; uint primary_key= show_table->s->primary_key; show_table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME); for (uint i=0 ; i < show_table->s->keys ; i++, key_info++) { if (i != primary_key && !(key_info->flags & HA_NOSAME)) continue; uint f_idx= 0; KEY_PART_INFO *key_part= key_info->key_part; for (uint j=0 ; j < key_info->key_parts ; j++,key_part++) { if (key_part->field) { f_idx++; restore_record(table, s->default_values); store_key_column_usage(table, db_name, table_name, key_info->name, strlen(key_info->name), key_part->field->field_name, strlen(key_part->field->field_name), (longlong) f_idx); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } } show_table->file->get_foreign_key_list(thd, &f_key_list); FOREIGN_KEY_INFO *f_key_info; List_iterator_fast<FOREIGN_KEY_INFO> fkey_it(f_key_list); while ((f_key_info= fkey_it++)) { LEX_STRING *f_info; LEX_STRING *r_info; List_iterator_fast<LEX_STRING> it(f_key_info->foreign_fields), it1(f_key_info->referenced_fields); uint f_idx= 0; while ((f_info= it++)) { r_info= it1++; f_idx++; restore_record(table, s->default_values); store_key_column_usage(table, db_name, table_name, f_key_info->foreign_id->str, f_key_info->foreign_id->length, f_info->str, f_info->length, (longlong) f_idx); table->field[8]->store((longlong) f_idx, TRUE); table->field[8]->set_notnull(); table->field[9]->store(f_key_info->referenced_db->str, f_key_info->referenced_db->length, system_charset_info); table->field[9]->set_notnull(); table->field[10]->store(f_key_info->referenced_table->str, f_key_info->referenced_table->length, system_charset_info); table->field[10]->set_notnull(); table->field[11]->store(r_info->str, r_info->length, system_charset_info); table->field[11]->set_notnull(); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } } DBUG_RETURN(res); } #ifdef WITH_PARTITION_STORAGE_ENGINE static void collect_partition_expr(THD *thd, List<char> &field_list, String *str) { List_iterator<char> part_it(field_list); ulong no_fields= field_list.elements; const char *field_str; str->length(0); while ((field_str= part_it++)) { append_identifier(thd, str, field_str, strlen(field_str)); if (--no_fields != 0) str->append(","); } return; } /* Convert a string in a given character set to a string which can be used for FRM file storage in which case use_hex is TRUE and we store the character constants as hex strings in the character set encoding their field have. In the case of SHOW CREATE TABLE and the PARTITIONS information schema table we instead provide utf8 strings to the user and convert to the utf8 character set. SYNOPSIS get_cs_converted_part_value_from_string() item Item from which constant comes input_str String as provided by val_str after conversion to character set output_str Out value: The string created cs Character set string is encoded in NULL for INT_RESULT's here use_hex TRUE => hex string created FALSE => utf8 constant string created RETURN VALUES TRUE Error FALSE Ok */ int get_cs_converted_part_value_from_string(THD *thd, Item *item, String *input_str, String *output_str, CHARSET_INFO *cs, bool use_hex) { if (item->result_type() == INT_RESULT) { longlong value= item->val_int(); output_str->set(value, system_charset_info); return FALSE; } if (!input_str) { my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0)); return TRUE; } get_cs_converted_string_value(thd, input_str, output_str, cs, use_hex); return FALSE; } #endif static void store_schema_partitions_record(THD *thd, TABLE *schema_table, TABLE *showing_table, partition_element *part_elem, handler *file, uint part_id) { TABLE* table= schema_table; CHARSET_INFO *cs= system_charset_info; PARTITION_STATS stat_info; MYSQL_TIME time; file->get_dynamic_partition_info(&stat_info, part_id); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[12]->store((longlong) stat_info.records, TRUE); table->field[13]->store((longlong) stat_info.mean_rec_length, TRUE); table->field[14]->store((longlong) stat_info.data_file_length, TRUE); if (stat_info.max_data_file_length) { table->field[15]->store((longlong) stat_info.max_data_file_length, TRUE); table->field[15]->set_notnull(); } table->field[16]->store((longlong) stat_info.index_file_length, TRUE); table->field[17]->store((longlong) stat_info.delete_length, TRUE); if (stat_info.create_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t)stat_info.create_time); table->field[18]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[18]->set_notnull(); } if (stat_info.update_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t)stat_info.update_time); table->field[19]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[19]->set_notnull(); } if (stat_info.check_time) { thd->variables.time_zone->gmt_sec_to_TIME(&time, (my_time_t)stat_info.check_time); table->field[20]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); table->field[20]->set_notnull(); } if (file->ha_table_flags() & (ulong) HA_HAS_CHECKSUM) { table->field[21]->store((longlong) stat_info.check_sum, TRUE); table->field[21]->set_notnull(); } if (part_elem) { if (part_elem->part_comment) table->field[22]->store(part_elem->part_comment, strlen(part_elem->part_comment), cs); else table->field[22]->store(STRING_WITH_LEN(""), cs); if (part_elem->nodegroup_id != UNDEF_NODEGROUP) table->field[23]->store((longlong) part_elem->nodegroup_id, TRUE); else table->field[23]->store(STRING_WITH_LEN("default"), cs); table->field[24]->set_notnull(); if (part_elem->tablespace_name) table->field[24]->store(part_elem->tablespace_name, strlen(part_elem->tablespace_name), cs); else { char *ts= showing_table->s->tablespace; if(ts) table->field[24]->store(ts, strlen(ts), cs); else table->field[24]->set_null(); } } return; } #ifdef WITH_PARTITION_STORAGE_ENGINE static int get_partition_column_description(THD *thd, partition_info *part_info, part_elem_value *list_value, String &tmp_str) { uint num_elements= part_info->part_field_list.elements; uint i; DBUG_ENTER("get_partition_column_description"); for (i= 0; i < num_elements; i++) { part_column_list_val *col_val= &list_value->col_val_array[i]; if (col_val->max_value) tmp_str.append(partition_keywords[PKW_MAXVALUE].str); else if (col_val->null_value) tmp_str.append("NULL"); else { char buffer[MAX_KEY_LENGTH]; String str(buffer, sizeof(buffer), &my_charset_bin); String val_conv; Item *item= col_val->item_expression; if (!(item= part_info->get_column_item(item, part_info->part_field_array[i]))) { DBUG_RETURN(1); } String *res= item->val_str(&str); if (get_cs_converted_part_value_from_string(thd, item, res, &val_conv, part_info->part_field_array[i]->charset(), FALSE)) { DBUG_RETURN(1); } tmp_str.append(val_conv); } if (i != num_elements - 1) tmp_str.append(","); } DBUG_RETURN(0); } #endif /* WITH_PARTITION_STORAGE_ENGINE */ static int get_schema_partitions_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { CHARSET_INFO *cs= system_charset_info; char buff[61]; String tmp_res(buff, sizeof(buff), cs); String tmp_str; TABLE *show_table= tables->table; handler *file; #ifdef WITH_PARTITION_STORAGE_ENGINE partition_info *part_info; #endif DBUG_ENTER("get_schema_partitions_record"); if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } file= show_table->file; #ifdef WITH_PARTITION_STORAGE_ENGINE part_info= show_table->part_info; if (part_info) { partition_element *part_elem; List_iterator<partition_element> part_it(part_info->partitions); uint part_pos= 0, part_id= 0; restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[2]->store(table_name->str, table_name->length, cs); /* Partition method*/ switch (part_info->part_type) { case RANGE_PARTITION: case LIST_PARTITION: tmp_res.length(0); if (part_info->part_type == RANGE_PARTITION) tmp_res.append(partition_keywords[PKW_RANGE].str, partition_keywords[PKW_RANGE].length); else tmp_res.append(partition_keywords[PKW_LIST].str, partition_keywords[PKW_LIST].length); if (part_info->column_list) tmp_res.append(partition_keywords[PKW_COLUMNS].str, partition_keywords[PKW_COLUMNS].length); table->field[7]->store(tmp_res.ptr(), tmp_res.length(), cs); break; case HASH_PARTITION: tmp_res.length(0); if (part_info->linear_hash_ind) tmp_res.append(partition_keywords[PKW_LINEAR].str, partition_keywords[PKW_LINEAR].length); if (part_info->list_of_part_fields) tmp_res.append(partition_keywords[PKW_KEY].str, partition_keywords[PKW_KEY].length); else tmp_res.append(partition_keywords[PKW_HASH].str, partition_keywords[PKW_HASH].length); table->field[7]->store(tmp_res.ptr(), tmp_res.length(), cs); break; default: DBUG_ASSERT(0); my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR)); DBUG_RETURN(1); } table->field[7]->set_notnull(); /* Partition expression */ if (part_info->part_expr) { table->field[9]->store(part_info->part_func_string, part_info->part_func_len, cs); } else if (part_info->list_of_part_fields) { collect_partition_expr(thd, part_info->part_field_list, &tmp_str); table->field[9]->store(tmp_str.ptr(), tmp_str.length(), cs); } table->field[9]->set_notnull(); if (part_info->is_sub_partitioned()) { /* Subpartition method */ tmp_res.length(0); if (part_info->linear_hash_ind) tmp_res.append(partition_keywords[PKW_LINEAR].str, partition_keywords[PKW_LINEAR].length); if (part_info->list_of_subpart_fields) tmp_res.append(partition_keywords[PKW_KEY].str, partition_keywords[PKW_KEY].length); else tmp_res.append(partition_keywords[PKW_HASH].str, partition_keywords[PKW_HASH].length); table->field[8]->store(tmp_res.ptr(), tmp_res.length(), cs); table->field[8]->set_notnull(); /* Subpartition expression */ if (part_info->subpart_expr) { table->field[10]->store(part_info->subpart_func_string, part_info->subpart_func_len, cs); } else if (part_info->list_of_subpart_fields) { collect_partition_expr(thd, part_info->subpart_field_list, &tmp_str); table->field[10]->store(tmp_str.ptr(), tmp_str.length(), cs); } table->field[10]->set_notnull(); } while ((part_elem= part_it++)) { table->field[3]->store(part_elem->partition_name, strlen(part_elem->partition_name), cs); table->field[3]->set_notnull(); /* PARTITION_ORDINAL_POSITION */ table->field[5]->store((longlong) ++part_pos, TRUE); table->field[5]->set_notnull(); /* Partition description */ if (part_info->part_type == RANGE_PARTITION) { if (part_info->column_list) { List_iterator<part_elem_value> list_val_it(part_elem->list_val_list); part_elem_value *list_value= list_val_it++; tmp_str.length(0); if (get_partition_column_description(thd, part_info, list_value, tmp_str)) { DBUG_RETURN(1); } table->field[11]->store(tmp_str.ptr(), tmp_str.length(), cs); } else { if (part_elem->range_value != LONGLONG_MAX) table->field[11]->store((longlong) part_elem->range_value, FALSE); else table->field[11]->store(partition_keywords[PKW_MAXVALUE].str, partition_keywords[PKW_MAXVALUE].length, cs); } table->field[11]->set_notnull(); } else if (part_info->part_type == LIST_PARTITION) { List_iterator<part_elem_value> list_val_it(part_elem->list_val_list); part_elem_value *list_value; uint num_items= part_elem->list_val_list.elements; tmp_str.length(0); tmp_res.length(0); if (part_elem->has_null_value) { tmp_str.append("NULL"); if (num_items > 0) tmp_str.append(","); } while ((list_value= list_val_it++)) { if (part_info->column_list) { if (part_info->part_field_list.elements > 1U) tmp_str.append("("); if (get_partition_column_description(thd, part_info, list_value, tmp_str)) { DBUG_RETURN(1); } if (part_info->part_field_list.elements > 1U) tmp_str.append(")"); } else { if (!list_value->unsigned_flag) tmp_res.set(list_value->value, cs); else tmp_res.set((ulonglong)list_value->value, cs); tmp_str.append(tmp_res); } if (--num_items != 0) tmp_str.append(","); } table->field[11]->store(tmp_str.ptr(), tmp_str.length(), cs); table->field[11]->set_notnull(); } if (part_elem->subpartitions.elements) { List_iterator<partition_element> sub_it(part_elem->subpartitions); partition_element *subpart_elem; uint subpart_pos= 0; while ((subpart_elem= sub_it++)) { table->field[4]->store(subpart_elem->partition_name, strlen(subpart_elem->partition_name), cs); table->field[4]->set_notnull(); /* SUBPARTITION_ORDINAL_POSITION */ table->field[6]->store((longlong) ++subpart_pos, TRUE); table->field[6]->set_notnull(); store_schema_partitions_record(thd, table, show_table, subpart_elem, file, part_id); part_id++; if(schema_table_store_record(thd, table)) DBUG_RETURN(1); } } else { store_schema_partitions_record(thd, table, show_table, part_elem, file, part_id); part_id++; if(schema_table_store_record(thd, table)) DBUG_RETURN(1); } } DBUG_RETURN(0); } else #endif { store_schema_partitions_record(thd, table, show_table, 0, file, 0); if(schema_table_store_record(thd, table)) DBUG_RETURN(1); } DBUG_RETURN(0); } #ifdef HAVE_EVENT_SCHEDULER /* Loads an event from mysql.event and copies it's data to a row of I_S.EVENTS Synopsis copy_event_to_schema_table() thd Thread sch_table The schema table (information_schema.event) event_table The event table to use for loading (mysql.event). Returns 0 OK 1 Error */ int copy_event_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table) { const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; CHARSET_INFO *scs= system_charset_info; MYSQL_TIME time; Event_timed et; DBUG_ENTER("copy_event_to_schema_table"); restore_record(sch_table, s->default_values); if (et.load_from_row(thd, event_table)) { my_error(ER_CANNOT_LOAD_FROM_TABLE, MYF(0), event_table->alias); DBUG_RETURN(1); } if (!(!wild || !wild[0] || !wild_case_compare(scs, et.name.str, wild))) DBUG_RETURN(0); /* Skip events in schemas one does not have access to. The check is optimized. It's guaranteed in case of SHOW EVENTS that the user has access. */ if (thd->lex->sql_command != SQLCOM_SHOW_EVENTS && check_access(thd, EVENT_ACL, et.dbname.str, NULL, NULL, 0, 1)) DBUG_RETURN(0); sch_table->field[ISE_EVENT_CATALOG]->store(STRING_WITH_LEN("def"), scs); sch_table->field[ISE_EVENT_SCHEMA]-> store(et.dbname.str, et.dbname.length,scs); sch_table->field[ISE_EVENT_NAME]-> store(et.name.str, et.name.length, scs); sch_table->field[ISE_DEFINER]-> store(et.definer.str, et.definer.length, scs); const String *tz_name= et.time_zone->get_name(); sch_table->field[ISE_TIME_ZONE]-> store(tz_name->ptr(), tz_name->length(), scs); sch_table->field[ISE_EVENT_BODY]-> store(STRING_WITH_LEN("SQL"), scs); sch_table->field[ISE_EVENT_DEFINITION]->store( et.body_utf8.str, et.body_utf8.length, scs); /* SQL_MODE */ { LEX_STRING sql_mode; sql_mode_string_representation(thd, et.sql_mode, &sql_mode); sch_table->field[ISE_SQL_MODE]-> store(sql_mode.str, sql_mode.length, scs); } int not_used=0; if (et.expression) { String show_str; /* type */ sch_table->field[ISE_EVENT_TYPE]->store(STRING_WITH_LEN("RECURRING"), scs); if (Events::reconstruct_interval_expression(&show_str, et.interval, et.expression)) DBUG_RETURN(1); sch_table->field[ISE_INTERVAL_VALUE]->set_notnull(); sch_table->field[ISE_INTERVAL_VALUE]-> store(show_str.ptr(), show_str.length(), scs); LEX_STRING *ival= &interval_type_to_name[et.interval]; sch_table->field[ISE_INTERVAL_FIELD]->set_notnull(); sch_table->field[ISE_INTERVAL_FIELD]->store(ival->str, ival->length, scs); /* starts & ends . STARTS is always set - see sql_yacc.yy */ et.time_zone->gmt_sec_to_TIME(&time, et.starts); sch_table->field[ISE_STARTS]->set_notnull(); sch_table->field[ISE_STARTS]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); if (!et.ends_null) { et.time_zone->gmt_sec_to_TIME(&time, et.ends); sch_table->field[ISE_ENDS]->set_notnull(); sch_table->field[ISE_ENDS]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); } } else { /* type */ sch_table->field[ISE_EVENT_TYPE]->store(STRING_WITH_LEN("ONE TIME"), scs); et.time_zone->gmt_sec_to_TIME(&time, et.execute_at); sch_table->field[ISE_EXECUTE_AT]->set_notnull(); sch_table->field[ISE_EXECUTE_AT]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); } /* status */ switch (et.status) { case Event_parse_data::ENABLED: sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("ENABLED"), scs); break; case Event_parse_data::SLAVESIDE_DISABLED: sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("SLAVESIDE_DISABLED"), scs); break; case Event_parse_data::DISABLED: sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("DISABLED"), scs); break; default: DBUG_ASSERT(0); } sch_table->field[ISE_ORIGINATOR]->store(et.originator, TRUE); /* on_completion */ if (et.on_completion == Event_parse_data::ON_COMPLETION_DROP) sch_table->field[ISE_ON_COMPLETION]-> store(STRING_WITH_LEN("NOT PRESERVE"), scs); else sch_table->field[ISE_ON_COMPLETION]-> store(STRING_WITH_LEN("PRESERVE"), scs); number_to_datetime(et.created, &time, 0, &not_used); DBUG_ASSERT(not_used==0); sch_table->field[ISE_CREATED]->store_time(&time, MYSQL_TIMESTAMP_DATETIME); number_to_datetime(et.modified, &time, 0, &not_used); DBUG_ASSERT(not_used==0); sch_table->field[ISE_LAST_ALTERED]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); if (et.last_executed) { et.time_zone->gmt_sec_to_TIME(&time, et.last_executed); sch_table->field[ISE_LAST_EXECUTED]->set_notnull(); sch_table->field[ISE_LAST_EXECUTED]-> store_time(&time, MYSQL_TIMESTAMP_DATETIME); } sch_table->field[ISE_EVENT_COMMENT]-> store(et.comment.str, et.comment.length, scs); sch_table->field[ISE_CLIENT_CS]->set_notnull(); sch_table->field[ISE_CLIENT_CS]->store( et.creation_ctx->get_client_cs()->csname, strlen(et.creation_ctx->get_client_cs()->csname), scs); sch_table->field[ISE_CONNECTION_CL]->set_notnull(); sch_table->field[ISE_CONNECTION_CL]->store( et.creation_ctx->get_connection_cl()->name, strlen(et.creation_ctx->get_connection_cl()->name), scs); sch_table->field[ISE_DB_CL]->set_notnull(); sch_table->field[ISE_DB_CL]->store( et.creation_ctx->get_db_cl()->name, strlen(et.creation_ctx->get_db_cl()->name), scs); if (schema_table_store_record(thd, sch_table)) DBUG_RETURN(1); DBUG_RETURN(0); } #endif int fill_open_tables(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_open_tables"); const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; TABLE *table= tables->table; CHARSET_INFO *cs= system_charset_info; OPEN_TABLE_LIST *open_list; if (!(open_list=list_open_tables(thd,thd->lex->select_lex.db, wild)) && thd->is_fatal_error) DBUG_RETURN(1); for (; open_list ; open_list=open_list->next) { restore_record(table, s->default_values); table->field[0]->store(open_list->db, strlen(open_list->db), cs); table->field[1]->store(open_list->table, strlen(open_list->table), cs); table->field[2]->store((longlong) open_list->in_use, TRUE); table->field[3]->store((longlong) open_list->locked, TRUE); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } DBUG_RETURN(0); } int fill_variables(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_variables"); int res= 0; LEX *lex= thd->lex; const char *wild= lex->wild ? lex->wild->ptr() : NullS; enum enum_schema_tables schema_table_idx= get_schema_table_idx(tables->schema_table); enum enum_var_type option_type= OPT_SESSION; bool upper_case_names= (schema_table_idx != SCH_VARIABLES); bool sorted_vars= (schema_table_idx == SCH_VARIABLES); if (lex->option_type == OPT_GLOBAL || schema_table_idx == SCH_GLOBAL_VARIABLES) option_type= OPT_GLOBAL; mysql_rwlock_rdlock(&LOCK_system_variables_hash); res= show_status_array(thd, wild, enumerate_sys_vars(thd, sorted_vars, option_type), option_type, NULL, "", tables->table, upper_case_names, cond); mysql_rwlock_unlock(&LOCK_system_variables_hash); DBUG_RETURN(res); } int fill_status(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("fill_status"); LEX *lex= thd->lex; const char *wild= lex->wild ? lex->wild->ptr() : NullS; int res= 0; STATUS_VAR *tmp1, tmp; enum enum_schema_tables schema_table_idx= get_schema_table_idx(tables->schema_table); enum enum_var_type option_type; bool upper_case_names= (schema_table_idx != SCH_STATUS); if (schema_table_idx == SCH_STATUS) { option_type= lex->option_type; if (option_type == OPT_GLOBAL) tmp1= &tmp; else tmp1= thd->initial_status_var; } else if (schema_table_idx == SCH_GLOBAL_STATUS) { option_type= OPT_GLOBAL; tmp1= &tmp; } else { option_type= OPT_SESSION; tmp1= &thd->status_var; } /* Avoid recursive acquisition of LOCK_status in cases when WHERE clause represented by "cond" contains subquery on I_S.SESSION/GLOBAL_STATUS. */ if (thd->fill_status_recursion_level++ == 0) mysql_mutex_lock(&LOCK_status); if (option_type == OPT_GLOBAL) calc_sum_of_all_status(&tmp); res= show_status_array(thd, wild, (SHOW_VAR *)all_status_vars.buffer, option_type, tmp1, "", tables->table, upper_case_names, cond); if (thd->fill_status_recursion_level-- == 1) mysql_mutex_unlock(&LOCK_status); DBUG_RETURN(res); } /* Fill and store records into I_S.referential_constraints table SYNOPSIS get_referential_constraints_record() thd thread handle tables table list struct(processed table) table I_S table res 1 means the error during opening of the processed table 0 means processed table is opened without error base_name db name file_name table name RETURN 0 ok # error */ static int get_referential_constraints_record(THD *thd, TABLE_LIST *tables, TABLE *table, bool res, LEX_STRING *db_name, LEX_STRING *table_name) { CHARSET_INFO *cs= system_charset_info; DBUG_ENTER("get_referential_constraints_record"); if (res) { if (thd->is_error()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, thd->stmt_da->sql_errno(), thd->stmt_da->message()); thd->clear_error(); DBUG_RETURN(0); } if (!tables->view) { List<FOREIGN_KEY_INFO> f_key_list; TABLE *show_table= tables->table; show_table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME); show_table->file->get_foreign_key_list(thd, &f_key_list); FOREIGN_KEY_INFO *f_key_info; List_iterator_fast<FOREIGN_KEY_INFO> it(f_key_list); while ((f_key_info= it++)) { restore_record(table, s->default_values); table->field[0]->store(STRING_WITH_LEN("def"), cs); table->field[1]->store(db_name->str, db_name->length, cs); table->field[9]->store(table_name->str, table_name->length, cs); table->field[2]->store(f_key_info->foreign_id->str, f_key_info->foreign_id->length, cs); table->field[3]->store(STRING_WITH_LEN("def"), cs); table->field[4]->store(f_key_info->referenced_db->str, f_key_info->referenced_db->length, cs); table->field[10]->store(f_key_info->referenced_table->str, f_key_info->referenced_table->length, cs); if (f_key_info->referenced_key_name) { table->field[5]->store(f_key_info->referenced_key_name->str, f_key_info->referenced_key_name->length, cs); table->field[5]->set_notnull(); } else table->field[5]->set_null(); table->field[6]->store(STRING_WITH_LEN("NONE"), cs); table->field[7]->store(f_key_info->update_method->str, f_key_info->update_method->length, cs); table->field[8]->store(f_key_info->delete_method->str, f_key_info->delete_method->length, cs); if (schema_table_store_record(thd, table)) DBUG_RETURN(1); } } DBUG_RETURN(0); } struct schema_table_ref { const char *table_name; ST_SCHEMA_TABLE *schema_table; }; /* Find schema_tables elment by name SYNOPSIS find_schema_table_in_plugin() thd thread handler plugin plugin table_name table name RETURN 0 table not found 1 found the schema table */ static my_bool find_schema_table_in_plugin(THD *thd, plugin_ref plugin, void* p_table) { schema_table_ref *p_schema_table= (schema_table_ref *)p_table; const char* table_name= p_schema_table->table_name; ST_SCHEMA_TABLE *schema_table= plugin_data(plugin, ST_SCHEMA_TABLE *); DBUG_ENTER("find_schema_table_in_plugin"); if (!my_strcasecmp(system_charset_info, schema_table->table_name, table_name)) { p_schema_table->schema_table= schema_table; DBUG_RETURN(1); } DBUG_RETURN(0); } /* Find schema_tables elment by name SYNOPSIS find_schema_table() thd thread handler table_name table name RETURN 0 table not found # pointer to 'schema_tables' element */ ST_SCHEMA_TABLE *find_schema_table(THD *thd, const char* table_name) { schema_table_ref schema_table_a; ST_SCHEMA_TABLE *schema_table= schema_tables; DBUG_ENTER("find_schema_table"); for (; schema_table->table_name; schema_table++) { if (!my_strcasecmp(system_charset_info, schema_table->table_name, table_name)) DBUG_RETURN(schema_table); } schema_table_a.table_name= table_name; if (plugin_foreach(thd, find_schema_table_in_plugin, MYSQL_INFORMATION_SCHEMA_PLUGIN, &schema_table_a)) DBUG_RETURN(schema_table_a.schema_table); DBUG_RETURN(NULL); } ST_SCHEMA_TABLE *get_schema_table(enum enum_schema_tables schema_table_idx) { return &schema_tables[schema_table_idx]; } /** Create information_schema table using schema_table data. @note For MYSQL_TYPE_DECIMAL fields only, the field_length member has encoded into it two numbers, based on modulus of base-10 numbers. In the ones position is the number of decimals. Tens position is unused. In the hundreds and thousands position is a two-digit decimal number representing length. Encode this value with (decimals*100)+length , where 0<decimals<10 and 0<=length<100 . @param thd thread handler @param table_list Used to pass I_S table information(fields info, tables parameters etc) and table name. @retval \# Pointer to created table @retval NULL Can't create table */ TABLE *create_schema_table(THD *thd, TABLE_LIST *table_list) { int field_count= 0; Item *item; TABLE *table; List<Item> field_list; ST_SCHEMA_TABLE *schema_table= table_list->schema_table; ST_FIELD_INFO *fields_info= schema_table->fields_info; CHARSET_INFO *cs= system_charset_info; DBUG_ENTER("create_schema_table"); for (; fields_info->field_name; fields_info++) { switch (fields_info->field_type) { case MYSQL_TYPE_TINY: case MYSQL_TYPE_LONG: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_INT24: if (!(item= new Item_return_int(fields_info->field_name, fields_info->field_length, fields_info->field_type, fields_info->value))) { DBUG_RETURN(0); } item->unsigned_flag= (fields_info->field_flags & MY_I_S_UNSIGNED); break; case MYSQL_TYPE_DATE: case MYSQL_TYPE_TIME: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: if (!(item=new Item_return_date_time(fields_info->field_name, fields_info->field_type))) { DBUG_RETURN(0); } break; case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: if ((item= new Item_float(fields_info->field_name, 0.0, NOT_FIXED_DEC, fields_info->field_length)) == NULL) DBUG_RETURN(NULL); break; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: if (!(item= new Item_decimal((longlong) fields_info->value, false))) { DBUG_RETURN(0); } item->unsigned_flag= (fields_info->field_flags & MY_I_S_UNSIGNED); item->decimals= fields_info->field_length%10; item->max_length= (fields_info->field_length/100)%100; if (item->unsigned_flag == 0) item->max_length+= 1; if (item->decimals > 0) item->max_length+= 1; item->set_name(fields_info->field_name, strlen(fields_info->field_name), cs); break; case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: if (!(item= new Item_blob(fields_info->field_name, fields_info->field_length))) { DBUG_RETURN(0); } break; default: /* Don't let unimplemented types pass through. Could be a grave error. */ DBUG_ASSERT(fields_info->field_type == MYSQL_TYPE_STRING); if (!(item= new Item_empty_string("", fields_info->field_length, cs))) { DBUG_RETURN(0); } item->set_name(fields_info->field_name, strlen(fields_info->field_name), cs); break; } field_list.push_back(item); item->maybe_null= (fields_info->field_flags & MY_I_S_MAYBE_NULL); field_count++; } TMP_TABLE_PARAM *tmp_table_param = (TMP_TABLE_PARAM*) (thd->alloc(sizeof(TMP_TABLE_PARAM))); tmp_table_param->init(); tmp_table_param->table_charset= cs; tmp_table_param->field_count= field_count; tmp_table_param->schema_table= 1; SELECT_LEX *select_lex= thd->lex->current_select; if (!(table= create_tmp_table(thd, tmp_table_param, field_list, (ORDER*) 0, 0, 0, (select_lex->options | thd->variables.option_bits | TMP_TABLE_ALL_COLUMNS), HA_POS_ERROR, table_list->alias))) DBUG_RETURN(0); my_bitmap_map* bitmaps= (my_bitmap_map*) thd->alloc(bitmap_buffer_size(field_count)); bitmap_init(&table->def_read_set, (my_bitmap_map*) bitmaps, field_count, FALSE); table->read_set= &table->def_read_set; bitmap_clear_all(table->read_set); table_list->schema_table_param= tmp_table_param; DBUG_RETURN(table); } /* For old SHOW compatibility. It is used when old SHOW doesn't have generated column names Make list of fields for SHOW SYNOPSIS make_old_format() thd thread handler schema_table pointer to 'schema_tables' element RETURN 1 error 0 success */ int make_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { ST_FIELD_INFO *field_info= schema_table->fields_info; Name_resolution_context *context= &thd->lex->select_lex.context; for (; field_info->field_name; field_info++) { if (field_info->old_name) { Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (field) { field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); if (add_item_to_list(thd, field)) return 1; } } } return 0; } int make_schemata_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { char tmp[128]; LEX *lex= thd->lex; SELECT_LEX *sel= lex->current_select; Name_resolution_context *context= &sel->context; if (!sel->item_list.elements) { ST_FIELD_INFO *field_info= &schema_table->fields_info[1]; String buffer(tmp,sizeof(tmp), system_charset_info); Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (!field || add_item_to_list(thd, field)) return 1; buffer.length(0); buffer.append(field_info->old_name); if (lex->wild && lex->wild->ptr()) { buffer.append(STRING_WITH_LEN(" (")); buffer.append(lex->wild->ptr()); buffer.append(')'); } field->set_name(buffer.ptr(), buffer.length(), system_charset_info); } return 0; } int make_table_names_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { char tmp[128]; String buffer(tmp,sizeof(tmp), thd->charset()); LEX *lex= thd->lex; Name_resolution_context *context= &lex->select_lex.context; ST_FIELD_INFO *field_info= &schema_table->fields_info[2]; buffer.length(0); buffer.append(field_info->old_name); buffer.append(lex->select_lex.db); if (lex->wild && lex->wild->ptr()) { buffer.append(STRING_WITH_LEN(" (")); buffer.append(lex->wild->ptr()); buffer.append(')'); } Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (add_item_to_list(thd, field)) return 1; field->set_name(buffer.ptr(), buffer.length(), system_charset_info); if (thd->lex->verbose) { field->set_name(buffer.ptr(), buffer.length(), system_charset_info); field_info= &schema_table->fields_info[3]; field= new Item_field(context, NullS, NullS, field_info->field_name); if (add_item_to_list(thd, field)) return 1; field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); } return 0; } int make_columns_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { int fields_arr[]= {3, 14, 13, 6, 15, 5, 16, 17, 18, -1}; int *field_num= fields_arr; ST_FIELD_INFO *field_info; Name_resolution_context *context= &thd->lex->select_lex.context; for (; *field_num >= 0; field_num++) { field_info= &schema_table->fields_info[*field_num]; if (!thd->lex->verbose && (*field_num == 13 || *field_num == 17 || *field_num == 18)) continue; Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (field) { field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); if (add_item_to_list(thd, field)) return 1; } } return 0; } int make_character_sets_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { int fields_arr[]= {0, 2, 1, 3, -1}; int *field_num= fields_arr; ST_FIELD_INFO *field_info; Name_resolution_context *context= &thd->lex->select_lex.context; for (; *field_num >= 0; field_num++) { field_info= &schema_table->fields_info[*field_num]; Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (field) { field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); if (add_item_to_list(thd, field)) return 1; } } return 0; } int make_proc_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table) { int fields_arr[]= {2, 3, 4, 26, 23, 22, 21, 25, 27, 28, 29, -1}; int *field_num= fields_arr; ST_FIELD_INFO *field_info; Name_resolution_context *context= &thd->lex->select_lex.context; for (; *field_num >= 0; field_num++) { field_info= &schema_table->fields_info[*field_num]; Item_field *field= new Item_field(context, NullS, NullS, field_info->field_name); if (field) { field->set_name(field_info->old_name, strlen(field_info->old_name), system_charset_info); if (add_item_to_list(thd, field)) return 1; } } return 0; } /* Create information_schema table SYNOPSIS mysql_schema_table() thd thread handler lex pointer to LEX table_list pointer to table_list RETURN 0 success 1 error */ int mysql_schema_table(THD *thd, LEX *lex, TABLE_LIST *table_list) { TABLE *table; DBUG_ENTER("mysql_schema_table"); if (!(table= table_list->schema_table->create_table(thd, table_list))) DBUG_RETURN(1); table->s->tmp_table= SYSTEM_TMP_TABLE; table->grant.privilege= SELECT_ACL; /* This test is necessary to make case insensitive file systems + upper case table names(information schema tables) + views working correctly */ if (table_list->schema_table_name) table->alias_name_used= my_strcasecmp(table_alias_charset, table_list->schema_table_name, table_list->alias); table_list->table_name= table->s->table_name.str; table_list->table_name_length= table->s->table_name.length; table_list->table= table; table->next= thd->derived_tables; thd->derived_tables= table; table_list->select_lex->options |= OPTION_SCHEMA_TABLE; lex->safe_to_cache_query= 0; if (table_list->schema_table_reformed) // show command { SELECT_LEX *sel= lex->current_select; Item *item; Field_translator *transl, *org_transl; if (table_list->field_translation) { Field_translator *end= table_list->field_translation_end; for (transl= table_list->field_translation; transl < end; transl++) { if (!transl->item->fixed && transl->item->fix_fields(thd, &transl->item)) DBUG_RETURN(1); } DBUG_RETURN(0); } List_iterator_fast<Item> it(sel->item_list); if (!(transl= (Field_translator*)(thd->stmt_arena-> alloc(sel->item_list.elements * sizeof(Field_translator))))) { DBUG_RETURN(1); } for (org_transl= transl; (item= it++); transl++) { transl->item= item; transl->name= item->name; if (!item->fixed && item->fix_fields(thd, &transl->item)) { DBUG_RETURN(1); } } table_list->field_translation= org_transl; table_list->field_translation_end= transl; } DBUG_RETURN(0); } /* Generate select from information_schema table SYNOPSIS make_schema_select() thd thread handler sel pointer to SELECT_LEX schema_table_idx index of 'schema_tables' element RETURN 0 success 1 error */ int make_schema_select(THD *thd, SELECT_LEX *sel, enum enum_schema_tables schema_table_idx) { ST_SCHEMA_TABLE *schema_table= get_schema_table(schema_table_idx); LEX_STRING db, table; DBUG_ENTER("make_schema_select"); DBUG_PRINT("enter", ("mysql_schema_select: %s", schema_table->table_name)); /* We have to make non const db_name & table_name because of lower_case_table_names */ thd->make_lex_string(&db, INFORMATION_SCHEMA_NAME.str, INFORMATION_SCHEMA_NAME.length, 0); thd->make_lex_string(&table, schema_table->table_name, strlen(schema_table->table_name), 0); if (schema_table->old_format(thd, schema_table) || /* Handle old syntax */ !sel->add_table_to_list(thd, new Table_ident(thd, db, table, 0), 0, 0, TL_READ, MDL_SHARED_READ)) { DBUG_RETURN(1); } DBUG_RETURN(0); } /** Fill INFORMATION_SCHEMA-table, leave correct Diagnostics_area / Warning_info state after itself. This function is a wrapper around ST_SCHEMA_TABLE::fill_table(), which may "partially silence" some errors. The thing is that during fill_table() many errors might be emitted. These errors stem from the nature of fill_table(). For example, SELECT ... FROM INFORMATION_SCHEMA.xxx WHERE TABLE_NAME = 'xxx' results in a number of 'Table <db name>.xxx does not exist' errors, because fill_table() tries to open the 'xxx' table in every possible database. Those errors are cleared (the error status is cleared from Diagnostics_area) inside fill_table(), but they remain in Warning_info (Warning_info is not cleared because it may contain useful warnings). This function is responsible for making sure that Warning_info does not contain warnings corresponding to the cleared errors. @note: THD::no_warnings_for_error used to be set before calling fill_table(), thus those errors didn't go to Warning_info. This is not the case now (THD::no_warnings_for_error was eliminated as a hack), so we need to take care of those warnings here. @param thd Thread context. @param table_list I_S table. @param join_table JOIN/SELECT table. @return Error status. @retval TRUE Error. @retval FALSE Success. */ static bool do_fill_table(THD *thd, TABLE_LIST *table_list, JOIN_TAB *join_table) { // NOTE: fill_table() may generate many "useless" warnings, which will be // ignored afterwards. On the other hand, there might be "useful" // warnings, which should be presented to the user. Warning_info usually // stores no more than THD::variables.max_error_count warnings. // The problem is that "useless warnings" may occupy all the slots in the // Warning_info, so "useful warnings" get rejected. In order to avoid // that problem we create a Warning_info instance, which is capable of // storing "unlimited" number of warnings. Warning_info wi(thd->query_id, true); Warning_info *wi_saved= thd->warning_info; thd->warning_info= &wi; bool res= table_list->schema_table->fill_table( thd, table_list, join_table->select_cond); thd->warning_info= wi_saved; // Pass an error if any. if (thd->stmt_da->is_error()) { thd->warning_info->push_warning(thd, thd->stmt_da->sql_errno(), thd->stmt_da->get_sqlstate(), MYSQL_ERROR::WARN_LEVEL_ERROR, thd->stmt_da->message()); } // Pass warnings (if any). // // Filter out warnings with WARN_LEVEL_ERROR level, because they // correspond to the errors which were filtered out in fill_table(). List_iterator_fast<MYSQL_ERROR> it(wi.warn_list()); MYSQL_ERROR *err; while ((err= it++)) { if (err->get_level() != MYSQL_ERROR::WARN_LEVEL_ERROR) thd->warning_info->push_warning(thd, err); } return res; } /* Fill temporary schema tables before SELECT SYNOPSIS get_schema_tables_result() join join which use schema tables executed_place place where I_S table processed RETURN FALSE success TRUE error */ bool get_schema_tables_result(JOIN *join, enum enum_schema_table_state executed_place) { JOIN_TAB *tmp_join_tab= join->join_tab+join->tables; THD *thd= join->thd; LEX *lex= thd->lex; bool result= 0; DBUG_ENTER("get_schema_tables_result"); for (JOIN_TAB *tab= join->join_tab; tab < tmp_join_tab; tab++) { if (!tab->table || !tab->table->pos_in_table_list) break; TABLE_LIST *table_list= tab->table->pos_in_table_list; if (table_list->schema_table && thd->fill_information_schema_tables()) { bool is_subselect= (&lex->unit != lex->current_select->master_unit() && lex->current_select->master_unit()->item); /* A value of 0 indicates a dummy implementation */ if (table_list->schema_table->fill_table == 0) continue; /* skip I_S optimizations specific to get_all_tables */ if (thd->lex->describe && (table_list->schema_table->fill_table != get_all_tables)) continue; /* If schema table is already processed and the statement is not a subselect then we don't need to fill this table again. If schema table is already processed and schema_table_state != executed_place then table is already processed and we should skip second data processing. */ if (table_list->schema_table_state && (!is_subselect || table_list->schema_table_state != executed_place)) continue; /* if table is used in a subselect and table has been processed earlier with the same 'executed_place' value then we should refresh the table. */ if (table_list->schema_table_state && is_subselect) { table_list->table->file->extra(HA_EXTRA_NO_CACHE); table_list->table->file->extra(HA_EXTRA_RESET_STATE); table_list->table->file->ha_delete_all_rows(); free_io_cache(table_list->table); filesort_free_buffers(table_list->table,1); table_list->table->null_row= 0; } else table_list->table->file->stats.records= 0; if (do_fill_table(thd, table_list, tab)) { result= 1; join->error= 1; tab->read_record.file= table_list->table->file; table_list->schema_table_state= executed_place; break; } tab->read_record.file= table_list->table->file; table_list->schema_table_state= executed_place; } } DBUG_RETURN(result); } struct run_hton_fill_schema_table_args { TABLE_LIST *tables; COND *cond; }; static my_bool run_hton_fill_schema_table(THD *thd, plugin_ref plugin, void *arg) { struct run_hton_fill_schema_table_args *args= (run_hton_fill_schema_table_args *) arg; handlerton *hton= plugin_data(plugin, handlerton *); if (hton->fill_is_table && hton->state == SHOW_OPTION_YES) hton->fill_is_table(hton, thd, args->tables, args->cond, get_schema_table_idx(args->tables->schema_table)); return false; } int hton_fill_schema_table(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_ENTER("hton_fill_schema_table"); struct run_hton_fill_schema_table_args args; args.tables= tables; args.cond= cond; plugin_foreach(thd, run_hton_fill_schema_table, MYSQL_STORAGE_ENGINE_PLUGIN, &args); DBUG_RETURN(0); } ST_FIELD_INFO schema_fields_info[]= { {"CATALOG_NAME", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"SCHEMA_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Database", SKIP_OPEN_TABLE}, {"DEFAULT_CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"DEFAULT_COLLATION_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"SQL_PATH", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO tables_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name", SKIP_OPEN_TABLE}, {"TABLE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"ENGINE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Engine", OPEN_FRM_ONLY}, {"VERSION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Version", OPEN_FRM_ONLY}, {"ROW_FORMAT", 10, MYSQL_TYPE_STRING, 0, 1, "Row_format", OPEN_FULL_TABLE}, {"TABLE_ROWS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Rows", OPEN_FULL_TABLE}, {"AVG_ROW_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Avg_row_length", OPEN_FULL_TABLE}, {"DATA_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_length", OPEN_FULL_TABLE}, {"MAX_DATA_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Max_data_length", OPEN_FULL_TABLE}, {"INDEX_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Index_length", OPEN_FULL_TABLE}, {"DATA_FREE", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_free", OPEN_FULL_TABLE}, {"AUTO_INCREMENT", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Auto_increment", OPEN_FULL_TABLE}, {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Create_time", OPEN_FULL_TABLE}, {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Update_time", OPEN_FULL_TABLE}, {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Check_time", OPEN_FULL_TABLE}, {"TABLE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 1, "Collation", OPEN_FRM_ONLY}, {"CHECKSUM", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Checksum", OPEN_FULL_TABLE}, {"CREATE_OPTIONS", 255, MYSQL_TYPE_STRING, 0, 1, "Create_options", OPEN_FRM_ONLY}, {"TABLE_COMMENT", TABLE_COMMENT_MAXLEN, MYSQL_TYPE_STRING, 0, 0, "Comment", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO columns_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Field", OPEN_FRM_ONLY}, {"ORDINAL_POSITION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FRM_ONLY}, {"COLUMN_DEFAULT", MAX_FIELD_VARCHARLENGTH, MYSQL_TYPE_STRING, 0, 1, "Default", OPEN_FRM_ONLY}, {"IS_NULLABLE", 3, MYSQL_TYPE_STRING, 0, 0, "Null", OPEN_FRM_ONLY}, {"DATA_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"CHARACTER_MAXIMUM_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FRM_ONLY}, {"CHARACTER_OCTET_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FRM_ONLY}, {"NUMERIC_PRECISION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FRM_ONLY}, {"NUMERIC_SCALE", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FRM_ONLY}, {"CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FRM_ONLY}, {"COLLATION_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 1, "Collation", OPEN_FRM_ONLY}, {"COLUMN_TYPE", 65535, MYSQL_TYPE_STRING, 0, 0, "Type", OPEN_FRM_ONLY}, {"COLUMN_KEY", 3, MYSQL_TYPE_STRING, 0, 0, "Key", OPEN_FRM_ONLY}, {"EXTRA", 27, MYSQL_TYPE_STRING, 0, 0, "Extra", OPEN_FRM_ONLY}, {"PRIVILEGES", 80, MYSQL_TYPE_STRING, 0, 0, "Privileges", OPEN_FRM_ONLY}, {"COLUMN_COMMENT", COLUMN_COMMENT_MAXLEN, MYSQL_TYPE_STRING, 0, 0, "Comment", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO charsets_fields_info[]= { {"CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Charset", SKIP_OPEN_TABLE}, {"DEFAULT_COLLATE_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Default collation", SKIP_OPEN_TABLE}, {"DESCRIPTION", 60, MYSQL_TYPE_STRING, 0, 0, "Description", SKIP_OPEN_TABLE}, {"MAXLEN", 3, MYSQL_TYPE_LONGLONG, 0, 0, "Maxlen", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO collation_fields_info[]= { {"COLLATION_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Collation", SKIP_OPEN_TABLE}, {"CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Charset", SKIP_OPEN_TABLE}, {"ID", MY_INT32_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 0, "Id", SKIP_OPEN_TABLE}, {"IS_DEFAULT", 3, MYSQL_TYPE_STRING, 0, 0, "Default", SKIP_OPEN_TABLE}, {"IS_COMPILED", 3, MYSQL_TYPE_STRING, 0, 0, "Compiled", SKIP_OPEN_TABLE}, {"SORTLEN", 3, MYSQL_TYPE_LONGLONG, 0, 0, "Sortlen", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO engines_fields_info[]= { {"ENGINE", 64, MYSQL_TYPE_STRING, 0, 0, "Engine", SKIP_OPEN_TABLE}, {"SUPPORT", 8, MYSQL_TYPE_STRING, 0, 0, "Support", SKIP_OPEN_TABLE}, {"COMMENT", 80, MYSQL_TYPE_STRING, 0, 0, "Comment", SKIP_OPEN_TABLE}, {"TRANSACTIONS", 3, MYSQL_TYPE_STRING, 0, 1, "Transactions", SKIP_OPEN_TABLE}, {"XA", 3, MYSQL_TYPE_STRING, 0, 1, "XA", SKIP_OPEN_TABLE}, {"SAVEPOINTS", 3 ,MYSQL_TYPE_STRING, 0, 1, "Savepoints", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO events_fields_info[]= { {"EVENT_CATALOG", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"EVENT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Db", SKIP_OPEN_TABLE}, {"EVENT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name", SKIP_OPEN_TABLE}, {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer", SKIP_OPEN_TABLE}, {"TIME_ZONE", 64, MYSQL_TYPE_STRING, 0, 0, "Time zone", SKIP_OPEN_TABLE}, {"EVENT_BODY", 8, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"EVENT_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"EVENT_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, "Type", SKIP_OPEN_TABLE}, {"EXECUTE_AT", 0, MYSQL_TYPE_DATETIME, 0, 1, "Execute at", SKIP_OPEN_TABLE}, {"INTERVAL_VALUE", 256, MYSQL_TYPE_STRING, 0, 1, "Interval value", SKIP_OPEN_TABLE}, {"INTERVAL_FIELD", 18, MYSQL_TYPE_STRING, 0, 1, "Interval field", SKIP_OPEN_TABLE}, {"SQL_MODE", 32*256, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"STARTS", 0, MYSQL_TYPE_DATETIME, 0, 1, "Starts", SKIP_OPEN_TABLE}, {"ENDS", 0, MYSQL_TYPE_DATETIME, 0, 1, "Ends", SKIP_OPEN_TABLE}, {"STATUS", 18, MYSQL_TYPE_STRING, 0, 0, "Status", SKIP_OPEN_TABLE}, {"ON_COMPLETION", 12, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 0, 0, SKIP_OPEN_TABLE}, {"LAST_ALTERED", 0, MYSQL_TYPE_DATETIME, 0, 0, 0, SKIP_OPEN_TABLE}, {"LAST_EXECUTED", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, SKIP_OPEN_TABLE}, {"EVENT_COMMENT", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ORIGINATOR", 10, MYSQL_TYPE_LONGLONG, 0, 0, "Originator", SKIP_OPEN_TABLE}, {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "character_set_client", SKIP_OPEN_TABLE}, {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "collation_connection", SKIP_OPEN_TABLE}, {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Database Collation", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO coll_charset_app_fields_info[]= { {"COLLATION_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"CHARACTER_SET_NAME", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO proc_fields_info[]= { {"SPECIFIC_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ROUTINE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ROUTINE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Db", SKIP_OPEN_TABLE}, {"ROUTINE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name", SKIP_OPEN_TABLE}, {"ROUTINE_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, "Type", SKIP_OPEN_TABLE}, {"DATA_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"CHARACTER_MAXIMUM_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"CHARACTER_OCTET_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"NUMERIC_PRECISION", 21 , MYSQL_TYPE_LONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"NUMERIC_SCALE", 21 , MYSQL_TYPE_LONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"DTD_IDENTIFIER", 65535, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"ROUTINE_BODY", 8, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ROUTINE_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"EXTERNAL_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"EXTERNAL_LANGUAGE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"PARAMETER_STYLE", 8, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_DETERMINISTIC", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"SQL_DATA_ACCESS", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"SQL_PATH", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"SECURITY_TYPE", 7, MYSQL_TYPE_STRING, 0, 0, "Security_type", SKIP_OPEN_TABLE}, {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 0, "Created", SKIP_OPEN_TABLE}, {"LAST_ALTERED", 0, MYSQL_TYPE_DATETIME, 0, 0, "Modified", SKIP_OPEN_TABLE}, {"SQL_MODE", 32*256, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ROUTINE_COMMENT", 65535, MYSQL_TYPE_STRING, 0, 0, "Comment", SKIP_OPEN_TABLE}, {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer", SKIP_OPEN_TABLE}, {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "character_set_client", SKIP_OPEN_TABLE}, {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "collation_connection", SKIP_OPEN_TABLE}, {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Database Collation", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO stat_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table", OPEN_FRM_ONLY}, {"NON_UNIQUE", 1, MYSQL_TYPE_LONGLONG, 0, 0, "Non_unique", OPEN_FRM_ONLY}, {"INDEX_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"INDEX_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Key_name", OPEN_FRM_ONLY}, {"SEQ_IN_INDEX", 2, MYSQL_TYPE_LONGLONG, 0, 0, "Seq_in_index", OPEN_FRM_ONLY}, {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Column_name", OPEN_FRM_ONLY}, {"COLLATION", 1, MYSQL_TYPE_STRING, 0, 1, "Collation", OPEN_FRM_ONLY}, {"CARDINALITY", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 1, "Cardinality", OPEN_FULL_TABLE}, {"SUB_PART", 3, MYSQL_TYPE_LONGLONG, 0, 1, "Sub_part", OPEN_FRM_ONLY}, {"PACKED", 10, MYSQL_TYPE_STRING, 0, 1, "Packed", OPEN_FRM_ONLY}, {"NULLABLE", 3, MYSQL_TYPE_STRING, 0, 0, "Null", OPEN_FRM_ONLY}, {"INDEX_TYPE", 16, MYSQL_TYPE_STRING, 0, 0, "Index_type", OPEN_FULL_TABLE}, {"COMMENT", 16, MYSQL_TYPE_STRING, 0, 1, "Comment", OPEN_FRM_ONLY}, {"INDEX_COMMENT", INDEX_COMMENT_MAXLEN, MYSQL_TYPE_STRING, 0, 0, "Index_comment", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO view_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"VIEW_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"CHECK_OPTION", 8, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"IS_UPDATABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"SECURITY_TYPE", 7, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO user_privileges_fields_info[]= { {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO schema_privileges_fields_info[]= { {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO table_privileges_fields_info[]= { {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO column_privileges_fields_info[]= { {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO table_constraints_fields_info[]= { {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO key_column_usage_fields_info[]= { {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"ORDINAL_POSITION", 10 ,MYSQL_TYPE_LONGLONG, 0, 0, 0, OPEN_FULL_TABLE}, {"POSITION_IN_UNIQUE_CONSTRAINT", 10 ,MYSQL_TYPE_LONGLONG, 0, 1, 0, OPEN_FULL_TABLE}, {"REFERENCED_TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"REFERENCED_TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"REFERENCED_COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO table_names_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Tables_in_", SKIP_OPEN_TABLE}, {"TABLE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table_type", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO open_tables_fields_info[]= { {"Database", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Database", SKIP_OPEN_TABLE}, {"Table",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table", SKIP_OPEN_TABLE}, {"In_use", 1, MYSQL_TYPE_LONGLONG, 0, 0, "In_use", SKIP_OPEN_TABLE}, {"Name_locked", 4, MYSQL_TYPE_LONGLONG, 0, 0, "Name_locked", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO triggers_fields_info[]= { {"TRIGGER_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TRIGGER_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"TRIGGER_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Trigger", OPEN_FRM_ONLY}, {"EVENT_MANIPULATION", 6, MYSQL_TYPE_STRING, 0, 0, "Event", OPEN_FRM_ONLY}, {"EVENT_OBJECT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"EVENT_OBJECT_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"EVENT_OBJECT_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table", OPEN_FRM_ONLY}, {"ACTION_ORDER", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0, OPEN_FRM_ONLY}, {"ACTION_CONDITION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FRM_ONLY}, {"ACTION_STATEMENT", 65535, MYSQL_TYPE_STRING, 0, 0, "Statement", OPEN_FRM_ONLY}, {"ACTION_ORIENTATION", 9, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"ACTION_TIMING", 6, MYSQL_TYPE_STRING, 0, 0, "Timing", OPEN_FRM_ONLY}, {"ACTION_REFERENCE_OLD_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FRM_ONLY}, {"ACTION_REFERENCE_NEW_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FRM_ONLY}, {"ACTION_REFERENCE_OLD_ROW", 3, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"ACTION_REFERENCE_NEW_ROW", 3, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FRM_ONLY}, {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 1, "Created", OPEN_FRM_ONLY}, {"SQL_MODE", 32*256, MYSQL_TYPE_STRING, 0, 0, "sql_mode", OPEN_FRM_ONLY}, {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer", OPEN_FRM_ONLY}, {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "character_set_client", OPEN_FRM_ONLY}, {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "collation_connection", OPEN_FRM_ONLY}, {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, "Database Collation", OPEN_FRM_ONLY}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO partitions_fields_info[]= { {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"PARTITION_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"SUBPARTITION_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"PARTITION_ORDINAL_POSITION", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FULL_TABLE}, {"SUBPARTITION_ORDINAL_POSITION", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FULL_TABLE}, {"PARTITION_METHOD", 18, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"SUBPARTITION_METHOD", 12, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"PARTITION_EXPRESSION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"SUBPARTITION_EXPRESSION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"PARTITION_DESCRIPTION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"TABLE_ROWS", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"AVG_ROW_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"MAX_DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FULL_TABLE}, {"INDEX_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"DATA_FREE", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0, OPEN_FULL_TABLE}, {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, OPEN_FULL_TABLE}, {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, OPEN_FULL_TABLE}, {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, OPEN_FULL_TABLE}, {"CHECKSUM", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, OPEN_FULL_TABLE}, {"PARTITION_COMMENT", 80, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"NODEGROUP", 12 , MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLESPACE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO variables_fields_info[]= { {"VARIABLE_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Variable_name", SKIP_OPEN_TABLE}, {"VARIABLE_VALUE", 1024, MYSQL_TYPE_STRING, 0, 1, "Value", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO processlist_fields_info[]= { {"ID", 4, MYSQL_TYPE_LONGLONG, 0, 0, "Id", SKIP_OPEN_TABLE}, {"USER", 16, MYSQL_TYPE_STRING, 0, 0, "User", SKIP_OPEN_TABLE}, {"HOST", LIST_PROCESS_HOST_LEN, MYSQL_TYPE_STRING, 0, 0, "Host", SKIP_OPEN_TABLE}, {"DB", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Db", SKIP_OPEN_TABLE}, {"COMMAND", 16, MYSQL_TYPE_STRING, 0, 0, "Command", SKIP_OPEN_TABLE}, {"TIME", 7, MYSQL_TYPE_LONG, 0, 0, "Time", SKIP_OPEN_TABLE}, {"STATE", 64, MYSQL_TYPE_STRING, 0, 1, "State", SKIP_OPEN_TABLE}, {"INFO", PROCESS_LIST_INFO_WIDTH, MYSQL_TYPE_STRING, 0, 1, "Info", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO plugin_fields_info[]= { {"PLUGIN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name", SKIP_OPEN_TABLE}, {"PLUGIN_VERSION", 20, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PLUGIN_STATUS", 10, MYSQL_TYPE_STRING, 0, 0, "Status", SKIP_OPEN_TABLE}, {"PLUGIN_TYPE", 80, MYSQL_TYPE_STRING, 0, 0, "Type", SKIP_OPEN_TABLE}, {"PLUGIN_TYPE_VERSION", 20, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"PLUGIN_LIBRARY", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Library", SKIP_OPEN_TABLE}, {"PLUGIN_LIBRARY_VERSION", 20, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"PLUGIN_AUTHOR", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"PLUGIN_DESCRIPTION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"PLUGIN_LICENSE", 80, MYSQL_TYPE_STRING, 0, 1, "License", SKIP_OPEN_TABLE}, {"LOAD_OPTION", 64, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO files_fields_info[]= { {"FILE_ID", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0, SKIP_OPEN_TABLE}, {"FILE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"FILE_TYPE", 20, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLESPACE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"TABLE_CATALOG", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"LOGFILE_GROUP_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"LOGFILE_GROUP_NUMBER", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"ENGINE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"FULLTEXT_KEYS", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {"DELETED_ROWS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"UPDATE_COUNT", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"FREE_EXTENTS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"TOTAL_EXTENTS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"EXTENT_SIZE", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0, SKIP_OPEN_TABLE}, {"INITIAL_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, SKIP_OPEN_TABLE}, {"MAXIMUM_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, SKIP_OPEN_TABLE}, {"AUTOEXTEND_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0, SKIP_OPEN_TABLE}, {"CREATION_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, SKIP_OPEN_TABLE}, {"LAST_UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, SKIP_OPEN_TABLE}, {"LAST_ACCESS_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0, SKIP_OPEN_TABLE}, {"RECOVER_TIME", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"TRANSACTION_COUNTER", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0, SKIP_OPEN_TABLE}, {"VERSION", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Version", SKIP_OPEN_TABLE}, {"ROW_FORMAT", 10, MYSQL_TYPE_STRING, 0, 1, "Row_format", SKIP_OPEN_TABLE}, {"TABLE_ROWS", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Rows", SKIP_OPEN_TABLE}, {"AVG_ROW_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Avg_row_length", SKIP_OPEN_TABLE}, {"DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_length", SKIP_OPEN_TABLE}, {"MAX_DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Max_data_length", SKIP_OPEN_TABLE}, {"INDEX_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Index_length", SKIP_OPEN_TABLE}, {"DATA_FREE", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_free", SKIP_OPEN_TABLE}, {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Create_time", SKIP_OPEN_TABLE}, {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Update_time", SKIP_OPEN_TABLE}, {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Check_time", SKIP_OPEN_TABLE}, {"CHECKSUM", 21 , MYSQL_TYPE_LONGLONG, 0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Checksum", SKIP_OPEN_TABLE}, {"STATUS", 20, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"EXTRA", 255, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; void init_fill_schema_files_row(TABLE* table) { int i; for(i=0; files_fields_info[i].field_name!=NULL; i++) table->field[i]->set_null(); table->field[IS_FILES_STATUS]->set_notnull(); table->field[IS_FILES_STATUS]->store("NORMAL", 6, system_charset_info); } ST_FIELD_INFO referential_constraints_fields_info[]= { {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"UNIQUE_CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"UNIQUE_CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"UNIQUE_CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, MY_I_S_MAYBE_NULL, 0, OPEN_FULL_TABLE}, {"MATCH_OPTION", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"UPDATE_RULE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"DELETE_RULE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"REFERENCED_TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; ST_FIELD_INFO parameters_fields_info[]= { {"SPECIFIC_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"SPECIFIC_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"SPECIFIC_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"ORDINAL_POSITION", 21 , MYSQL_TYPE_LONG, 0, 0, 0, OPEN_FULL_TABLE}, {"PARAMETER_MODE", 5, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"PARAMETER_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"DATA_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"CHARACTER_MAXIMUM_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0, OPEN_FULL_TABLE}, {"CHARACTER_OCTET_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0, OPEN_FULL_TABLE}, {"NUMERIC_PRECISION", 21 , MYSQL_TYPE_LONG, 0, 1, 0, OPEN_FULL_TABLE}, {"NUMERIC_SCALE", 21 , MYSQL_TYPE_LONG, 0, 1, 0, OPEN_FULL_TABLE}, {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0, OPEN_FULL_TABLE}, {"DTD_IDENTIFIER", 65535, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {"ROUTINE_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, OPEN_FULL_TABLE} }; ST_FIELD_INFO tablespaces_fields_info[]= { {"TABLESPACE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"ENGINE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {"TABLESPACE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, MY_I_S_MAYBE_NULL, 0, SKIP_OPEN_TABLE}, {"LOGFILE_GROUP_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, MY_I_S_MAYBE_NULL, 0, SKIP_OPEN_TABLE}, {"EXTENT_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED, 0, SKIP_OPEN_TABLE}, {"AUTOEXTEND_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED, 0, SKIP_OPEN_TABLE}, {"MAXIMUM_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED, 0, SKIP_OPEN_TABLE}, {"NODEGROUP_ID", 21, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED, 0, SKIP_OPEN_TABLE}, {"TABLESPACE_COMMENT", 2048, MYSQL_TYPE_STRING, 0, MY_I_S_MAYBE_NULL, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; /* Description of ST_FIELD_INFO in table.h Make sure that the order of schema_tables and enum_schema_tables are the same. */ ST_SCHEMA_TABLE schema_tables[]= { {"CHARACTER_SETS", charsets_fields_info, create_schema_table, fill_schema_charsets, make_character_sets_old_format, 0, -1, -1, 0, 0}, {"COLLATIONS", collation_fields_info, create_schema_table, fill_schema_collation, make_old_format, 0, -1, -1, 0, 0}, {"COLLATION_CHARACTER_SET_APPLICABILITY", coll_charset_app_fields_info, create_schema_table, fill_schema_coll_charset_app, 0, 0, -1, -1, 0, 0}, {"COLUMNS", columns_fields_info, create_schema_table, get_all_tables, make_columns_old_format, get_schema_column_record, 1, 2, 0, OPTIMIZE_I_S_TABLE|OPEN_VIEW_FULL}, {"COLUMN_PRIVILEGES", column_privileges_fields_info, create_schema_table, fill_schema_column_privileges, 0, 0, -1, -1, 0, 0}, {"ENGINES", engines_fields_info, create_schema_table, fill_schema_engines, make_old_format, 0, -1, -1, 0, 0}, #ifdef HAVE_EVENT_SCHEDULER {"EVENTS", events_fields_info, create_schema_table, Events::fill_schema_events, make_old_format, 0, -1, -1, 0, 0}, #else {"EVENTS", events_fields_info, create_schema_table, 0, make_old_format, 0, -1, -1, 0, 0}, #endif {"FILES", files_fields_info, create_schema_table, hton_fill_schema_table, 0, 0, -1, -1, 0, 0}, {"GLOBAL_STATUS", variables_fields_info, create_schema_table, fill_status, make_old_format, 0, 0, -1, 0, 0}, {"GLOBAL_VARIABLES", variables_fields_info, create_schema_table, fill_variables, make_old_format, 0, 0, -1, 0, 0}, {"KEY_COLUMN_USAGE", key_column_usage_fields_info, create_schema_table, get_all_tables, 0, get_schema_key_column_usage_record, 4, 5, 0, OPTIMIZE_I_S_TABLE|OPEN_TABLE_ONLY}, {"OPEN_TABLES", open_tables_fields_info, create_schema_table, fill_open_tables, make_old_format, 0, -1, -1, 1, 0}, {"PARAMETERS", parameters_fields_info, create_schema_table, fill_schema_proc, 0, 0, -1, -1, 0, 0}, {"PARTITIONS", partitions_fields_info, create_schema_table, get_all_tables, 0, get_schema_partitions_record, 1, 2, 0, OPTIMIZE_I_S_TABLE|OPEN_TABLE_ONLY}, {"PLUGINS", plugin_fields_info, create_schema_table, fill_plugins, make_old_format, 0, -1, -1, 0, 0}, {"PROCESSLIST", processlist_fields_info, create_schema_table, fill_schema_processlist, make_old_format, 0, -1, -1, 0, 0}, {"PROFILING", query_profile_statistics_info, create_schema_table, fill_query_profile_statistics_info, make_profile_table_for_show, NULL, -1, -1, false, 0}, {"REFERENTIAL_CONSTRAINTS", referential_constraints_fields_info, create_schema_table, get_all_tables, 0, get_referential_constraints_record, 1, 9, 0, OPTIMIZE_I_S_TABLE|OPEN_TABLE_ONLY}, {"ROUTINES", proc_fields_info, create_schema_table, fill_schema_proc, make_proc_old_format, 0, -1, -1, 0, 0}, {"SCHEMATA", schema_fields_info, create_schema_table, fill_schema_schemata, make_schemata_old_format, 0, 1, -1, 0, 0}, {"SCHEMA_PRIVILEGES", schema_privileges_fields_info, create_schema_table, fill_schema_schema_privileges, 0, 0, -1, -1, 0, 0}, {"SESSION_STATUS", variables_fields_info, create_schema_table, fill_status, make_old_format, 0, 0, -1, 0, 0}, {"SESSION_VARIABLES", variables_fields_info, create_schema_table, fill_variables, make_old_format, 0, 0, -1, 0, 0}, {"STATISTICS", stat_fields_info, create_schema_table, get_all_tables, make_old_format, get_schema_stat_record, 1, 2, 0, OPEN_TABLE_ONLY|OPTIMIZE_I_S_TABLE}, {"STATUS", variables_fields_info, create_schema_table, fill_status, make_old_format, 0, 0, -1, 1, 0}, {"TABLES", tables_fields_info, create_schema_table, get_all_tables, make_old_format, get_schema_tables_record, 1, 2, 0, OPTIMIZE_I_S_TABLE}, {"TABLESPACES", tablespaces_fields_info, create_schema_table, hton_fill_schema_table, 0, 0, -1, -1, 0, 0}, {"TABLE_CONSTRAINTS", table_constraints_fields_info, create_schema_table, get_all_tables, 0, get_schema_constraints_record, 3, 4, 0, OPTIMIZE_I_S_TABLE|OPEN_TABLE_ONLY}, {"TABLE_NAMES", table_names_fields_info, create_schema_table, get_all_tables, make_table_names_old_format, 0, 1, 2, 1, 0}, {"TABLE_PRIVILEGES", table_privileges_fields_info, create_schema_table, fill_schema_table_privileges, 0, 0, -1, -1, 0, 0}, {"TRIGGERS", triggers_fields_info, create_schema_table, get_all_tables, make_old_format, get_schema_triggers_record, 5, 6, 0, OPEN_TRIGGER_ONLY|OPTIMIZE_I_S_TABLE}, {"USER_PRIVILEGES", user_privileges_fields_info, create_schema_table, fill_schema_user_privileges, 0, 0, -1, -1, 0, 0}, {"VARIABLES", variables_fields_info, create_schema_table, fill_variables, make_old_format, 0, 0, -1, 1, 0}, {"VIEWS", view_fields_info, create_schema_table, get_all_tables, 0, get_schema_views_record, 1, 2, 0, OPEN_VIEW_ONLY|OPTIMIZE_I_S_TABLE}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; #ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION template class List_iterator_fast<char>; template class List<char>; #endif int initialize_schema_table(st_plugin_int *plugin) { ST_SCHEMA_TABLE *schema_table; DBUG_ENTER("initialize_schema_table"); if (!(schema_table= (ST_SCHEMA_TABLE *)my_malloc(sizeof(ST_SCHEMA_TABLE), MYF(MY_WME | MY_ZEROFILL)))) DBUG_RETURN(1); /* Historical Requirement */ plugin->data= schema_table; // shortcut for the future if (plugin->plugin->init) { schema_table->create_table= create_schema_table; schema_table->old_format= make_old_format; schema_table->idx_field1= -1, schema_table->idx_field2= -1; /* Make the name available to the init() function. */ schema_table->table_name= plugin->name.str; if (plugin->plugin->init(schema_table)) { sql_print_error("Plugin '%s' init function returned error.", plugin->name.str); plugin->data= NULL; my_free(schema_table); DBUG_RETURN(1); } /* Make sure the plugin name is not set inside the init() function. */ schema_table->table_name= plugin->name.str; } DBUG_RETURN(0); } int finalize_schema_table(st_plugin_int *plugin) { ST_SCHEMA_TABLE *schema_table= (ST_SCHEMA_TABLE *)plugin->data; DBUG_ENTER("finalize_schema_table"); if (schema_table) { if (plugin->plugin->deinit) { DBUG_PRINT("info", ("Deinitializing plugin: '%s'", plugin->name.str)); if (plugin->plugin->deinit(NULL)) { DBUG_PRINT("warning", ("Plugin '%s' deinit function returned error.", plugin->name.str)); } } my_free(schema_table); } DBUG_RETURN(0); } /** Output trigger information (SHOW CREATE TRIGGER) to the client. @param thd Thread context. @param triggers List of triggers for the table. @param trigger_idx Index of the trigger to dump. @return Operation status @retval TRUE Error. @retval FALSE Success. */ static bool show_create_trigger_impl(THD *thd, Table_triggers_list *triggers, int trigger_idx) { int ret_code; Protocol *p= thd->protocol; List<Item> fields; LEX_STRING trg_name; ulonglong trg_sql_mode; LEX_STRING trg_sql_mode_str; LEX_STRING trg_sql_original_stmt; LEX_STRING trg_client_cs_name; LEX_STRING trg_connection_cl_name; LEX_STRING trg_db_cl_name; CHARSET_INFO *trg_client_cs; /* TODO: Check privileges here. This functionality will be added by implementation of the following WL items: - WL#2227: New privileges for new objects - WL#3482: Protect SHOW CREATE PROCEDURE | FUNCTION | VIEW | TRIGGER properly SHOW TRIGGERS and I_S.TRIGGERS will be affected too. */ /* Prepare trigger "object". */ triggers->get_trigger_info(thd, trigger_idx, &trg_name, &trg_sql_mode, &trg_sql_original_stmt, &trg_client_cs_name, &trg_connection_cl_name, &trg_db_cl_name); sql_mode_string_representation(thd, trg_sql_mode, &trg_sql_mode_str); /* Resolve trigger client character set. */ if (resolve_charset(trg_client_cs_name.str, NULL, &trg_client_cs)) return TRUE; /* Send header. */ fields.push_back(new Item_empty_string("Trigger", NAME_LEN)); fields.push_back(new Item_empty_string("sql_mode", trg_sql_mode_str.length)); { /* NOTE: SQL statement field must be not less than 1024 in order not to confuse old clients. */ Item_empty_string *stmt_fld= new Item_empty_string("SQL Original Statement", max(trg_sql_original_stmt.length, 1024)); stmt_fld->maybe_null= TRUE; fields.push_back(stmt_fld); } fields.push_back(new Item_empty_string("character_set_client", MY_CS_NAME_SIZE)); fields.push_back(new Item_empty_string("collation_connection", MY_CS_NAME_SIZE)); fields.push_back(new Item_empty_string("Database Collation", MY_CS_NAME_SIZE)); if (p->send_result_set_metadata(&fields, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) return TRUE; /* Send data. */ p->prepare_for_resend(); p->store(trg_name.str, trg_name.length, system_charset_info); p->store(trg_sql_mode_str.str, trg_sql_mode_str.length, system_charset_info); p->store(trg_sql_original_stmt.str, trg_sql_original_stmt.length, trg_client_cs); p->store(trg_client_cs_name.str, trg_client_cs_name.length, system_charset_info); p->store(trg_connection_cl_name.str, trg_connection_cl_name.length, system_charset_info); p->store(trg_db_cl_name.str, trg_db_cl_name.length, system_charset_info); ret_code= p->write(); if (!ret_code) my_eof(thd); return ret_code != 0; } /** Read TRN and TRG files to obtain base table name for the specified trigger name and construct TABE_LIST object for the base table. @param thd Thread context. @param trg_name Trigger name. @return TABLE_LIST object corresponding to the base table. TODO: This function is a copy&paste from add_table_to_list() and sp_add_to_query_tables(). The problem is that in order to be compatible with Stored Programs (Prepared Statements), we should not touch thd->lex. The "source" functions also add created TABLE_LIST object to the thd->lex->query_tables. The plan to eliminate this copy&paste is to: - get rid of sp_add_to_query_tables() and use Lex::add_table_to_list(). Only add_table_to_list() must be used to add tables from the parser into Lex::query_tables list. - do not update Lex::query_tables in add_table_to_list(). */ static TABLE_LIST *get_trigger_table(THD *thd, const sp_name *trg_name) { char trn_path_buff[FN_REFLEN]; LEX_STRING trn_path= { trn_path_buff, 0 }; LEX_STRING db; LEX_STRING tbl_name; TABLE_LIST *table; build_trn_path(thd, trg_name, &trn_path); if (check_trn_exists(&trn_path)) { my_error(ER_TRG_DOES_NOT_EXIST, MYF(0)); return NULL; } if (load_table_name_for_trigger(thd, trg_name, &trn_path, &tbl_name)) return NULL; /* We need to reset statement table list to be PS/SP friendly. */ if (!(table= (TABLE_LIST*) thd->alloc(sizeof(TABLE_LIST)))) return NULL; db= trg_name->m_db; db.str= thd->strmake(db.str, db.length); tbl_name.str= thd->strmake(tbl_name.str, tbl_name.length); if (db.str == NULL || tbl_name.str == NULL) return NULL; table->init_one_table(db.str, db.length, tbl_name.str, tbl_name.length, tbl_name.str, TL_IGNORE); return table; } /** SHOW CREATE TRIGGER high-level implementation. @param thd Thread context. @param trg_name Trigger name. @return Operation status @retval TRUE Error. @retval FALSE Success. */ bool show_create_trigger(THD *thd, const sp_name *trg_name) { TABLE_LIST *lst= get_trigger_table(thd, trg_name); uint num_tables; /* NOTE: unused, only to pass to open_tables(). */ Table_triggers_list *triggers; int trigger_idx; bool error= TRUE; if (!lst) return TRUE; if (check_table_access(thd, TRIGGER_ACL, lst, FALSE, 1, TRUE)) { my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "TRIGGER"); return TRUE; } /* Metadata locks taken during SHOW CREATE TRIGGER should be released when the statement completes as it is an information statement. */ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint(); /* Open the table by name in order to load Table_triggers_list object. */ if (open_tables(thd, &lst, &num_tables, MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL)) { my_error(ER_TRG_CANT_OPEN_TABLE, MYF(0), (const char *) trg_name->m_db.str, (const char *) lst->table_name); goto exit; /* Perform closing actions and return error status. */ } triggers= lst->table->triggers; if (!triggers) { my_error(ER_TRG_DOES_NOT_EXIST, MYF(0)); goto exit; } trigger_idx= triggers->find_trigger_by_name(&trg_name->m_name); if (trigger_idx < 0) { my_error(ER_TRG_CORRUPTED_FILE, MYF(0), (const char *) trg_name->m_db.str, (const char *) lst->table_name); goto exit; } error= show_create_trigger_impl(thd, triggers, trigger_idx); /* NOTE: if show_create_trigger_impl() failed, that means we could not send data to the client. In this case we simply raise the error status and client connection will be closed. */ exit: close_thread_tables(thd); /* Release any metadata locks taken during SHOW CREATE TRIGGER. */ thd->mdl_context.rollback_to_savepoint(mdl_savepoint); return error; } class IS_internal_schema_access : public ACL_internal_schema_access { public: IS_internal_schema_access() {} ~IS_internal_schema_access() {} ACL_internal_access_result check(ulong want_access, ulong *save_priv) const; const ACL_internal_table_access *lookup(const char *name) const; }; ACL_internal_access_result IS_internal_schema_access::check(ulong want_access, ulong *save_priv) const { want_access &= ~SELECT_ACL; /* We don't allow any simple privileges but SELECT_ACL on the information_schema database. */ if (unlikely(want_access & DB_ACLS)) return ACL_INTERNAL_ACCESS_DENIED; /* Always grant SELECT for the information schema. */ *save_priv|= SELECT_ACL; return want_access ? ACL_INTERNAL_ACCESS_CHECK_GRANT : ACL_INTERNAL_ACCESS_GRANTED; } const ACL_internal_table_access * IS_internal_schema_access::lookup(const char *name) const { /* There are no per table rules for the information schema. */ return NULL; } static IS_internal_schema_access is_internal_schema_access; void initialize_information_schema_acl() { ACL_internal_schema_registry::register_schema(&INFORMATION_SCHEMA_NAME, &is_internal_schema_access); } #ifdef WITH_PARTITION_STORAGE_ENGINE /* Convert a string in character set in column character set format to utf8 character set if possible, the utf8 character set string will later possibly be converted to character set used by client. Thus we attempt conversion from column character set to both utf8 and to character set client. Examples of strings that should fail conversion to utf8 are unassigned characters as e.g. 0x81 in cp1250 (Windows character set for for countries like Czech and Poland). Example of string that should fail conversion to character set on client (e.g. if this is latin1) is 0x2020 (daggger) in ucs2. If the conversion fails we will as a fall back convert the string to hex encoded format. The caller of the function can also ask for hex encoded format of output string unconditionally. SYNOPSIS get_cs_converted_string_value() thd Thread object input_str Input string in cs character set output_str Output string to be produced in utf8 cs Character set of input string use_hex Use hex string unconditionally RETURN VALUES No return value */ static void get_cs_converted_string_value(THD *thd, String *input_str, String *output_str, CHARSET_INFO *cs, bool use_hex) { output_str->length(0); if (input_str->length() == 0) { output_str->append("''"); return; } if (!use_hex) { String try_val; uint try_conv_error= 0; try_val.copy(input_str->ptr(), input_str->length(), cs, thd->variables.character_set_client, &try_conv_error); if (!try_conv_error) { String val; uint conv_error= 0; val.copy(input_str->ptr(), input_str->length(), cs, system_charset_info, &conv_error); if (!conv_error) { append_unescaped(output_str, val.ptr(), val.length()); return; } } /* We had a conversion error, use hex encoded string for safety */ } { const uchar *ptr; uint i, len; char buf[3]; output_str->append("_"); output_str->append(cs->csname); output_str->append(" "); output_str->append("0x"); len= input_str->length(); ptr= (uchar*)input_str->ptr(); for (i= 0; i < len; i++) { uint high, low; high= (*ptr) >> 4; low= (*ptr) & 0x0F; buf[0]= _dig_vec_upper[high]; buf[1]= _dig_vec_upper[low]; buf[2]= 0; output_str->append((const char*)buf); ptr++; } } return; } #endif
#ifdef _WIN32 #include <windows.h> #include <conio.h> #else #include <unistd.h> // for close() #include <fcntl.h> // for open() #include <sys/ioctl.h> #endif #include "libtorrent/config.hpp" #include "print.hpp" #include <stdlib.h> // for atoi #include <string.h> // for strlen #include <cmath> #include <algorithm> // for std::min #include <iterator> // for back_inserter char const* esc(char const* code) { // this is a silly optimization // to avoid copying of strings enum { num_strings = 200 }; static char buf[num_strings][20]; static int round_robin = 0; char* ret = buf[round_robin]; ++round_robin; if (round_robin >= num_strings) round_robin = 0; ret[0] = '\033'; ret[1] = '['; int i = 2; int j = 0; while (code[j]) ret[i++] = code[j++]; ret[i++] = 'm'; ret[i++] = 0; return ret; } std::string to_string(int v, int width) { char buf[100]; snprintf(buf, sizeof(buf), "%*d", width, v); return buf; } std::string add_suffix(float val, char const* suffix) { std::string ret; if (val == 0) { ret.resize(4 + 2, ' '); if (suffix) ret.resize(4 + 2 + strlen(suffix), ' '); return ret; } const char* prefix[] = {"kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); for (int i = 0; i < num_prefix; ++i) { val /= 1000.f; if (std::fabs(val) < 1000.f) { ret = to_string(val, 4); ret += prefix[i]; if (suffix) ret += suffix; return ret; } } ret = to_string(val, 4); ret += "PB"; if (suffix) ret += suffix; return ret; } std::string color(std::string const& s, color_code c) { if (c == col_none) return s; char buf[1024]; snprintf(buf, sizeof(buf), "\x1b[3%dm%s\x1b[39m", c, s.c_str()); return buf; } std::string const& progress_bar(int progress, int width, color_code c , char fill, char bg, std::string caption, int flags) { static std::string bar; bar.clear(); bar.reserve(width + 10); int progress_chars = (progress * width + 500) / 1000; if (caption.empty()) { char code[10]; snprintf(code, sizeof(code), "\x1b[3%dm", c); bar = code; std::fill_n(std::back_inserter(bar), progress_chars, fill); std::fill_n(std::back_inserter(bar), width - progress_chars, bg); bar += esc("39"); } else { // foreground color (depends a bit on background color) color_code tc = col_black; if (c == col_black || c == col_blue) tc = col_white; caption.resize(width, ' '); char str[256]; if (flags & progress_invert) snprintf(str, sizeof(str), "\x1b[48;5;238m\x1b[37m%s\x1b[4%d;3%dm%s\x1b[49;39m" , caption.substr(0, progress_chars).c_str(), c, tc , caption.substr(progress_chars).c_str()); else snprintf(str, sizeof(str), "\x1b[4%d;3%dm%s\x1b[48;5;238m\x1b[37m%s\x1b[49;39m" , c, tc, caption.substr(0, progress_chars).c_str(), caption.substr(progress_chars).c_str()); bar = str; } return bar; } void set_cursor_pos(int x, int y) { #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {x, y}; SetConsoleCursorPosition(out, c); #else printf("\033[%d;%dH", y + 1, x + 1); #endif } void clear_screen() { #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, 0}; CONSOLE_SCREEN_BUFFER_INFO si; GetConsoleScreenBufferInfo(out, &si); DWORD n; FillConsoleOutputCharacter(out, ' ', si.dwSize.X * si.dwSize.Y, c, &n); FillConsoleOutputAttribute(out, 0x7, si.dwSize.X * si.dwSize.Y, c, &n); #else printf("\033[2J"); #endif } void clear_rows(int y1, int y2) { if (y1 > y2) return; #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, y1}; SetConsoleCursorPosition(out, c); CONSOLE_SCREEN_BUFFER_INFO si; GetConsoleScreenBufferInfo(out, &si); DWORD n; int num_chars = si.dwSize.X * (std::min)(si.dwSize.Y - y1, y2 - y1); FillConsoleOutputCharacter(out, ' ', num_chars, c, &n); FillConsoleOutputAttribute(out, 0x7, num_chars, c, &n); #else for (int i = y1; i < y2; ++i) printf("\033[%d;1H\033[2K", i + 1); #endif } void terminal_size(int* terminal_width, int* terminal_height) { #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO coninfo; if (GetConsoleScreenBufferInfo(out, &coninfo)) { *terminal_width = coninfo.dwSize.X; *terminal_height = coninfo.srWindow.Bottom - coninfo.srWindow.Top; #else int tty = open("/dev/tty", O_RDONLY); winsize size; int ret = ioctl(tty, TIOCGWINSZ, (char*)&size); close(tty); if (ret == 0) { *terminal_width = size.ws_col; *terminal_height = size.ws_row; #endif if (*terminal_width < 64) *terminal_width = 64; if (*terminal_height < 25) *terminal_height = 25; } else { *terminal_width = 190; *terminal_height = 100; } } #ifdef _WIN32 void apply_ansi_code(int* attributes, bool* reverse, int code) { const static int color_table[8] = { 0, // black FOREGROUND_RED, // red FOREGROUND_GREEN, // green FOREGROUND_RED | FOREGROUND_GREEN, // yellow FOREGROUND_BLUE, // blue FOREGROUND_RED | FOREGROUND_BLUE, // magenta FOREGROUND_BLUE | FOREGROUND_GREEN, // cyan FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE // white }; enum { foreground_mask = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, background_mask = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE }; const static int fg_mask[2] = {foreground_mask, background_mask}; const static int bg_mask[2] = {background_mask, foreground_mask}; const static int fg_shift[2] = { 0, 4}; const static int bg_shift[2] = { 4, 0}; if (code == 0) { // reset *attributes = color_table[7]; *reverse = false; } else if (code == 7) { if (*reverse) return; *reverse = true; int fg_col = *attributes & foreground_mask; int bg_col = (*attributes & background_mask) >> 4; *attributes &= ~(foreground_mask + background_mask); *attributes |= fg_col << 4; *attributes |= bg_col; } else if (code >= 30 && code <= 37) { // foreground color *attributes &= ~fg_mask[*reverse]; *attributes |= color_table[code - 30] << fg_shift[*reverse]; } else if (code >= 40 && code <= 47) { // foreground color *attributes &= ~bg_mask[*reverse]; *attributes |= color_table[code - 40] << bg_shift[*reverse]; } } #endif void print(char const* str) { #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); char buffer[4096]; char* buf = buffer; strcpy(buf, str); int current_attributes = 7; bool reverse = false; SetConsoleTextAttribute(out, current_attributes); char* start = buf; DWORD written; while (*buf != 0) { if (*buf == '\033' && buf[1] == '[') { *buf = 0; WriteFile(out, start, buf - start, &written, NULL); buf += 2; // skip escape and '[' start = buf; one_more: while (*buf != 'm' && *buf != ';' && *buf != 0) ++buf; if (*buf == 0) break; int code = atoi(start); apply_ansi_code(&current_attributes, &reverse, code); if (*buf == ';') { ++buf; start = buf; goto one_more; } SetConsoleTextAttribute(out, current_attributes); ++buf; // skip 'm' start = buf; } else { ++buf; } } WriteFile(out, start, buf - start, &written, NULL); #else puts(str); #endif } improve printing of rates and counters in client_test git-svn-id: c39a6fcb73c71bf990fd9353909696546eb40440@10651 a83610d8-ad2a-0410-a6ab-fc0612d85776 #ifdef _WIN32 #include <windows.h> #include <conio.h> #else #include <unistd.h> // for close() #include <fcntl.h> // for open() #include <sys/ioctl.h> #endif #include "libtorrent/config.hpp" #include "print.hpp" #include <stdlib.h> // for atoi #include <string.h> // for strlen #include <cmath> #include <algorithm> // for std::min #include <iterator> // for back_inserter char const* esc(char const* code) { // this is a silly optimization // to avoid copying of strings enum { num_strings = 200 }; static char buf[num_strings][20]; static int round_robin = 0; char* ret = buf[round_robin]; ++round_robin; if (round_robin >= num_strings) round_robin = 0; ret[0] = '\033'; ret[1] = '['; int i = 2; int j = 0; while (code[j]) ret[i++] = code[j++]; ret[i++] = 'm'; ret[i++] = 0; return ret; } std::string to_string(int v, int width) { char buf[100]; snprintf(buf, sizeof(buf), "%*d", width, v); return buf; } std::string add_suffix(float val, char const* suffix) { if (val == 0) { std::string ret; ret.resize(4 + 2, ' '); if (suffix) ret.resize(4 + 2 + strlen(suffix), ' '); return ret; } const char* prefix[] = {"kB", "MB", "GB", "TB", "PB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i = 0; for (; i < num_prefix - 1; ++i) { val /= 1000.f; if (std::fabs(val) < 1000.f) break; } char ret[100]; snprintf(ret, sizeof(ret), "%4.*f%s%s", val < 99 ? 1 : 0, val, prefix[i], suffix ? suffix : ""); return ret; } std::string color(std::string const& s, color_code c) { if (c == col_none) return s; char buf[1024]; snprintf(buf, sizeof(buf), "\x1b[3%dm%s\x1b[39m", c, s.c_str()); return buf; } std::string const& progress_bar(int progress, int width, color_code c , char fill, char bg, std::string caption, int flags) { static std::string bar; bar.clear(); bar.reserve(width + 10); int progress_chars = (progress * width + 500) / 1000; if (caption.empty()) { char code[10]; snprintf(code, sizeof(code), "\x1b[3%dm", c); bar = code; std::fill_n(std::back_inserter(bar), progress_chars, fill); std::fill_n(std::back_inserter(bar), width - progress_chars, bg); bar += esc("39"); } else { // foreground color (depends a bit on background color) color_code tc = col_black; if (c == col_black || c == col_blue) tc = col_white; caption.resize(width, ' '); char str[256]; if (flags & progress_invert) snprintf(str, sizeof(str), "\x1b[48;5;238m\x1b[37m%s\x1b[4%d;3%dm%s\x1b[49;39m" , caption.substr(0, progress_chars).c_str(), c, tc , caption.substr(progress_chars).c_str()); else snprintf(str, sizeof(str), "\x1b[4%d;3%dm%s\x1b[48;5;238m\x1b[37m%s\x1b[49;39m" , c, tc, caption.substr(0, progress_chars).c_str(), caption.substr(progress_chars).c_str()); bar = str; } return bar; } void set_cursor_pos(int x, int y) { #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {x, y}; SetConsoleCursorPosition(out, c); #else printf("\033[%d;%dH", y + 1, x + 1); #endif } void clear_screen() { #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, 0}; CONSOLE_SCREEN_BUFFER_INFO si; GetConsoleScreenBufferInfo(out, &si); DWORD n; FillConsoleOutputCharacter(out, ' ', si.dwSize.X * si.dwSize.Y, c, &n); FillConsoleOutputAttribute(out, 0x7, si.dwSize.X * si.dwSize.Y, c, &n); #else printf("\033[2J"); #endif } void clear_rows(int y1, int y2) { if (y1 > y2) return; #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, y1}; SetConsoleCursorPosition(out, c); CONSOLE_SCREEN_BUFFER_INFO si; GetConsoleScreenBufferInfo(out, &si); DWORD n; int num_chars = si.dwSize.X * (std::min)(si.dwSize.Y - y1, y2 - y1); FillConsoleOutputCharacter(out, ' ', num_chars, c, &n); FillConsoleOutputAttribute(out, 0x7, num_chars, c, &n); #else for (int i = y1; i < y2; ++i) printf("\033[%d;1H\033[2K", i + 1); #endif } void terminal_size(int* terminal_width, int* terminal_height) { #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO coninfo; if (GetConsoleScreenBufferInfo(out, &coninfo)) { *terminal_width = coninfo.dwSize.X; *terminal_height = coninfo.srWindow.Bottom - coninfo.srWindow.Top; #else int tty = open("/dev/tty", O_RDONLY); winsize size; int ret = ioctl(tty, TIOCGWINSZ, (char*)&size); close(tty); if (ret == 0) { *terminal_width = size.ws_col; *terminal_height = size.ws_row; #endif if (*terminal_width < 64) *terminal_width = 64; if (*terminal_height < 25) *terminal_height = 25; } else { *terminal_width = 190; *terminal_height = 100; } } #ifdef _WIN32 void apply_ansi_code(int* attributes, bool* reverse, int code) { const static int color_table[8] = { 0, // black FOREGROUND_RED, // red FOREGROUND_GREEN, // green FOREGROUND_RED | FOREGROUND_GREEN, // yellow FOREGROUND_BLUE, // blue FOREGROUND_RED | FOREGROUND_BLUE, // magenta FOREGROUND_BLUE | FOREGROUND_GREEN, // cyan FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE // white }; enum { foreground_mask = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, background_mask = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE }; const static int fg_mask[2] = {foreground_mask, background_mask}; const static int bg_mask[2] = {background_mask, foreground_mask}; const static int fg_shift[2] = { 0, 4}; const static int bg_shift[2] = { 4, 0}; if (code == 0) { // reset *attributes = color_table[7]; *reverse = false; } else if (code == 7) { if (*reverse) return; *reverse = true; int fg_col = *attributes & foreground_mask; int bg_col = (*attributes & background_mask) >> 4; *attributes &= ~(foreground_mask + background_mask); *attributes |= fg_col << 4; *attributes |= bg_col; } else if (code >= 30 && code <= 37) { // foreground color *attributes &= ~fg_mask[*reverse]; *attributes |= color_table[code - 30] << fg_shift[*reverse]; } else if (code >= 40 && code <= 47) { // foreground color *attributes &= ~bg_mask[*reverse]; *attributes |= color_table[code - 40] << bg_shift[*reverse]; } } #endif void print(char const* str) { #ifdef _WIN32 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); char buffer[4096]; char* buf = buffer; strcpy(buf, str); int current_attributes = 7; bool reverse = false; SetConsoleTextAttribute(out, current_attributes); char* start = buf; DWORD written; while (*buf != 0) { if (*buf == '\033' && buf[1] == '[') { *buf = 0; WriteFile(out, start, buf - start, &written, NULL); buf += 2; // skip escape and '[' start = buf; one_more: while (*buf != 'm' && *buf != ';' && *buf != 0) ++buf; if (*buf == 0) break; int code = atoi(start); apply_ansi_code(&current_attributes, &reverse, code); if (*buf == ';') { ++buf; start = buf; goto one_more; } SetConsoleTextAttribute(out, current_attributes); ++buf; // skip 'm' start = buf; } else { ++buf; } } WriteFile(out, start, buf - start, &written, NULL); #else puts(str); #endif }
#include <sstream> #include "FemusDefault.hpp" #include "FemusInit.hpp" #include "MultiLevelMesh.hpp" #include "WriterEnum.hpp" using namespace femus; // Test for SalomeIO reading int main(int argc,char **args) { FemusInit init(argc,args,MPI_COMM_WORLD); std::string med_file = "GroupsANDMeshes.med"; std::ostringstream mystream; mystream << "./" << DEFAULT_INPUTDIR << "/" << med_file; const std::string infile = mystream.str(); //Adimensional double Lref = 1.; MultiLevelMesh ml_msh; ml_msh.ReadCoarseMesh(infile.c_str(),"fifth",Lref); ml_msh.SetWriter(XDMF); ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic"); ml_msh.SetWriter(VTK); ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic"); ml_msh.SetWriter(GMV); ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic"); return 0; } Found problem in testSalome #include <sstream> #include "FemusDefault.hpp" #include "FemusInit.hpp" #include "MultiLevelMesh.hpp" #include "WriterEnum.hpp" using namespace femus; // Test for SalomeIO reading int main(int argc,char **args) { FemusInit init(argc,args,MPI_COMM_WORLD); std::string med_file = "GroupsANDMeshes.med"; std::ostringstream mystream; mystream << "./" << DEFAULT_INPUTDIR << "/" << med_file; const std::string infile = mystream.str(); //Adimensional double Lref = 1.; MultiLevelMesh ml_msh; ml_msh.ReadCoarseMesh(infile.c_str(),"fifth",Lref); ml_msh.SetWriter(XDMF); ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic"); ml_msh.SetWriter(GMV); ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic"); ml_msh.SetWriter(VTK); ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic"); return 0; }
/* * nvbio * Copyright (c) 2011-2014, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <nvbio/io/output_stream.h> #include <nvbio/basic/console.h> #include <zlib/zlib.h> #include <lz4/lz4frame.h> #include <stdlib.h> #include <stdio.h> #include <string.h> namespace nvbio { GZOutputFile::GZOutputFile(const char* name, const char* comp) { char options_string[16]; sprintf( options_string, "w%s", comp); m_file = gzopen( name, options_string ); } GZOutputFile::~GZOutputFile() { if (m_file) gzclose( m_file ); } uint32 GZOutputFile::write(const uint32 bytes, const void* buffer) { if (bytes == 0) return 0; const int r = gzwrite( m_file, buffer, bytes ); if (r <= 0) { gzclose( m_file ); m_file = NULL; return 0; } return uint32(r); } LZ4OutputFile::LZ4OutputFile(const char* name, const char* comp) { fprintf(stderr, "LZ4OutputFile\n" ); m_file = (FILE*)fopen( name, "wb" ); if (m_file == NULL) return; m_buffer.resize( 1024*1024 ); // create a compression context LZ4F_createCompressionContext( &m_context, LZ4F_VERSION ); LZ4F_preferences_t* preferences = (LZ4F_preferences_t*)calloc( sizeof(LZ4F_preferences_t), 1u ); // TODO: handle compression modes const size_t compressed_bytes = LZ4F_compressBegin( m_context, &m_buffer[0], m_buffer.size(), preferences ); if (compressed_bytes == 0) return; // write down if (fwrite( &m_buffer[0], 1u, compressed_bytes, (FILE*)m_file ) < compressed_bytes) { // an error has occurred, shutdown the file fclose( (FILE*)m_file ); m_file = NULL; LZ4F_freeCompressionContext( m_context ); m_context = NULL; } } LZ4OutputFile::~LZ4OutputFile() { // flush any remaining data if (m_context && m_file) { const size_t compressed_bytes = LZ4F_compressEnd( m_context, &m_buffer[0], m_buffer.size(), NULL ); fwrite( &m_buffer[0], 1u, compressed_bytes, (FILE*)m_file ); } if (m_file) fclose( (FILE*)m_file ); if (m_context) LZ4F_freeCompressionContext( m_context ); } uint32 LZ4OutputFile::write(const uint32 bytes, const void* buffer) { if (bytes == 0) return 0; const size_t dst_max = LZ4F_compressBound( bytes, NULL ); if (m_buffer.size() <= dst_max) m_buffer.resize( dst_max ); // compress in-memory const size_t compressed_bytes = LZ4F_compressUpdate( m_context, &m_buffer[0], m_buffer.size(), buffer, bytes, NULL ); // check whether the compressor has actually produced any output if (compressed_bytes == 0) return bytes; // write down if (fwrite( &m_buffer[0], 1u, compressed_bytes, (FILE*)m_file ) < compressed_bytes) { // an error has occurred, shutdown the file fclose( (FILE*)m_file ); m_file = NULL; LZ4F_freeCompressionContext( m_context ); m_context = NULL; } return bytes; } // output file factory method // OutputStream* open_output_file(const char* file_name, const char* compressor, const char* options) { if (compressor == NULL || strcmp( compressor, "" ) == 0) return new GZOutputFile( file_name, "T" ); else if (strcmp( compressor, "gzip" ) == 0 || strcmp( compressor, "gz" ) == 0) return new GZOutputFile( file_name, options ); else if (strcmp( compressor, "lz4" ) == 0) return new LZ4OutputFile( file_name, options ); log_warning(stderr, "unknown output file compressor \"%s\"\n", compressor ); return NULL; } } // namespace nvbio removed debug printfs /* * nvbio * Copyright (c) 2011-2014, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <nvbio/io/output_stream.h> #include <nvbio/basic/console.h> #include <zlib/zlib.h> #include <lz4/lz4frame.h> #include <stdlib.h> #include <stdio.h> #include <string.h> namespace nvbio { GZOutputFile::GZOutputFile(const char* name, const char* comp) { char options_string[16]; sprintf( options_string, "w%s", comp); m_file = gzopen( name, options_string ); } GZOutputFile::~GZOutputFile() { if (m_file) gzclose( m_file ); } uint32 GZOutputFile::write(const uint32 bytes, const void* buffer) { if (bytes == 0) return 0; const int r = gzwrite( m_file, buffer, bytes ); if (r <= 0) { gzclose( m_file ); m_file = NULL; return 0; } return uint32(r); } LZ4OutputFile::LZ4OutputFile(const char* name, const char* comp) { m_file = (FILE*)fopen( name, "wb" ); if (m_file == NULL) return; m_buffer.resize( 1024*1024 ); // create a compression context LZ4F_createCompressionContext( &m_context, LZ4F_VERSION ); LZ4F_preferences_t* preferences = (LZ4F_preferences_t*)calloc( sizeof(LZ4F_preferences_t), 1u ); // TODO: handle compression modes const size_t compressed_bytes = LZ4F_compressBegin( m_context, &m_buffer[0], m_buffer.size(), preferences ); if (compressed_bytes == 0) return; // write down if (fwrite( &m_buffer[0], 1u, compressed_bytes, (FILE*)m_file ) < compressed_bytes) { // an error has occurred, shutdown the file fclose( (FILE*)m_file ); m_file = NULL; LZ4F_freeCompressionContext( m_context ); m_context = NULL; } } LZ4OutputFile::~LZ4OutputFile() { // flush any remaining data if (m_context && m_file) { const size_t compressed_bytes = LZ4F_compressEnd( m_context, &m_buffer[0], m_buffer.size(), NULL ); fwrite( &m_buffer[0], 1u, compressed_bytes, (FILE*)m_file ); } if (m_file) fclose( (FILE*)m_file ); if (m_context) LZ4F_freeCompressionContext( m_context ); } uint32 LZ4OutputFile::write(const uint32 bytes, const void* buffer) { if (bytes == 0) return 0; const size_t dst_max = LZ4F_compressBound( bytes, NULL ); if (m_buffer.size() <= dst_max) m_buffer.resize( dst_max ); // compress in-memory const size_t compressed_bytes = LZ4F_compressUpdate( m_context, &m_buffer[0], m_buffer.size(), buffer, bytes, NULL ); // check whether the compressor has actually produced any output if (compressed_bytes == 0) return bytes; // write down if (fwrite( &m_buffer[0], 1u, compressed_bytes, (FILE*)m_file ) < compressed_bytes) { // an error has occurred, shutdown the file fclose( (FILE*)m_file ); m_file = NULL; LZ4F_freeCompressionContext( m_context ); m_context = NULL; } return bytes; } // output file factory method // OutputStream* open_output_file(const char* file_name, const char* compressor, const char* options) { if (compressor == NULL || strcmp( compressor, "" ) == 0) return new GZOutputFile( file_name, "T" ); else if (strcmp( compressor, "gzip" ) == 0 || strcmp( compressor, "gz" ) == 0) return new GZOutputFile( file_name, options ); else if (strcmp( compressor, "lz4" ) == 0) return new LZ4OutputFile( file_name, options ); log_warning(stderr, "unknown output file compressor \"%s\"\n", compressor ); return NULL; } } // namespace nvbio
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "AliasedRegisters.h" #include <algorithm> #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #endif #include <boost/graph/adjacency_list.hpp> #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #include <boost/optional.hpp> #include <boost/range/iterator_range.hpp> #include <limits> #include <numeric> #include <unordered_set> using namespace sparta; // AliasedRegisters is a data structure that CopyPropagation uses to keep track // of which Values (registers, constants, final fields, etc.) are the same // (aliased). // // For example, // move v1, v0 // move v2, v0 // move v1, v2 ; delete this instruction because v1 and v2 are already aliased // // AliasedRegisters uses a graph to keep track of these alias relationships, // where nodes are Values. The graph is a forest of trees, where each tree is an // "alias group", meaning that all Values in the group (tree) are aliased to // each other. Creating groups like this implements the transitive nature of the // aliasing relationship. // // This is similar in concept to union/find. But it also needs to support // deleting an element and intersecting two data structures, which is why we // have a custom implementation. // // The implementation is similar to a link/cut tree, but these trees only have // two levels (every node is either a root or a leaf). The reason for the two // level design is because we are not actually supporting the "cut" part of the // link/cut tree. After two groups A and B get unioned, if one of the elements // of B gets overwritten, we only want to remove that single element from the // group instead of splitting off all the elements that were formerly in B. So // it's more of a link/delete tree. // // A single group could be represented as multiple different trees (by choosing // different roots), but this is undesirable. To enforce canonical trees, we use // `Value::operator<` to ensure that the minimum node is always the root node. // This incurs the cost of changing the root node more frequently, but it's // worth it over all, especially when computing the intersection of two graphs. // // The aliasing relation is an equivalence relation. An alias group is an // equivalence class of this relation. // Reflexive : A node is trivially equivalent to itself // Symmetric : If two nodes have the same root, they must be in the same tree // Transitive: `AliasedRegisters::move` adds an edge from the new node the // root of the tree namespace aliased_registers { using vertex_t = AliasedRegisters::vertex_t; // Move `moving` into the alias group of `group` void AliasedRegisters::move(const Value& moving, const Value& group) { always_assert_log(!moving.is_none() && !group.is_none(), "Neither should be NONE. %s, %s", moving.str().c_str(), group.str().c_str()); // Only need to do something if they're not already in same group if (!are_aliases(moving, group)) { // remove from the old group break_alias(moving); vertex_t v_moving = find_or_create(moving); vertex_t v_group = find_or_create(group); const auto& grp = vertices_in_group(v_group); track_insert_order(moving, v_moving, group, v_group, grp); // Add an edge from `moving` to the root of its new group // This maintains a maximum of 2 levels in the tree. // Therefore, root nodes are the only nodes with incoming edges. vertex_t v_group_root = find_root(v_group); boost::add_edge(v_moving, v_group_root, m_graph); // We want to have a single canonical representation of a tree. Make sure // the root is always the node that sorts lowest of the Values in this tree const Value& group_root = m_graph[v_group_root]; if (moving < group_root) { change_root_to(v_group_root, v_moving); } } } // Set the insertion number of `v_moving` to 1 + the max of `group`. // `v_moving` is the newest member of `group` so it should have the highest // insertion number. // // If this call creates a new group (of size two), also set the insertion // number of `v_group` void AliasedRegisters::track_insert_order(const Value& moving, vertex_t v_moving, const Value& group, vertex_t v_group, const std::vector<vertex_t>& grp) { always_assert(!grp.empty()); if (grp.size() == 1 && group.is_register()) { // We're creating a new group from a singleton. The `group` // register is the oldest, followed by `moving`. m_insert_order.emplace(v_group, 0); } if (moving.is_register()) { size_t moving_index = 1 + std::accumulate( grp.begin(), grp.end(), 0, [this](size_t acc, vertex_t v) { // use operator[] to ignore non-register group members return std::max(acc, m_insert_order[v]); }); m_insert_order.emplace(v_moving, moving_index); } } // Remove `r` from its alias group void AliasedRegisters::break_alias(const Value& r) { const auto& v = find(r); if (v) { // if `v` was the root of a tree, we need to promote a leaf maybe_change_root(*v); // clear removes all edges to and from `r` boost::clear_vertex(*v, m_graph); if (r.is_register()) { // `v` is not in a group any more so it has no insert order clear_insert_number(*v); } } } // Call this when `v` should no longer have an insertion number (because it does // not belong to a group). void AliasedRegisters::clear_insert_number(vertex_t v) { m_insert_order.erase(v); } // Two Values are aliased when they are in the same tree bool AliasedRegisters::are_aliases(const Value& r1, const Value& r2) const { if (r1 == r2) { return true; } const auto& v1 = find(r1); return v1 != boost::none && find_in_tree(r2, *v1) != boost::none; } // Two vertices are aliased when they have the same root bool AliasedRegisters::vertices_are_aliases(vertex_t v1, vertex_t v2) const { return v1 == v2 || find_root(v1) == find_root(v2); } // Return the vertex of the root node of the tree that `v` belongs to // If `v` is not part of a group, then it is a singleton and it is its own root // node. vertex_t AliasedRegisters::find_root(vertex_t v) const { // The trees only have two levels. No need to loop const auto& adj = boost::adjacent_vertices(v, m_graph); const auto& begin = adj.first; const auto& end = adj.second; if (begin == end) { // `v` is its own root return v; } always_assert_log(std::next(begin) == end, "a tree can't have more than one root"); return *begin; } // If `old_root` is a root node, promote a different node from this tree to the // root. void AliasedRegisters::change_root_helper( vertex_t old_root, boost::optional<vertex_t> maybe_new_root) { const auto& in_adj = boost::inv_adjacent_vertices(old_root, m_graph); const auto& in_begin = in_adj.first; const auto& in_end = in_adj.second; if (in_begin != in_end) { always_assert_log( !has_outgoing(old_root), "Only 2 levels allowed\n%s", dump().c_str()); vertex_t new_root = (maybe_new_root == boost::none) ? find_new_root(old_root) : *maybe_new_root; if (new_root != old_root) { always_assert_log( !has_incoming(new_root), "Only 2 levels allowed\n%s", dump().c_str()); std::vector<vertex_t> leaves; leaves.reserve((in_end - in_begin) - 1); for (auto it = in_begin; it != in_end; ++it) { if (*it != new_root) { leaves.push_back(*it); } } // For all nodes in the tree that aren't the new or old root, // redirect their outgoing edges to the new root for (vertex_t leaf : leaves) { boost::remove_edge(leaf, old_root, m_graph); boost::add_edge(leaf, new_root, m_graph); } // reverse the edge between the old root and the new root boost::remove_edge(new_root, old_root, m_graph); boost::add_edge(old_root, new_root, m_graph); } } } // If `old_root` is a root, promote one of its leaves to the root. // Otherwise, do nothing. void AliasedRegisters::maybe_change_root(vertex_t old_root) { change_root_helper(old_root, boost::none); } // Promote `new_root` to a root and demote `old_root` to a leaf void AliasedRegisters::change_root_to(vertex_t old_root, vertex_t new_root) { always_assert(old_root != new_root); always_assert(has_incoming(old_root)); change_root_helper(old_root, new_root); } // We want to have a single canonical representation of a tree. the new root is // the node that sorts lowest of the leaves in this tree vertex_t AliasedRegisters::find_new_root(vertex_t old_root) const { const auto& in_adj = boost::inv_adjacent_vertices(old_root, m_graph); const auto& in_begin = in_adj.first; const auto& in_end = in_adj.second; always_assert_log(in_begin != in_end, "%s", dump().c_str()); // We can't use std::min_element because the compiler on macosx doesn't think // that boost::inv_adjacency_iterator is a ForwardIterator, even though it // should be. auto it = in_begin; vertex_t lowest = *it; Value lowest_val = m_graph[lowest]; ++it; for (; it != in_end; ++it) { vertex_t v = *it; const Value& val = m_graph[v]; if (val < lowest_val) { lowest = v; lowest_val = val; } } return lowest; } // Return a representative for this register. // // Return the oldest register that is <= `max_addressable` // We want the oldest register because it helps create more dead stores. // Consider this example: // // move v1, v2 // move v0, v1 // ; v1 is never used again // // if we choose v2 as our representative (not v1) then we can remove an insn: // // move v0, v2 // // `max_addressable` is useful for instructions that can only address up to v15 reg_t AliasedRegisters::get_representative( const Value& orig, const boost::optional<reg_t>& max_addressable) const { always_assert(orig.is_register()); // if orig is not in the graph, then it has no representative const auto& v = find(orig); if (!v) { return orig.reg(); } // intentionally copy the vector so we can safely remove from it std::vector<vertex_t> group = vertices_in_group(*v); // filter out non registers and other ineligible registers group.erase(std::remove_if(group.begin(), group.end(), [this, &max_addressable](vertex_t elem) { // return true to remove it const Value& val = m_graph[elem]; if (!val.is_register()) { return true; } return max_addressable && val.reg() > *max_addressable; }), group.end()); if (group.empty()) { return orig.reg(); } // We want the oldest element. It has the lowest insertion number const Value& representative = m_graph[*std::min_element( group.begin(), group.end(), [this](vertex_t a, vertex_t b) { return m_insert_order.at(a) < m_insert_order.at(b); })]; return representative.reg(); } // if `r` is in the graph, return the vertex holding it. // if not, return boost::none. // WARNING: this operation is expensive on large graphs. It's an O(n) search of // all the nodes. boost::optional<vertex_t> AliasedRegisters::find(const Value& r) const { const auto& iters = boost::vertices(m_graph); const auto& begin = iters.first; const auto& end = iters.second; for (auto it = begin; it != end; ++it) { if (m_graph[*it] == r) { return *it; } } return boost::none; } // If any nodes in the same tree as `in_this_tree` have the Value `r`, then // return `r`'s vertex. // This is a faster alternative to a `find()` over the entire graph boost::optional<vertex_t> AliasedRegisters::find_in_tree( const Value& r, vertex_t in_this_tree) const { vertex_t root = find_root(in_this_tree); if (m_graph[root] == r) { return root; } const auto& adj = boost::inv_adjacent_vertices(root, m_graph); const auto& begin = adj.first; const auto& end = adj.second; for (auto it = begin; it != end; ++it) { if (m_graph[*it] == r) { return *it; } } return boost::none; } // returns the vertex holding `r` or creates a new (unconnected) // vertex if `r` is not in m_graph vertex_t AliasedRegisters::find_or_create(const Value& r) { const auto& it = find(r); if (it) { return *it; } else { vertex_t v = boost::add_vertex(r, m_graph); return v; } } // return a vector of `v` and all the vertices in the same tree // (with the root first) std::vector<vertex_t> AliasedRegisters::vertices_in_group( vertex_t input) const { vertex_t root = find_root(input); const auto& in_adj = boost::inv_adjacent_vertices(root, m_graph); const auto& in_begin = in_adj.first; const auto& in_end = in_adj.second; std::vector<vertex_t> result; result.reserve(1 + (in_end - in_begin)); result.push_back(root); for (auto it = in_begin; it != in_end; ++it) { result.push_back(*it); } return result; } // return true if `v` has no neighbors bool AliasedRegisters::is_singleton(vertex_t v) { return !has_outgoing(v) && !has_incoming(v); } // return true if `v` has any incoming edges (equivalent to v being a root of a // non-singleton tree) bool AliasedRegisters::has_incoming(vertex_t v) { const auto& in_adj = boost::inv_adjacent_vertices(v, m_graph); const auto& in_begin = in_adj.first; const auto& in_end = in_adj.second; return in_begin != in_end; } // return true if `v` has any outgoing edges (equivalent to v being a leaf) bool AliasedRegisters::has_outgoing(vertex_t v) { const auto& out_adj = boost::adjacent_vertices(v, m_graph); const auto& out_begin = out_adj.first; const auto& out_end = out_adj.second; return out_begin != out_end; } // ---- extends AbstractValue ---- void AliasedRegisters::clear() { m_graph.clear(); m_insert_order.clear(); } AbstractValueKind AliasedRegisters::kind() const { return (boost::num_edges(m_graph) > 0) ? AbstractValueKind::Value : AbstractValueKind::Top; } // leq (<=) is the superset relation on the alias groups bool AliasedRegisters::leq(const AliasedRegisters& other) const { if (boost::num_edges(m_graph) < boost::num_edges(other.m_graph)) { // this cannot be a superset of other if this has fewer edges return false; } // for all edges in `other` (the potential subset), make sure `this` has that // alias relationship const auto& iters = boost::edges(other.m_graph); const auto& begin = iters.first; const auto& end = iters.second; for (auto it = begin; it != end; ++it) { const Value& r1 = other.m_graph[boost::source(*it, other.m_graph)]; const Value& r2 = other.m_graph[boost::target(*it, other.m_graph)]; if (!are_aliases(r1, r2)) { return false; } } return true; } // returns true iff they have exactly the same edges between the same Values bool AliasedRegisters::equals(const AliasedRegisters& other) const { return boost::num_edges(m_graph) == boost::num_edges(other.m_graph) && leq(other); } AbstractValueKind AliasedRegisters::narrow_with(const AliasedRegisters& other) { return meet_with(other); } AbstractValueKind AliasedRegisters::widen_with(const AliasedRegisters& other) { return join_with(other); } // alias group union AbstractValueKind AliasedRegisters::meet_with(const AliasedRegisters& other) { always_assert_log(false, "UNUSED"); } // Alias group intersection. // Only keep the alias relationships that both `this` and `other` contain. AbstractValueKind AliasedRegisters::join_with(const AliasedRegisters& other) { auto this_before_groups = this->all_groups(); // Remove all edges from this graph. We will add back the ones that `other` // also has using edge_t = boost::graph_traits<Graph>::edge_descriptor; boost::remove_edge_if([](const edge_t&) { return true; }, m_graph); // Break up each group into some number of new groups. // Intersection can't create any groups larger than what `this` had, only the // same size or smaller. for (auto& group : this_before_groups) { // Sort so that we only have to scan the nodes after the potential root // (remember that the root node must sort lowest of its tree) std::sort(group.begin(), group.end(), [this](vertex_t v1, vertex_t v2) { return m_graph[v1] < m_graph[v2]; }); // Starting with the lowest node, grab all the singletons that `other` // agrees are aliased with this potential root. // Repeat with the next potential root. size_t sz = group.size(); for (size_t i = 0; i < sz; ++i) { vertex_t new_root = group[i]; if (has_outgoing(new_root)) { // This can't be a new root because it's already a leaf continue; } // We can start iterating from i + 1 because everything beneath `i` has // already been considered as a potential root and had all possible nodes // added to its tree. for (size_t j = i + 1; j < sz; ++j) { // If `v` hasn't already been added to another tree and `other` agrees, // then add the edge. vertex_t v = group[j]; if (!has_outgoing(v) && other.are_aliases(this->m_graph[v], this->m_graph[new_root])) { boost::add_edge(v, new_root, m_graph); } } } } handle_edge_intersection_insert_order(other); return AbstractValueKind::Value; } void AliasedRegisters::handle_edge_intersection_insert_order( const AliasedRegisters& other) { // Clear out stale values in `m_insert_order` for vertices removed from // groups. const auto& iters = boost::vertices(this->m_graph); const auto& begin = iters.first; const auto& end = iters.second; for (auto it = begin; it != end; ++it) { if (is_singleton(*it)) { clear_insert_number(*it); } } // Assign new insertion numbers while taking into account both insertion maps. for (auto& group : all_groups()) { handle_insert_order_at_merge(group, other); } } // Merge the ordering in `other.m_insert_order` into `this->m_insert_order`. // // When both graphs know about an edge (and they don't agree about insertion // order), use register number. // When only one graph knows about an edge, use insertion order from that graph. // When neither graph knows about the edge, use register number. void AliasedRegisters::handle_insert_order_at_merge( const std::vector<vertex_t>& group, const AliasedRegisters& other) { renumber_insert_order(group, [this, &other](vertex_t a, vertex_t b) { // return true if `a` occurs before `b`. // return false if they compare equal or if `b` occurs before `a`. if (a == b) return false; // `a` and `b` only index into this, not other. const Value& val_a = this->m_graph[a]; const Value& val_b = this->m_graph[b]; bool this_has = this->vertices_are_aliases(a, b); boost::optional<vertex_t> other_a = other.find(val_a); boost::optional<vertex_t> other_b = (other_a == boost::none ? boost::none : other.find_in_tree(val_b, *other_a)); bool other_has = other_b != boost::none; if (this_has && other_has) { // Intersection case should always come here bool this_less_than = this->m_insert_order.at(a) < this->m_insert_order.at(b); bool other_less_than = other.m_insert_order.at(*other_a) < other.m_insert_order.at(*other_b); if (this_less_than == other_less_than) { // The graphs agree on the order of these two vertices. // Preserve that order. return this_less_than; } else { // The graphs do not agree. Choose a deterministic order return val_a.reg() < val_b.reg(); } } else if (this_has) { return this->m_insert_order.at(a) < this->m_insert_order.at(b); } else if (other_has) { return other.m_insert_order.at(*other_a) < other.m_insert_order.at(*other_b); } else { // Neither graph has this relationship. Choose a deterministic order return val_a.reg() < val_b.reg(); } }); } // Rewrite the insertion number of all registers in `group` in an order defined // by `less_than` void AliasedRegisters::renumber_insert_order( std::vector<vertex_t> group, const std::function<bool(vertex_t, vertex_t)>& less_than) { // Filter out non registers. group.erase( std::remove_if(group.begin(), group.end(), [this](vertex_t v) { return !m_graph[v].is_register(); }), group.end()); if (group.size() < 2) { // No need to assign insert order for singletons return; } // Assign new insertion numbers based on sorting. std::sort(group.begin(), group.end(), less_than); size_t i = 0; for (vertex_t v : group) { this->m_insert_order[v] = i; ++i; } } // return all groups (not including singletons) std::vector<std::vector<vertex_t>> AliasedRegisters::all_groups() { std::vector<std::vector<vertex_t>> result; std::unordered_set<vertex_t> visited; const auto& iters = boost::vertices(this->m_graph); const auto& begin = iters.first; const auto& end = iters.second; for (auto it = begin; it != end; ++it) { vertex_t root = find_root(*it); const auto& pair = visited.insert(root); bool insertion_took_place = pair.second; if (insertion_took_place) { auto group = vertices_in_group(root); if (group.size() > 1) { result.emplace_back(std::move(group)); } } } return result; } // returns a string representation of this data structure. Intended for // debugging. std::string AliasedRegisters::dump() const { std::ostringstream oss; const auto& iters = boost::edges(this->m_graph); const auto& begin = iters.first; const auto& end = iters.second; oss << "Graph [" << std::endl; for (auto it = begin; it != end; ++it) { const Value& r1 = m_graph[boost::source(*it, m_graph)]; const Value& r2 = m_graph[boost::target(*it, m_graph)]; oss << "(" << r1.str().c_str() << " -> " << r2.str().c_str() << ") " << std::endl; } oss << "] insert order [" << std::endl; for (const auto& entry : m_insert_order) { vertex_t v = entry.first; const Value& r = m_graph[v]; size_t i = entry.second; oss << r.str().c_str() << " has index " << i << std::endl; } oss << "]" << std::endl; return oss.str(); } bool Value::operator==(const Value& other) const { if (m_kind != other.m_kind) { return false; } switch (m_kind) { case Kind::REGISTER: return m_reg == other.m_reg; case Kind::CONST_LITERAL: case Kind::CONST_LITERAL_UPPER: return m_literal == other.m_literal && m_type_demand == other.m_type_demand; case Kind::CONST_STRING: return m_str == other.m_str; case Kind::CONST_TYPE: return m_type == other.m_type; case Kind::STATIC_FINAL: case Kind::STATIC_FINAL_UPPER: return m_field == other.m_field; case Kind::NONE: return true; } } bool Value::operator<(const Value& other) const { if (m_kind != other.m_kind) { return m_kind < other.m_kind; } switch (m_kind) { case Kind::REGISTER: return m_reg < other.m_reg; case Kind::CONST_LITERAL: case Kind::CONST_LITERAL_UPPER: if (m_literal != other.m_literal) { return m_literal < other.m_literal; } else { return m_type_demand < other.m_type_demand; } case Kind::CONST_STRING: return compare_dexstrings(m_str, other.m_str); case Kind::CONST_TYPE: return compare_dextypes(m_type, other.m_type); case Kind::STATIC_FINAL: case Kind::STATIC_FINAL_UPPER: return compare_dexfields(m_field, other.m_field); case Kind::NONE: always_assert_log(false, "can't sort NONEs"); } } // returns a string representation of this Value. Intended for debugging. std::string Value::str() const { std::ostringstream oss; switch (m_kind) { case Kind::REGISTER: oss << "v" << m_reg; break; case Kind::CONST_LITERAL: oss << m_literal; break; case Kind::CONST_LITERAL_UPPER: oss << m_literal << " upper"; break; case Kind::CONST_STRING: oss << m_str->str(); break; case Kind::CONST_TYPE: oss << m_type->str(); break; case Kind::STATIC_FINAL: oss << m_field->str(); break; case Kind::STATIC_FINAL_UPPER: oss << m_field->str() << " upper"; break; case Kind::NONE: oss << "NONE"; break; } return oss.str(); } } // namespace aliased_registers use boost min_element instead Reviewed By: agampe Differential Revision: D21030510 fbshipit-source-id: 9cdd80d18d44386a2e6e3bd5b8eeb4048471f3fa /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "AliasedRegisters.h" #include <algorithm> #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #endif #include <boost/graph/adjacency_list.hpp> #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #include <boost/optional.hpp> #include <boost/range/algorithm.hpp> #include <boost/range/iterator_range.hpp> #include <limits> #include <numeric> #include <unordered_set> using namespace sparta; // AliasedRegisters is a data structure that CopyPropagation uses to keep track // of which Values (registers, constants, final fields, etc.) are the same // (aliased). // // For example, // move v1, v0 // move v2, v0 // move v1, v2 ; delete this instruction because v1 and v2 are already aliased // // AliasedRegisters uses a graph to keep track of these alias relationships, // where nodes are Values. The graph is a forest of trees, where each tree is an // "alias group", meaning that all Values in the group (tree) are aliased to // each other. Creating groups like this implements the transitive nature of the // aliasing relationship. // // This is similar in concept to union/find. But it also needs to support // deleting an element and intersecting two data structures, which is why we // have a custom implementation. // // The implementation is similar to a link/cut tree, but these trees only have // two levels (every node is either a root or a leaf). The reason for the two // level design is because we are not actually supporting the "cut" part of the // link/cut tree. After two groups A and B get unioned, if one of the elements // of B gets overwritten, we only want to remove that single element from the // group instead of splitting off all the elements that were formerly in B. So // it's more of a link/delete tree. // // A single group could be represented as multiple different trees (by choosing // different roots), but this is undesirable. To enforce canonical trees, we use // `Value::operator<` to ensure that the minimum node is always the root node. // This incurs the cost of changing the root node more frequently, but it's // worth it over all, especially when computing the intersection of two graphs. // // The aliasing relation is an equivalence relation. An alias group is an // equivalence class of this relation. // Reflexive : A node is trivially equivalent to itself // Symmetric : If two nodes have the same root, they must be in the same tree // Transitive: `AliasedRegisters::move` adds an edge from the new node the // root of the tree namespace aliased_registers { using vertex_t = AliasedRegisters::vertex_t; // Move `moving` into the alias group of `group` void AliasedRegisters::move(const Value& moving, const Value& group) { always_assert_log(!moving.is_none() && !group.is_none(), "Neither should be NONE. %s, %s", moving.str().c_str(), group.str().c_str()); // Only need to do something if they're not already in same group if (!are_aliases(moving, group)) { // remove from the old group break_alias(moving); vertex_t v_moving = find_or_create(moving); vertex_t v_group = find_or_create(group); const auto& grp = vertices_in_group(v_group); track_insert_order(moving, v_moving, group, v_group, grp); // Add an edge from `moving` to the root of its new group // This maintains a maximum of 2 levels in the tree. // Therefore, root nodes are the only nodes with incoming edges. vertex_t v_group_root = find_root(v_group); boost::add_edge(v_moving, v_group_root, m_graph); // We want to have a single canonical representation of a tree. Make sure // the root is always the node that sorts lowest of the Values in this tree const Value& group_root = m_graph[v_group_root]; if (moving < group_root) { change_root_to(v_group_root, v_moving); } } } // Set the insertion number of `v_moving` to 1 + the max of `group`. // `v_moving` is the newest member of `group` so it should have the highest // insertion number. // // If this call creates a new group (of size two), also set the insertion // number of `v_group` void AliasedRegisters::track_insert_order(const Value& moving, vertex_t v_moving, const Value& group, vertex_t v_group, const std::vector<vertex_t>& grp) { always_assert(!grp.empty()); if (grp.size() == 1 && group.is_register()) { // We're creating a new group from a singleton. The `group` // register is the oldest, followed by `moving`. m_insert_order.emplace(v_group, 0); } if (moving.is_register()) { size_t moving_index = 1 + std::accumulate( grp.begin(), grp.end(), 0, [this](size_t acc, vertex_t v) { // use operator[] to ignore non-register group members return std::max(acc, m_insert_order[v]); }); m_insert_order.emplace(v_moving, moving_index); } } // Remove `r` from its alias group void AliasedRegisters::break_alias(const Value& r) { const auto& v = find(r); if (v) { // if `v` was the root of a tree, we need to promote a leaf maybe_change_root(*v); // clear removes all edges to and from `r` boost::clear_vertex(*v, m_graph); if (r.is_register()) { // `v` is not in a group any more so it has no insert order clear_insert_number(*v); } } } // Call this when `v` should no longer have an insertion number (because it does // not belong to a group). void AliasedRegisters::clear_insert_number(vertex_t v) { m_insert_order.erase(v); } // Two Values are aliased when they are in the same tree bool AliasedRegisters::are_aliases(const Value& r1, const Value& r2) const { if (r1 == r2) { return true; } const auto& v1 = find(r1); return v1 != boost::none && find_in_tree(r2, *v1) != boost::none; } // Two vertices are aliased when they have the same root bool AliasedRegisters::vertices_are_aliases(vertex_t v1, vertex_t v2) const { return v1 == v2 || find_root(v1) == find_root(v2); } // Return the vertex of the root node of the tree that `v` belongs to // If `v` is not part of a group, then it is a singleton and it is its own root // node. vertex_t AliasedRegisters::find_root(vertex_t v) const { // The trees only have two levels. No need to loop const auto& adj = boost::adjacent_vertices(v, m_graph); const auto& begin = adj.first; const auto& end = adj.second; if (begin == end) { // `v` is its own root return v; } always_assert_log(std::next(begin) == end, "a tree can't have more than one root"); return *begin; } // If `old_root` is a root node, promote a different node from this tree to the // root. void AliasedRegisters::change_root_helper( vertex_t old_root, boost::optional<vertex_t> maybe_new_root) { const auto& in_adj = boost::inv_adjacent_vertices(old_root, m_graph); const auto& in_begin = in_adj.first; const auto& in_end = in_adj.second; if (in_begin != in_end) { always_assert_log( !has_outgoing(old_root), "Only 2 levels allowed\n%s", dump().c_str()); vertex_t new_root = (maybe_new_root == boost::none) ? find_new_root(old_root) : *maybe_new_root; if (new_root != old_root) { always_assert_log( !has_incoming(new_root), "Only 2 levels allowed\n%s", dump().c_str()); std::vector<vertex_t> leaves; leaves.reserve((in_end - in_begin) - 1); for (auto it = in_begin; it != in_end; ++it) { if (*it != new_root) { leaves.push_back(*it); } } // For all nodes in the tree that aren't the new or old root, // redirect their outgoing edges to the new root for (vertex_t leaf : leaves) { boost::remove_edge(leaf, old_root, m_graph); boost::add_edge(leaf, new_root, m_graph); } // reverse the edge between the old root and the new root boost::remove_edge(new_root, old_root, m_graph); boost::add_edge(old_root, new_root, m_graph); } } } // If `old_root` is a root, promote one of its leaves to the root. // Otherwise, do nothing. void AliasedRegisters::maybe_change_root(vertex_t old_root) { change_root_helper(old_root, boost::none); } // Promote `new_root` to a root and demote `old_root` to a leaf void AliasedRegisters::change_root_to(vertex_t old_root, vertex_t new_root) { always_assert(old_root != new_root); always_assert(has_incoming(old_root)); change_root_helper(old_root, new_root); } // We want to have a single canonical representation of a tree. the new root is // the node that sorts lowest of the leaves in this tree vertex_t AliasedRegisters::find_new_root(vertex_t old_root) const { const auto& in_adj = boost::inv_adjacent_vertices(old_root, m_graph); const auto& in_begin = in_adj.first; const auto& in_end = in_adj.second; always_assert_log(in_begin != in_end, "%s", dump().c_str()); return *boost::range::min_element(in_adj, [this](vertex_t v1, vertex_t v2) { return m_graph[v1] < m_graph[v2]; }); } // Return a representative for this register. // // Return the oldest register that is <= `max_addressable` // We want the oldest register because it helps create more dead stores. // Consider this example: // // move v1, v2 // move v0, v1 // ; v1 is never used again // // if we choose v2 as our representative (not v1) then we can remove an insn: // // move v0, v2 // // `max_addressable` is useful for instructions that can only address up to v15 reg_t AliasedRegisters::get_representative( const Value& orig, const boost::optional<reg_t>& max_addressable) const { always_assert(orig.is_register()); // if orig is not in the graph, then it has no representative const auto& v = find(orig); if (!v) { return orig.reg(); } // intentionally copy the vector so we can safely remove from it std::vector<vertex_t> group = vertices_in_group(*v); // filter out non registers and other ineligible registers group.erase(std::remove_if(group.begin(), group.end(), [this, &max_addressable](vertex_t elem) { // return true to remove it const Value& val = m_graph[elem]; if (!val.is_register()) { return true; } return max_addressable && val.reg() > *max_addressable; }), group.end()); if (group.empty()) { return orig.reg(); } // We want the oldest element. It has the lowest insertion number const Value& representative = m_graph[*std::min_element( group.begin(), group.end(), [this](vertex_t a, vertex_t b) { return m_insert_order.at(a) < m_insert_order.at(b); })]; return representative.reg(); } // if `r` is in the graph, return the vertex holding it. // if not, return boost::none. // WARNING: this operation is expensive on large graphs. It's an O(n) search of // all the nodes. boost::optional<vertex_t> AliasedRegisters::find(const Value& r) const { const auto& iters = boost::vertices(m_graph); const auto& begin = iters.first; const auto& end = iters.second; for (auto it = begin; it != end; ++it) { if (m_graph[*it] == r) { return *it; } } return boost::none; } // If any nodes in the same tree as `in_this_tree` have the Value `r`, then // return `r`'s vertex. // This is a faster alternative to a `find()` over the entire graph boost::optional<vertex_t> AliasedRegisters::find_in_tree( const Value& r, vertex_t in_this_tree) const { vertex_t root = find_root(in_this_tree); if (m_graph[root] == r) { return root; } const auto& adj = boost::inv_adjacent_vertices(root, m_graph); const auto& begin = adj.first; const auto& end = adj.second; for (auto it = begin; it != end; ++it) { if (m_graph[*it] == r) { return *it; } } return boost::none; } // returns the vertex holding `r` or creates a new (unconnected) // vertex if `r` is not in m_graph vertex_t AliasedRegisters::find_or_create(const Value& r) { const auto& it = find(r); if (it) { return *it; } else { vertex_t v = boost::add_vertex(r, m_graph); return v; } } // return a vector of `v` and all the vertices in the same tree // (with the root first) std::vector<vertex_t> AliasedRegisters::vertices_in_group( vertex_t input) const { vertex_t root = find_root(input); const auto& in_adj = boost::inv_adjacent_vertices(root, m_graph); const auto& in_begin = in_adj.first; const auto& in_end = in_adj.second; std::vector<vertex_t> result; result.reserve(1 + (in_end - in_begin)); result.push_back(root); for (auto it = in_begin; it != in_end; ++it) { result.push_back(*it); } return result; } // return true if `v` has no neighbors bool AliasedRegisters::is_singleton(vertex_t v) { return !has_outgoing(v) && !has_incoming(v); } // return true if `v` has any incoming edges (equivalent to v being a root of a // non-singleton tree) bool AliasedRegisters::has_incoming(vertex_t v) { const auto& in_adj = boost::inv_adjacent_vertices(v, m_graph); const auto& in_begin = in_adj.first; const auto& in_end = in_adj.second; return in_begin != in_end; } // return true if `v` has any outgoing edges (equivalent to v being a leaf) bool AliasedRegisters::has_outgoing(vertex_t v) { const auto& out_adj = boost::adjacent_vertices(v, m_graph); const auto& out_begin = out_adj.first; const auto& out_end = out_adj.second; return out_begin != out_end; } // ---- extends AbstractValue ---- void AliasedRegisters::clear() { m_graph.clear(); m_insert_order.clear(); } AbstractValueKind AliasedRegisters::kind() const { return (boost::num_edges(m_graph) > 0) ? AbstractValueKind::Value : AbstractValueKind::Top; } // leq (<=) is the superset relation on the alias groups bool AliasedRegisters::leq(const AliasedRegisters& other) const { if (boost::num_edges(m_graph) < boost::num_edges(other.m_graph)) { // this cannot be a superset of other if this has fewer edges return false; } // for all edges in `other` (the potential subset), make sure `this` has that // alias relationship const auto& iters = boost::edges(other.m_graph); const auto& begin = iters.first; const auto& end = iters.second; for (auto it = begin; it != end; ++it) { const Value& r1 = other.m_graph[boost::source(*it, other.m_graph)]; const Value& r2 = other.m_graph[boost::target(*it, other.m_graph)]; if (!are_aliases(r1, r2)) { return false; } } return true; } // returns true iff they have exactly the same edges between the same Values bool AliasedRegisters::equals(const AliasedRegisters& other) const { return boost::num_edges(m_graph) == boost::num_edges(other.m_graph) && leq(other); } AbstractValueKind AliasedRegisters::narrow_with(const AliasedRegisters& other) { return meet_with(other); } AbstractValueKind AliasedRegisters::widen_with(const AliasedRegisters& other) { return join_with(other); } // alias group union AbstractValueKind AliasedRegisters::meet_with(const AliasedRegisters& other) { always_assert_log(false, "UNUSED"); } // Alias group intersection. // Only keep the alias relationships that both `this` and `other` contain. AbstractValueKind AliasedRegisters::join_with(const AliasedRegisters& other) { auto this_before_groups = this->all_groups(); // Remove all edges from this graph. We will add back the ones that `other` // also has using edge_t = boost::graph_traits<Graph>::edge_descriptor; boost::remove_edge_if([](const edge_t&) { return true; }, m_graph); // Break up each group into some number of new groups. // Intersection can't create any groups larger than what `this` had, only the // same size or smaller. for (auto& group : this_before_groups) { // Sort so that we only have to scan the nodes after the potential root // (remember that the root node must sort lowest of its tree) std::sort(group.begin(), group.end(), [this](vertex_t v1, vertex_t v2) { return m_graph[v1] < m_graph[v2]; }); // Starting with the lowest node, grab all the singletons that `other` // agrees are aliased with this potential root. // Repeat with the next potential root. size_t sz = group.size(); for (size_t i = 0; i < sz; ++i) { vertex_t new_root = group[i]; if (has_outgoing(new_root)) { // This can't be a new root because it's already a leaf continue; } // We can start iterating from i + 1 because everything beneath `i` has // already been considered as a potential root and had all possible nodes // added to its tree. for (size_t j = i + 1; j < sz; ++j) { // If `v` hasn't already been added to another tree and `other` agrees, // then add the edge. vertex_t v = group[j]; if (!has_outgoing(v) && other.are_aliases(this->m_graph[v], this->m_graph[new_root])) { boost::add_edge(v, new_root, m_graph); } } } } handle_edge_intersection_insert_order(other); return AbstractValueKind::Value; } void AliasedRegisters::handle_edge_intersection_insert_order( const AliasedRegisters& other) { // Clear out stale values in `m_insert_order` for vertices removed from // groups. const auto& iters = boost::vertices(this->m_graph); const auto& begin = iters.first; const auto& end = iters.second; for (auto it = begin; it != end; ++it) { if (is_singleton(*it)) { clear_insert_number(*it); } } // Assign new insertion numbers while taking into account both insertion maps. for (auto& group : all_groups()) { handle_insert_order_at_merge(group, other); } } // Merge the ordering in `other.m_insert_order` into `this->m_insert_order`. // // When both graphs know about an edge (and they don't agree about insertion // order), use register number. // When only one graph knows about an edge, use insertion order from that graph. // When neither graph knows about the edge, use register number. void AliasedRegisters::handle_insert_order_at_merge( const std::vector<vertex_t>& group, const AliasedRegisters& other) { renumber_insert_order(group, [this, &other](vertex_t a, vertex_t b) { // return true if `a` occurs before `b`. // return false if they compare equal or if `b` occurs before `a`. if (a == b) return false; // `a` and `b` only index into this, not other. const Value& val_a = this->m_graph[a]; const Value& val_b = this->m_graph[b]; bool this_has = this->vertices_are_aliases(a, b); boost::optional<vertex_t> other_a = other.find(val_a); boost::optional<vertex_t> other_b = (other_a == boost::none ? boost::none : other.find_in_tree(val_b, *other_a)); bool other_has = other_b != boost::none; if (this_has && other_has) { // Intersection case should always come here bool this_less_than = this->m_insert_order.at(a) < this->m_insert_order.at(b); bool other_less_than = other.m_insert_order.at(*other_a) < other.m_insert_order.at(*other_b); if (this_less_than == other_less_than) { // The graphs agree on the order of these two vertices. // Preserve that order. return this_less_than; } else { // The graphs do not agree. Choose a deterministic order return val_a.reg() < val_b.reg(); } } else if (this_has) { return this->m_insert_order.at(a) < this->m_insert_order.at(b); } else if (other_has) { return other.m_insert_order.at(*other_a) < other.m_insert_order.at(*other_b); } else { // Neither graph has this relationship. Choose a deterministic order return val_a.reg() < val_b.reg(); } }); } // Rewrite the insertion number of all registers in `group` in an order defined // by `less_than` void AliasedRegisters::renumber_insert_order( std::vector<vertex_t> group, const std::function<bool(vertex_t, vertex_t)>& less_than) { // Filter out non registers. group.erase( std::remove_if(group.begin(), group.end(), [this](vertex_t v) { return !m_graph[v].is_register(); }), group.end()); if (group.size() < 2) { // No need to assign insert order for singletons return; } // Assign new insertion numbers based on sorting. std::sort(group.begin(), group.end(), less_than); size_t i = 0; for (vertex_t v : group) { this->m_insert_order[v] = i; ++i; } } // return all groups (not including singletons) std::vector<std::vector<vertex_t>> AliasedRegisters::all_groups() { std::vector<std::vector<vertex_t>> result; std::unordered_set<vertex_t> visited; const auto& iters = boost::vertices(this->m_graph); const auto& begin = iters.first; const auto& end = iters.second; for (auto it = begin; it != end; ++it) { vertex_t root = find_root(*it); const auto& pair = visited.insert(root); bool insertion_took_place = pair.second; if (insertion_took_place) { auto group = vertices_in_group(root); if (group.size() > 1) { result.emplace_back(std::move(group)); } } } return result; } // returns a string representation of this data structure. Intended for // debugging. std::string AliasedRegisters::dump() const { std::ostringstream oss; const auto& iters = boost::edges(this->m_graph); const auto& begin = iters.first; const auto& end = iters.second; oss << "Graph [" << std::endl; for (auto it = begin; it != end; ++it) { const Value& r1 = m_graph[boost::source(*it, m_graph)]; const Value& r2 = m_graph[boost::target(*it, m_graph)]; oss << "(" << r1.str().c_str() << " -> " << r2.str().c_str() << ") " << std::endl; } oss << "] insert order [" << std::endl; for (const auto& entry : m_insert_order) { vertex_t v = entry.first; const Value& r = m_graph[v]; size_t i = entry.second; oss << r.str().c_str() << " has index " << i << std::endl; } oss << "]" << std::endl; return oss.str(); } bool Value::operator==(const Value& other) const { if (m_kind != other.m_kind) { return false; } switch (m_kind) { case Kind::REGISTER: return m_reg == other.m_reg; case Kind::CONST_LITERAL: case Kind::CONST_LITERAL_UPPER: return m_literal == other.m_literal && m_type_demand == other.m_type_demand; case Kind::CONST_STRING: return m_str == other.m_str; case Kind::CONST_TYPE: return m_type == other.m_type; case Kind::STATIC_FINAL: case Kind::STATIC_FINAL_UPPER: return m_field == other.m_field; case Kind::NONE: return true; } } bool Value::operator<(const Value& other) const { if (m_kind != other.m_kind) { return m_kind < other.m_kind; } switch (m_kind) { case Kind::REGISTER: return m_reg < other.m_reg; case Kind::CONST_LITERAL: case Kind::CONST_LITERAL_UPPER: if (m_literal != other.m_literal) { return m_literal < other.m_literal; } else { return m_type_demand < other.m_type_demand; } case Kind::CONST_STRING: return compare_dexstrings(m_str, other.m_str); case Kind::CONST_TYPE: return compare_dextypes(m_type, other.m_type); case Kind::STATIC_FINAL: case Kind::STATIC_FINAL_UPPER: return compare_dexfields(m_field, other.m_field); case Kind::NONE: always_assert_log(false, "can't sort NONEs"); } } // returns a string representation of this Value. Intended for debugging. std::string Value::str() const { std::ostringstream oss; switch (m_kind) { case Kind::REGISTER: oss << "v" << m_reg; break; case Kind::CONST_LITERAL: oss << m_literal; break; case Kind::CONST_LITERAL_UPPER: oss << m_literal << " upper"; break; case Kind::CONST_STRING: oss << m_str->str(); break; case Kind::CONST_TYPE: oss << m_type->str(); break; case Kind::STATIC_FINAL: oss << m_field->str(); break; case Kind::STATIC_FINAL_UPPER: oss << m_field->str() << " upper"; break; case Kind::NONE: oss << "NONE"; break; } return oss.str(); } } // namespace aliased_registers
#include <ctime> #include "uipcp-rib.hpp" using namespace std; static uint64_t time64() { struct timespec tv; if (clock_gettime(CLOCK_MONOTONIC, &tv)) { PE("clock_gettime() failed\n"); tv.tv_sec = 0; tv.tv_nsec = 0; } return (tv.tv_sec << 32) | (tv.tv_nsec & ((1L << 32) - 1L)); } uint64_t uipcp_rib::dft_lookup(const RinaName& appl_name) const { map< string, DFTEntry >::const_iterator mit = dft.find(static_cast<string>(appl_name)); if (mit == dft.end()) { return 0; } return mit->second.address; } int uipcp_rib::dft_set(const RinaName& appl_name, uint64_t remote_addr) { string key = static_cast<string>(appl_name); DFTEntry entry; entry.address = remote_addr; entry.appl_name = appl_name; entry.timestamp = time64(); dft[key] = entry; PD("[uipcp %u] setting DFT entry '%s' --> %llu\n", uipcp->ipcp_id, key.c_str(), (long long unsigned)entry.address); return 0; } int uipcp_rib::application_register(int reg, const RinaName& appl_name) { map< string, DFTEntry >::iterator mit; uint64_t local_addr; string name_str; int ret; bool create = true; DFTSlice dft_slice; DFTEntry dft_entry; ret = rinalite_lookup_ipcp_addr_by_id(&uipcp->appl.loop, uipcp->ipcp_id, &local_addr); assert(!ret); dft_entry.address = local_addr; dft_entry.appl_name = appl_name; dft_entry.timestamp = time64(); name_str = static_cast<string>(dft_entry.appl_name); mit = dft.find(name_str); if (reg) { if (mit != dft.end()) { PE("Application %s already registered on uipcp with address " "[%llu], my address being [%llu]\n", name_str.c_str(), (long long unsigned)mit->second.address, (long long unsigned)local_addr); return -1; } /* Insert the object into the RIB. */ dft.insert(make_pair(name_str, dft_entry)); } else { if (mit == dft.end()) { PE("Application %s was not registered here\n", name_str.c_str()); return -1; } /* Remove the object from the RIB. */ dft.erase(mit); create = false; } dft_slice.entries.push_back(dft_entry); PD("Application %s %sregistered %s uipcp %d\n", name_str.c_str(), reg ? "" : "un", reg ? "to" : "from", uipcp->ipcp_id); remote_sync_all(create, obj_class::dft, obj_name::dft, &dft_slice); return 0; } int uipcp_rib::dft_handler(const CDAPMessage *rm, Neighbor *neigh) { const char *objbuf; size_t objlen; bool add = true; if (rm->op_code != gpb::M_CREATE && rm->op_code != gpb::M_DELETE) { PE("M_CREATE or M_DELETE expected\n"); return 0; } if (rm->op_code == gpb::M_DELETE) { add = false; } rm->get_obj_value(objbuf, objlen); if (!objbuf) { PE("M_START does not contain a nested message\n"); abort(); return 0; } DFTSlice dft_slice(objbuf, objlen); DFTSlice prop_dft; for (list<DFTEntry>::iterator e = dft_slice.entries.begin(); e != dft_slice.entries.end(); e++) { string key = static_cast<string>(e->appl_name); map< string, DFTEntry >::iterator mit = dft.find(key); if (add) { if (mit == dft.end() || e->timestamp > mit->second.timestamp) { dft[key] = *e; PD("DFT entry %s %s remotely\n", key.c_str(), (mit != dft.end() ? "updated" : "added")); } } else { if (mit == dft.end()) { PI("DFT entry does not exist\n"); } else { dft.erase(mit); prop_dft.entries.push_back(*e); PD("DFT entry %s removed remotely\n", key.c_str()); } } } if (add) { prop_dft = dft_slice; } if (prop_dft.entries.size()) { /* Propagate the DFT entries update to the other neighbors, * except for the one. */ /* TODO loops are not managed here! */ remote_sync_excluding(neigh, add, obj_class::dft, obj_name::dft, &prop_dft); } return 0; } uipcp: application-registration: avoid DFT update cycles #include <ctime> #include "uipcp-rib.hpp" using namespace std; static uint64_t time64() { struct timespec tv; if (clock_gettime(CLOCK_MONOTONIC, &tv)) { PE("clock_gettime() failed\n"); tv.tv_sec = 0; tv.tv_nsec = 0; } return (tv.tv_sec << 32) | (tv.tv_nsec & ((1L << 32) - 1L)); } uint64_t uipcp_rib::dft_lookup(const RinaName& appl_name) const { map< string, DFTEntry >::const_iterator mit = dft.find(static_cast<string>(appl_name)); if (mit == dft.end()) { return 0; } return mit->second.address; } int uipcp_rib::dft_set(const RinaName& appl_name, uint64_t remote_addr) { string key = static_cast<string>(appl_name); DFTEntry entry; entry.address = remote_addr; entry.appl_name = appl_name; entry.timestamp = time64(); dft[key] = entry; PD("[uipcp %u] setting DFT entry '%s' --> %llu\n", uipcp->ipcp_id, key.c_str(), (long long unsigned)entry.address); return 0; } int uipcp_rib::application_register(int reg, const RinaName& appl_name) { map< string, DFTEntry >::iterator mit; uint64_t local_addr; string name_str; int ret; bool create = true; DFTSlice dft_slice; DFTEntry dft_entry; ret = rinalite_lookup_ipcp_addr_by_id(&uipcp->appl.loop, uipcp->ipcp_id, &local_addr); assert(!ret); dft_entry.address = local_addr; dft_entry.appl_name = appl_name; dft_entry.timestamp = time64(); name_str = static_cast<string>(dft_entry.appl_name); mit = dft.find(name_str); if (reg) { if (mit != dft.end()) { PE("Application %s already registered on uipcp with address " "[%llu], my address being [%llu]\n", name_str.c_str(), (long long unsigned)mit->second.address, (long long unsigned)local_addr); return -1; } /* Insert the object into the RIB. */ dft.insert(make_pair(name_str, dft_entry)); } else { if (mit == dft.end()) { PE("Application %s was not registered here\n", name_str.c_str()); return -1; } /* Remove the object from the RIB. */ dft.erase(mit); create = false; } dft_slice.entries.push_back(dft_entry); PD("Application %s %sregistered %s uipcp %d\n", name_str.c_str(), reg ? "" : "un", reg ? "to" : "from", uipcp->ipcp_id); remote_sync_all(create, obj_class::dft, obj_name::dft, &dft_slice); return 0; } int uipcp_rib::dft_handler(const CDAPMessage *rm, Neighbor *neigh) { const char *objbuf; size_t objlen; bool add = true; if (rm->op_code != gpb::M_CREATE && rm->op_code != gpb::M_DELETE) { PE("M_CREATE or M_DELETE expected\n"); return 0; } if (rm->op_code == gpb::M_DELETE) { add = false; } rm->get_obj_value(objbuf, objlen); if (!objbuf) { PE("M_START does not contain a nested message\n"); abort(); return 0; } DFTSlice dft_slice(objbuf, objlen); DFTSlice prop_dft; for (list<DFTEntry>::iterator e = dft_slice.entries.begin(); e != dft_slice.entries.end(); e++) { string key = static_cast<string>(e->appl_name); map< string, DFTEntry >::iterator mit = dft.find(key); if (add) { if (mit == dft.end() || e->timestamp > mit->second.timestamp) { dft[key] = *e; prop_dft.entries.push_back(*e); PD("DFT entry %s %s remotely\n", key.c_str(), (mit != dft.end() ? "updated" : "added")); } } else { if (mit == dft.end()) { PI("DFT entry does not exist\n"); } else { dft.erase(mit); prop_dft.entries.push_back(*e); PD("DFT entry %s removed remotely\n", key.c_str()); } } } if (prop_dft.entries.size()) { /* Propagate the DFT entries update to the other neighbors, * except for the one. */ remote_sync_excluding(neigh, add, obj_class::dft, obj_name::dft, &prop_dft); } return 0; }
#include "actiondb.h" #include "main.h" #include <iostream> #include <fstream> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/shared_ptr.hpp> //#include <boost/serialization/base_object.hpp> // I don't know WHY I need this, I'm just glad I found out I did... BOOST_CLASS_EXPORT(StrokeSet) BOOST_CLASS_EXPORT(Action) BOOST_CLASS_EXPORT(Command) BOOST_CLASS_EXPORT(ModAction) BOOST_CLASS_EXPORT(SendKey) BOOST_CLASS_EXPORT(Scroll) BOOST_CLASS_EXPORT(Ignore) template<class Archive> void Action::serialize(Archive & ar, const unsigned int version) { } template<class Archive> void Command::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & cmd; } template<class Archive> void ModAction::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & mods; } template<class Archive> void SendKey::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); ar & key; ar & code; ar & xtest; } template<class Archive> void Scroll::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); } template<class Archive> void Ignore::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); } template<class Archive> void StrokeSet::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<std::set<RStroke> >(*this); } template<class Archive> void StrokeInfo::serialize(Archive & ar, const unsigned int version) { ar & strokes; ar & action; if (version == 0) return; ar & name; } using namespace std; bool Command::run() { system(cmd.c_str()); return true; } ActionDB::ActionDB() : filename(config_dir+"actions"), current_id(0) {} template<class Archive> void ActionDB::load(Archive & ar, const unsigned int version) { if (version >= 1) { ar & strokes; current_id = strokes.size(); return; } std::map<std::string, StrokeInfo> strokes2; ar & strokes2; for (std::map<std::string, StrokeInfo>::iterator i = strokes2.begin(); i != strokes2.end(); ++i) { i->second.name = i->first; add(i->second); } } void ActionDB::read() { try { ifstream ifs(filename.c_str(), ios::binary); boost::archive::text_iarchive ia(ifs); ia >> *this; if (verbosity >= 2) cout << "Loaded " << strokes.size() << " actions." << endl; } catch (...) { cout << "Error: Couldn't read action database." << endl; } } bool ActionDB::write() const { try { ofstream ofs(filename.c_str()); boost::archive::text_oarchive oa(ofs); const ActionDB db = *this; oa << db; if (verbosity >= 2) cout << "Saved " << strokes.size() << " actions." << endl; return true; } catch (...) { cout << "Error: Couldn't save action database." << endl; return false; } } bool ActionDB::remove(int id) { return strokes.erase(id); } int ActionDB::add(StrokeInfo &si) { strokes[current_id] = si; return current_id++; } int ActionDB::addCmd(RStroke stroke, const string& name, const string& cmd) { StrokeInfo si; if (stroke) si.strokes.insert(stroke); si.name = name; si.action = Command::create(cmd); return add(si); } int ActionDB::nested_size() const { int size = 0; for (const_iterator i = begin(); i != end(); i++) size += i->second.strokes.size(); return size; } Ranking ActionDB::handle(RStroke s) { Ranking r; r.stroke = s; r.score = -1; bool success = false; if (!s) return r; for (StrokeIterator i = strokes_begin(); i; i++) { if (!i.stroke()) continue; double score = Stroke::compare(s, i.stroke()); r.r.insert(pair<double, pair<std::string, RStroke> >(score, pair<std::string, RStroke>(strokes[i.id()].name, i.stroke()))); if (score >= r.score) { r.score = score; if (score >= 0.7) { r.id = i.id(); r.name = strokes[r.id].name; r.action = i.action(); success = true; } } } if (success) { if (verbosity >= 1) cout << "Excecuting Action " << r.name << "..." << endl; if (r.action) r.action->run(); } else { if (verbosity >= 1) cout << "Couldn't find matching stroke." << endl; } return r; } LActionDB& actions() { static LActionDB actions_; return actions_; } fixed a serious thinko darcs-hash:20080620064023-a887e-0a1dfe03fc3cfcfa585bbb9508ac4a87f710b2a9.gz #include "actiondb.h" #include "main.h" #include <iostream> #include <fstream> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/shared_ptr.hpp> //#include <boost/serialization/base_object.hpp> // I don't know WHY I need this, I'm just glad I found out I did... BOOST_CLASS_EXPORT(StrokeSet) BOOST_CLASS_EXPORT(Action) BOOST_CLASS_EXPORT(Command) BOOST_CLASS_EXPORT(ModAction) BOOST_CLASS_EXPORT(SendKey) BOOST_CLASS_EXPORT(Scroll) BOOST_CLASS_EXPORT(Ignore) template<class Archive> void Action::serialize(Archive & ar, const unsigned int version) { } template<class Archive> void Command::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & cmd; } template<class Archive> void ModAction::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & mods; } template<class Archive> void SendKey::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); ar & key; ar & code; ar & xtest; } template<class Archive> void Scroll::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); } template<class Archive> void Ignore::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); } template<class Archive> void StrokeSet::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<std::set<RStroke> >(*this); } template<class Archive> void StrokeInfo::serialize(Archive & ar, const unsigned int version) { ar & strokes; ar & action; if (version == 0) return; ar & name; } using namespace std; bool Command::run() { system(cmd.c_str()); return true; } ActionDB::ActionDB() : filename(config_dir+"actions"), current_id(0) {} template<class Archive> void ActionDB::load(Archive & ar, const unsigned int version) { if (version >= 1) { std::map<int, StrokeInfo> strokes2; ar & strokes2; for (std::map<int, StrokeInfo>::iterator i = strokes2.begin(); i != strokes2.end(); ++i) add(i->second); return; } else { std::map<std::string, StrokeInfo> strokes2; ar & strokes2; for (std::map<std::string, StrokeInfo>::iterator i = strokes2.begin(); i != strokes2.end(); ++i) { i->second.name = i->first; add(i->second); } return; } } void ActionDB::read() { try { ifstream ifs(filename.c_str(), ios::binary); boost::archive::text_iarchive ia(ifs); ia >> *this; if (verbosity >= 2) cout << "Loaded " << strokes.size() << " actions." << endl; } catch (...) { cout << "Error: Couldn't read action database." << endl; } } bool ActionDB::write() const { try { ofstream ofs(filename.c_str()); boost::archive::text_oarchive oa(ofs); const ActionDB db = *this; oa << db; if (verbosity >= 2) cout << "Saved " << strokes.size() << " actions." << endl; return true; } catch (...) { cout << "Error: Couldn't save action database." << endl; return false; } } bool ActionDB::remove(int id) { return strokes.erase(id); } int ActionDB::add(StrokeInfo &si) { strokes[current_id] = si; return current_id++; } int ActionDB::addCmd(RStroke stroke, const string& name, const string& cmd) { StrokeInfo si; if (stroke) si.strokes.insert(stroke); si.name = name; si.action = Command::create(cmd); return add(si); } int ActionDB::nested_size() const { int size = 0; for (const_iterator i = begin(); i != end(); i++) size += i->second.strokes.size(); return size; } Ranking ActionDB::handle(RStroke s) { Ranking r; r.stroke = s; r.score = -1; bool success = false; if (!s) return r; for (StrokeIterator i = strokes_begin(); i; i++) { if (!i.stroke()) continue; double score = Stroke::compare(s, i.stroke()); r.r.insert(pair<double, pair<std::string, RStroke> >(score, pair<std::string, RStroke>(strokes[i.id()].name, i.stroke()))); if (score >= r.score) { r.score = score; if (score >= 0.7) { r.id = i.id(); r.name = strokes[r.id].name; r.action = i.action(); success = true; } } } if (success) { if (verbosity >= 1) cout << "Excecuting Action " << r.name << "..." << endl; if (r.action) r.action->run(); } else { if (verbosity >= 1) cout << "Couldn't find matching stroke." << endl; } return r; } LActionDB& actions() { static LActionDB actions_; return actions_; }
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/instrument/transforms/asan_transform.h" #include <vector> #include "base/logging.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/memory/ref_counted.h" #include "syzygy/block_graph/basic_block_assembler.h" #include "syzygy/block_graph/block_builder.h" #include "syzygy/block_graph/block_util.h" #include "syzygy/common/defs.h" #include "syzygy/pe/block_util.h" #include "syzygy/pe/pe_utils.h" #include "syzygy/pe/transforms/add_imports_transform.h" #include "third_party/distorm/files/include/mnemonics.h" #include "third_party/distorm/files/src/x86defs.h" namespace instrument { namespace transforms { namespace { using block_graph::BasicBlock; using block_graph::BasicCodeBlock; using block_graph::BasicBlockAssembler; using block_graph::BasicBlockSubGraph; using block_graph::BasicBlockReference; using block_graph::BlockBuilder; using block_graph::BlockGraph; using block_graph::Displacement; using block_graph::Immediate; using block_graph::Instruction; using block_graph::Operand; using block_graph::TypedBlock; using block_graph::Value; using block_graph::analysis::LivenessAnalysis; using core::Register; using core::RegisterCode; using pe::transforms::AddImportsTransform; // A simple struct that can be used to let us access strings using TypedBlock. struct StringStruct { const char string[1]; }; typedef AddImportsTransform::ImportedModule ImportedModule; typedef AsanBasicBlockTransform::MemoryAccessMode AsanMemoryAccessMode; typedef AsanBasicBlockTransform::AsanHookMap HookMap; typedef std::vector<AsanBasicBlockTransform::AsanHookMapEntryKey> AccessHookParamVector; typedef TypedBlock<IMAGE_IMPORT_DESCRIPTOR> ImageImportDescriptor; typedef TypedBlock<StringStruct> String; // Returns true iff opcode should be instrumented. bool ShouldInstrumentOpcode(uint16 opcode) { switch (opcode) { case I_LEA: case I_CALL: case I_JMP: return false; default: return true; } } // Computes the correct displacement, if any, for operand // number @p operand of @p instr. Displacement ComputeDisplacementForOperand(const Instruction& instr, size_t operand) { const _DInst& repr = instr.representation(); DCHECK(repr.ops[operand].type == O_SMEM || repr.ops[operand].type == O_MEM); size_t access_size_bytes = repr.ops[operand].size / 8; if (repr.dispSize == 0) return Displacement(access_size_bytes - 1); BasicBlockReference reference; if (instr.FindOperandReference(operand, &reference)) { if (reference.referred_type() == BasicBlockReference::REFERRED_TYPE_BLOCK) { return Displacement(reference.block(), reference.offset() + access_size_bytes - 1); } else { return Displacement(reference.basic_block()); } } else { return Displacement(repr.disp + access_size_bytes - 1); } } // Returns true if operand @p op is instrumentable, e.g. // if it implies a memory access. bool IsInstrumentable(const _Operand& op) { switch (op.type) { case O_SMEM: case O_MEM: return true; default: return false; } } // Returns true if opcode @p opcode is a special instruction. // Memory checks for special instructions (string instructions, instructions // with prefix, etc) are handled by calling specialized functions rather than // the standard memory checks. bool IsSpecialInstruction(uint16_t opcode) { switch (opcode) { case I_CMPS: case I_STOS: case I_MOVS: return true; default: return false; } } // Decodes the first O_MEM or O_SMEM operand of @p instr, if any to the // corresponding Operand. bool DecodeMemoryAccess(const Instruction& instr, Operand* access, AsanBasicBlockTransform::MemoryAccessInfo* info) { DCHECK(access != NULL); DCHECK(info != NULL); const _DInst& repr = instr.representation(); // Figure out which operand we're instrumenting. size_t mem_op_id = -1; if (IsInstrumentable(repr.ops[0]) && IsInstrumentable(repr.ops[1])) { // This happens with instructions like: MOVS [EDI], [ESI]. DCHECK(repr.ops[0].size == repr.ops[1].size); mem_op_id = 0; } else if (IsInstrumentable(repr.ops[0])) { // The first operand is instrumentable. mem_op_id = 0; } else if (IsInstrumentable(repr.ops[1])) { // The second operand is instrumentable. mem_op_id = 1; } else { // Neither of the first two operands is instrumentable. return false; } // Determine the size of the access. info->size = repr.ops[mem_op_id].size / 8; // Determine the kind of access (read/write/instr/repz). if (FLAG_GET_PREFIX(repr.flags) & FLAG_REPNZ) info->mode = AsanBasicBlockTransform::kRepnzAccess; else if (FLAG_GET_PREFIX(repr.flags) & FLAG_REP) info->mode = AsanBasicBlockTransform::kRepzAccess; else if (IsSpecialInstruction(instr.opcode())) info->mode = AsanBasicBlockTransform::kInstrAccess; else if ((repr.flags & FLAG_DST_WR) && mem_op_id == 0) { // The first operand is written to. info->mode = AsanBasicBlockTransform::kWriteAccess; } else { info->mode = AsanBasicBlockTransform::kReadAccess; } // Determine the opcode of this instruction (when needed). if (info->mode == AsanBasicBlockTransform::kRepnzAccess || info->mode == AsanBasicBlockTransform::kRepzAccess || info->mode == AsanBasicBlockTransform::kInstrAccess) { info->opcode = instr.opcode(); } // Determine operand of the access. if (repr.ops[mem_op_id].type == O_SMEM) { // Simple memory dereference with optional displacement. Register base_reg(RegisterCode(repr.ops[mem_op_id].index - R_EAX)); // Get the displacement for the operand. Displacement displ = ComputeDisplacementForOperand(instr, mem_op_id); *access = Operand(base_reg, displ); } else if (repr.ops[0].type == O_MEM || repr.ops[1].type == O_MEM) { // Complex memory dereference. Register index_reg(RegisterCode(repr.ops[mem_op_id].index - R_EAX)); core::ScaleFactor scale = core::kTimes1; switch (repr.scale) { case 2: scale = core::kTimes2; break; case 4: scale = core::kTimes4; break; case 8: scale = core::kTimes8; break; default: break; } // Get the displacement for the operand (if any). Displacement displ = ComputeDisplacementForOperand(instr, mem_op_id); // Compute the full operand. if (repr.base != R_NONE) { Register base_reg(RegisterCode(repr.base - R_EAX)); if (displ.size() == core::kSizeNone) { // No displacement, it's a [base + index * scale] access. *access = Operand(base_reg, index_reg, scale); } else { // This is a [base + index * scale + displ] access. *access = Operand(base_reg, index_reg, scale, displ); } } else { // No base, this is an [index * scale + displ] access. // TODO(siggi): AFAIK, there's no encoding for [index * scale] without // a displacement. If this assert fires, I'm proven wrong. DCHECK_NE(core::kSizeNone, displ.size()); *access = Operand(index_reg, scale, displ); } } else { NOTREACHED(); return false; } return true; } // Use @p bb_asm to inject a hook to @p hook to instrument the access to the // address stored in the operand @p op. void InjectAsanHook(BasicBlockAssembler* bb_asm, const AsanBasicBlockTransform::MemoryAccessInfo& info, const Operand& op, BlockGraph::Reference* hook, const LivenessAnalysis::State& state) { DCHECK(hook != NULL); // TODO(etienneb): Use liveness information to implement more efficient hook. // Determine which kind of probe to inject. if (info.mode == AsanBasicBlockTransform::kReadAccess || info.mode == AsanBasicBlockTransform::kWriteAccess) { // The standard load/store probe assume the address is in EDX. // It restore the original version of EDX and cleanup the stack. bb_asm->push(core::edx); bb_asm->lea(core::edx, op); bb_asm->call(Operand(Displacement(hook->referenced(), hook->offset()))); } else { // The special instruction probe take addresses directly in registers. // The probe doesn't have any effects on stack, registers and flags. bb_asm->call(Operand(Displacement(hook->referenced(), hook->offset()))); } } typedef std::pair<BlockGraph::Block*, BlockGraph::Offset> ReferenceDest; typedef std::map<ReferenceDest, ReferenceDest> ReferenceMap; typedef std::set<BlockGraph::Block*> BlockSet; // For every block referencing @p dst_blocks, redirects any reference "ref" in // @p redirects to @p redirects[ref]. void RedirectReferences(const BlockSet& dst_blocks, const ReferenceMap& redirects) { // For each block referenced by any source reference. BlockSet::const_iterator dst_block_it = dst_blocks.begin(); for (; dst_block_it != dst_blocks.end(); ++dst_block_it) { // Iterate over all their referrers. BlockGraph::Block* referred_block = *dst_block_it; BlockGraph::Block::ReferrerSet referrers = referred_block->referrers(); BlockGraph::Block::ReferrerSet::iterator referrer_it = referrers.begin(); for (; referrer_it != referrers.end(); ++referrer_it) { BlockGraph::Block* referrer = referrer_it->first; // Don't redirect references from PE parsed blocks. This actually ends up // redirecting the IAT entries as well in the worst case. if (referrer->attributes() & BlockGraph::PE_PARSED) continue; // And redirect any references that happen to match a source reference. BlockGraph::Block::ReferenceMap::const_iterator reference_it = referrer->references().begin(); for (; reference_it != referrer->references().end(); ++reference_it) { const BlockGraph::Reference& ref(reference_it->second); ReferenceDest dest(std::make_pair(ref.referenced(), ref.offset())); ReferenceMap::const_iterator it(redirects.find(dest)); if (it != redirects.end()) { BlockGraph::Reference new_reference(ref.type(), ref.size(), it->second.first, it->second.second, 0); referrer->SetReference(reference_it->first, new_reference); } } } } } // Get the name of an asan check access function for an @p access_mode access. // @param info The memory access information, e.g. the size on a load/store, // the instruction opcode and the kind of access. std::string GetAsanCheckAccessFunctionName( AsanBasicBlockTransform::MemoryAccessInfo info) { DCHECK(info.mode != AsanBasicBlockTransform::kNoAccess); DCHECK(info.size != 0); DCHECK(info.mode == AsanBasicBlockTransform::kReadAccess || info.mode == AsanBasicBlockTransform::kWriteAccess || info.opcode != 0); const char* rep_str = NULL; if (info.mode == AsanBasicBlockTransform::kRepzAccess) rep_str = "_repz"; else if (info.mode == AsanBasicBlockTransform::kRepnzAccess) rep_str = "_repnz"; else rep_str = ""; const char* access_mode_str = NULL; if (info.mode == AsanBasicBlockTransform::kReadAccess) access_mode_str = "read"; else if (info.mode == AsanBasicBlockTransform::kWriteAccess) access_mode_str = "write"; else access_mode_str = reinterpret_cast<char*>(GET_MNEMONIC_NAME(info.opcode)); std::string function_name = base::StringPrintf("asan_check%s_%d_byte_%s_access%s", rep_str, info.size, access_mode_str, info.save_flags ? "" : "_no_flags"); StringToLowerASCII(&function_name); return function_name.c_str(); } // Add the imports for the asan check access hooks to the block-graph. // @param hooks_param_vector A vector of hook parameter values. // @param default_stub_map Stubs for the asan check access functions. // @param import_module The module for which the import should be added. // @param check_access_hook_map The map where the reference to the imports // should be stored. // @param block_graph The block-graph to populate. // @param header_block The block containing the module's DOS header of this // block-graph. // @returns True on success, false otherwise. bool AddAsanCheckAccessHooks( const AccessHookParamVector& hook_param_vector, const AsanBasicBlockTransform::AsanDefaultHookMap& default_stub_map, ImportedModule* import_module, HookMap* check_access_hook_map, BlockGraph* block_graph, BlockGraph::Block* header_block) { DCHECK(import_module != NULL); DCHECK(check_access_hook_map != NULL); DCHECK(block_graph != NULL); DCHECK(header_block != NULL); // Add the hooks to the import module. typedef std::map<AsanBasicBlockTransform::AsanHookMapEntryKey, size_t> HooksParamsToIdxMap; HooksParamsToIdxMap hooks_params_to_idx; AccessHookParamVector::const_iterator iter_params = hook_param_vector.begin(); for (; iter_params != hook_param_vector.end(); ++iter_params) { size_t symbol_idx = import_module->AddSymbol( GetAsanCheckAccessFunctionName(*iter_params), ImportedModule::kAlwaysImport); hooks_params_to_idx[*iter_params] = symbol_idx; } DCHECK_EQ(hooks_params_to_idx.size(), hook_param_vector.size()); // Transforms the block-graph. AddImportsTransform add_imports_transform; add_imports_transform.AddModule(import_module); if (!add_imports_transform.TransformBlockGraph(block_graph, header_block)) { LOG(ERROR) << "Unable to add imports for Asan instrumentation DLL."; return false; } // Get a reference to each hook and put it in the hooks map. HooksParamsToIdxMap::iterator iter_hooks = hooks_params_to_idx.begin(); for (; iter_hooks != hooks_params_to_idx.end(); ++iter_hooks) { BlockGraph::Reference import_reference; if (!import_module->GetSymbolReference(iter_hooks->second, &import_reference)) { LOG(ERROR) << "Unable to get import reference for Asan."; return false; } HookMap& hook_map = *check_access_hook_map; hook_map[iter_hooks->first] = import_reference; // In a Chrome sandboxed process the NtMapViewOfSection function is // intercepted by the sandbox agent. This causes execution in the executable // before imports have been resolved, as the ntdll patch invokes into the // executable while resolving imports. As the Asan instrumentation directly // refers to the IAT entries we need to temporarily stub these function // until the Asan imports are resolved. To do this we need to make the IAT // entries for those functions point to a temporarily block and we need to // mark the image import descriptor for this DLL as bound. AsanBasicBlockTransform::AsanDefaultHookMap::const_iterator stub_reference = default_stub_map.find(iter_hooks->first.mode); if (stub_reference == default_stub_map.end()) { LOG(ERROR) << "Could not find the default hook for " << GetAsanCheckAccessFunctionName(iter_hooks->first) << "."; return false; } import_reference.referenced()->SetReference(import_reference.offset(), stub_reference->second); } return true; } // Create a stub for the asan_check_access functions. For load/store, the stub // consists of a small block of code that restores the value of EDX and returns // to the caller. Otherwise, the stub do return. // @param block_graph The block-graph to populate with the stub. // @param stub_name The stub's name. // @param mode The kind of memory access. // @param A pointer to the stub's block on success, NULL otherwise. // @param reference Will receive the reference to the created hook. // @returns true on success, false otherwise. bool CreateHooksStub(BlockGraph* block_graph, const base::StringPiece& stub_name, AsanBasicBlockTransform::MemoryAccessMode mode, BlockGraph::Reference* reference) { DCHECK(reference != NULL); // Find or create the section we put our thunks in. BlockGraph::Section* thunk_section = block_graph->FindOrAddSection( common::kThunkSectionName, pe::kCodeCharacteristics); if (thunk_section == NULL) { LOG(ERROR) << "Unable to find or create .thunks section."; return false; } std::string stub_name_with_id = base::StringPrintf( "%.*s%d", stub_name.length(), stub_name.data(), mode); // Create the thunk for standard "load/store" (received address in EDX). BasicBlockSubGraph bbsg; BasicBlockSubGraph::BlockDescription* block_desc = bbsg.AddBlockDescription( stub_name_with_id, BlockGraph::CODE_BLOCK, thunk_section->id(), 1, 0); BasicCodeBlock* bb = bbsg.AddBasicCodeBlock(stub_name_with_id); block_desc->basic_block_order.push_back(bb); BasicBlockAssembler assm(bb->instructions().begin(), &bb->instructions()); if (mode == AsanBasicBlockTransform::kReadAccess || mode == AsanBasicBlockTransform::kWriteAccess) { // The thunk body restores the original value of EDX and cleans the stack on // return. assm.mov(core::edx, Operand(core::esp, Displacement(4))); assm.ret(4); } else { assm.ret(); } // Condense into a block. BlockBuilder block_builder(block_graph); if (!block_builder.Merge(&bbsg)) { LOG(ERROR) << "Failed to build thunk block."; return NULL; } // Exactly one new block should have been created. DCHECK_EQ(1u, block_builder.new_blocks().size()); BlockGraph::Block* thunk = block_builder.new_blocks().front(); *reference = BlockGraph::Reference(BlockGraph::ABSOLUTE_REF, 4, thunk, 0, 0); return true; } } // namespace const char AsanBasicBlockTransform::kTransformName[] = "SyzyAsanBasicBlockTransform"; bool AsanBasicBlockTransform::InstrumentBasicBlock( BasicCodeBlock* basic_block, StackAccessMode stack_mode) { DCHECK(basic_block != NULL); // Pre-compute liveness information for each instruction. std::list<LivenessAnalysis::State> states; LivenessAnalysis::State state; liveness_.GetStateAtExitOf(basic_block, &state); BasicBlock::Instructions::reverse_iterator rev_iter_inst = basic_block->instructions().rbegin(); for (; rev_iter_inst != basic_block->instructions().rend(); ++rev_iter_inst) { const Instruction& instr = *rev_iter_inst; liveness_.PropagateBackward(instr, &state); states.push_front(state); } DCHECK_EQ(states.size(), basic_block->instructions().size()); // Process each instruction and inject a call to Asan when we find an // instrumentable memory access. BasicBlock::Instructions::iterator iter_inst = basic_block->instructions().begin(); std::list<LivenessAnalysis::State>::iterator iter_state = states.begin(); for (; iter_inst != basic_block->instructions().end(); ++iter_inst) { Operand operand(core::eax); const Instruction& instr = *iter_inst; const _DInst& repr = instr.representation(); MemoryAccessInfo info; info.mode = kNoAccess; info.size = 0; info.opcode = 0; info.save_flags = true; // Get current instruction liveness information. state = *iter_state; ++iter_state; // Insert hook for a standard instruction. if (!DecodeMemoryAccess(instr, &operand, &info)) continue; // Bail if this is not a memory access. if (info.mode == kNoAccess) continue; // A basic block reference means that can be either a computed jump, // or a load from a case table. In either case it doesn't make sense // to instrument the access. if (operand.displacement().reference().referred_type() == BasicBlockReference::REFERRED_TYPE_BASIC_BLOCK) { continue; } // A block reference means this instruction is reading or writing to // a global variable or some such. It's viable to pad and align global // variables and to red-zone the padding, but without that, there's nothing // to gain by instrumenting these accesses. if (operand.displacement().reference().referred_type() == BasicBlockReference::REFERRED_TYPE_BLOCK) { continue; } // Is this an instruction we should be instrumenting. if (!ShouldInstrumentOpcode(repr.opcode)) continue; // If there are no unconventional manipulations of the stack frame, we can // skip instrumenting stack-based memory access (based on ESP or EBP). // Conventionally, accesses through ESP/EBP are always on stack. if (stack_mode == kSafeStackAccess && (operand.base() == core::kRegisterEsp || operand.base() == core::kRegisterEbp)) { continue; } // We do not instrument memory accesses through special segments. // FS is used for thread local specifics and GS for CPU info. uint8_t segment = SEGMENT_GET(repr.segment); if (segment == R_FS || segment == R_GS) continue; // Finally, don't instrument any filtered instructions. if (IsFiltered(*iter_inst)) continue; // Create a BasicBlockAssembler to insert new instruction. BasicBlockAssembler bb_asm(iter_inst, &basic_block->instructions()); // Configure the assembler to copy the SourceRange information of the // current instrumented instruction into newly created instructions. This is // a hack to allow valid stack walking and better error reporting, but // breaks the 1:1 OMAP mapping and may confuse some debuggers. if (debug_friendly_) bb_asm.set_source_range(instr.source_range()); if (use_liveness_analysis_ && (info.mode == kReadAccess || info.mode == kWriteAccess)) { // Use the liveness information to skip saving the flags if possible. info.save_flags = state.AreArithmeticFlagsLive(); } // Insert hook for standard instructions. AsanHookMap::iterator hook = check_access_hooks_->find(info); if (hook == check_access_hooks_->end()) { LOG(ERROR) << "Invalid access : " << GetAsanCheckAccessFunctionName(info); return false; } // Instrument this instruction. InjectAsanHook(&bb_asm, info, operand, &hook->second, state); } DCHECK(iter_state == states.end()); return true; } bool AsanBasicBlockTransform::TransformBasicBlockSubGraph( BlockGraph* block_graph, BasicBlockSubGraph* subgraph) { DCHECK(block_graph != NULL); DCHECK(subgraph != NULL); // Perform a global liveness analysis. liveness_.Analyze(subgraph); // Determines if this subgraph uses unconventional stack pointer // manipulations. StackAccessMode stack_mode = kUnsafeStackAccess; if (!block_graph::HasUnexpectedStackFrameManipulation(subgraph)) stack_mode = kSafeStackAccess; // Iterates through each basic block and instruments it. BasicBlockSubGraph::BBCollection::iterator it = subgraph->basic_blocks().begin(); for (; it != subgraph->basic_blocks().end(); ++it) { BasicCodeBlock* bb = BasicCodeBlock::Cast(*it); if (bb != NULL && !InstrumentBasicBlock(bb, stack_mode)) return false; } return true; } const char AsanTransform::kTransformName[] = "SyzyAsanTransform"; const char AsanTransform::kAsanHookStubName[] = "asan_hook_stub"; const char AsanTransform::kSyzyAsanDll[] = "asan_rtl.dll"; AsanTransform::AsanTransform() : asan_dll_name_(kSyzyAsanDll), debug_friendly_(false), check_access_hooks_ref_() { } bool AsanTransform::PreBlockGraphIteration(BlockGraph* block_graph, BlockGraph::Block* header_block) { bool already_instrumented = false; // Ensure that this image has not already been instrumented. if (!pe::HasImportEntry(header_block, kSyzyAsanDll, &already_instrumented)) { LOG(ERROR) << "Unable to check if the image is already instrumented."; return false; } if (already_instrumented) { LOG(ERROR) << "The image is already instrumented."; return false; } AccessHookParamVector access_hook_param_vec; AsanBasicBlockTransform::AsanDefaultHookMap default_stub_map; // Create the hook stub for read/write instructions. BlockGraph::Reference read_write_hook; if (!CreateHooksStub(block_graph, kAsanHookStubName, AsanBasicBlockTransform::kReadAccess, &read_write_hook)) { return false; } // Create the hook stub for strings instructions. BlockGraph::Reference instr_hook; if (!CreateHooksStub(block_graph, kAsanHookStubName, AsanBasicBlockTransform::kInstrAccess, &instr_hook)) { return false; } // Map each memory access kind to a appropriate stub. default_stub_map[AsanBasicBlockTransform::kReadAccess] = read_write_hook; default_stub_map[AsanBasicBlockTransform::kWriteAccess] = read_write_hook; default_stub_map[AsanBasicBlockTransform::kInstrAccess] = instr_hook; default_stub_map[AsanBasicBlockTransform::kRepzAccess] = instr_hook; default_stub_map[AsanBasicBlockTransform::kRepnzAccess] = instr_hook; // Add an import entry for the ASAN runtime. ImportedModule import_module(asan_dll_name_); // Import the hooks for the read/write accesses. for (int access_size = 1; access_size <= 32; access_size *= 2) { MemoryAccessInfo read_info = { AsanBasicBlockTransform::kReadAccess, access_size, 0, true }; access_hook_param_vec.push_back(read_info); if (use_liveness_analysis()) { read_info.save_flags = false; access_hook_param_vec.push_back(read_info); } MemoryAccessInfo write_info = { AsanBasicBlockTransform::kWriteAccess, access_size, 0, true }; access_hook_param_vec.push_back(write_info); if (use_liveness_analysis()) { write_info.save_flags = false; access_hook_param_vec.push_back(write_info); } } // Import the hooks for the read/write 10-bytes accesses. MemoryAccessInfo read_info_10 = { AsanBasicBlockTransform::kReadAccess, 10, 0, true }; access_hook_param_vec.push_back(read_info_10); if (use_liveness_analysis()) { read_info_10.save_flags = false; access_hook_param_vec.push_back(read_info_10); } MemoryAccessInfo write_info_10 = { AsanBasicBlockTransform::kWriteAccess, 10, 0, true }; access_hook_param_vec.push_back(write_info_10); if (use_liveness_analysis()) { write_info_10.save_flags = false; access_hook_param_vec.push_back(write_info_10); } // Import the hooks for strings/prefix memory accesses. const _InstructionType strings[] = { I_CMPS, I_MOVS, I_STOS }; int strings_length = sizeof(strings)/sizeof(_InstructionType); for (int access_size = 1; access_size <= 4; access_size *= 2) { for (int inst = 0; inst < strings_length; ++inst) { MemoryAccessInfo repz_inst_info = { AsanBasicBlockTransform::kRepzAccess, access_size, strings[inst], true }; access_hook_param_vec.push_back(repz_inst_info); MemoryAccessInfo inst_info = { AsanBasicBlockTransform::kInstrAccess, access_size, strings[inst], true }; access_hook_param_vec.push_back(inst_info); } } if (!AddAsanCheckAccessHooks(access_hook_param_vec, default_stub_map, &import_module, &check_access_hooks_ref_, block_graph, header_block)) { return false; } return true; } bool AsanTransform::OnBlock(BlockGraph* block_graph, BlockGraph::Block* block) { DCHECK(block_graph != NULL); DCHECK(block != NULL); if (block->type() != BlockGraph::CODE_BLOCK) return true; if (!pe::CodeBlockIsBasicBlockDecomposable(block)) return true; // Use the filter that was passed to us for our child transform. AsanBasicBlockTransform transform(&check_access_hooks_ref_); transform.set_debug_friendly(debug_friendly()); transform.set_use_liveness_analysis(use_liveness_analysis()); transform.set_filter(filter()); if (!ApplyBasicBlockSubGraphTransform(&transform, block_graph, block, NULL)) return false; return true; } bool AsanTransform::PostBlockGraphIteration(BlockGraph* block_graph, BlockGraph::Block* header_block) { // This function redirects a the heap-related kernel32 imports to point to // a set of "override" imports in the ASAN runtime. static const size_t kInvalidIndex = -1; struct Kernel32ImportRedirect { const char* import_name; const char* redirect_name; }; static const Kernel32ImportRedirect kKernel32Redirects[] = { { "HeapCreate", "asan_HeapCreate" }, { "HeapDestroy", "asan_HeapDestroy" }, { "HeapAlloc", "asan_HeapAlloc" }, { "HeapReAlloc", "asan_HeapReAlloc" }, { "HeapFree", "asan_HeapFree" }, { "HeapSize", "asan_HeapSize" }, { "HeapValidate", "asan_HeapValidate" }, { "HeapCompact", "asan_HeapCompact" }, { "HeapLock", "asan_HeapLock" }, { "HeapUnlock", "asan_HeapUnlock" }, { "HeapWalk", "asan_HeapWalk" }, { "HeapSetInformation", "asan_HeapSetInformation" }, { "HeapQueryInformation", "asan_HeapQueryInformation" }, }; // Initialize the module info for querying kernel32 imports. std::vector<std::pair<size_t, size_t>> override_indexes; ImportedModule module_kernel32("kernel32.dll"); for (size_t i = 0; i < arraysize(kKernel32Redirects); ++i) { size_t kernel32_index = module_kernel32.AddSymbol(kKernel32Redirects[i].import_name, ImportedModule::kFindOnly); override_indexes.push_back(std::make_pair(kernel32_index, kInvalidIndex)); } // Query the kernel32 imports. AddImportsTransform find_kernel_imports; find_kernel_imports.AddModule(&module_kernel32); if (!find_kernel_imports.TransformBlockGraph(block_graph, header_block)) { LOG(ERROR) << "Unable to find kernel32 imports for redirection."; return false; } // Add ASAN imports for those kernel32 functions we found. These will later // be redirected. ImportedModule module_asan(asan_dll_name_); for (size_t i = 0; i < arraysize(kKernel32Redirects); ++i) { size_t kernel32_index = override_indexes[i].first; if (module_kernel32.SymbolIsImported(kernel32_index)) { size_t asan_index = module_asan.AddSymbol( kKernel32Redirects[i].redirect_name, ImportedModule::kAlwaysImport); DCHECK_EQ(kInvalidIndex, override_indexes[i].second); override_indexes[i].second = asan_index; } } // Another transform can safely be run without invalidating the results // stored in module_kernel32, as additions to the IAT will strictly be // performed at the end. AddImportsTransform add_imports_transform; add_imports_transform.AddModule(&module_asan); if (!add_imports_transform.TransformBlockGraph(block_graph, header_block)) { LOG(ERROR) << "Unable to add imports for import redirection."; return false; } // Keeps track of all the blocks referenced by the original references. BlockSet dst_blocks; // Stores the reference mapping we want to rewrite. ReferenceMap reference_redirect_map; for (size_t i = 0; i < override_indexes.size(); ++i) { // Symbols that aren't imported don't need to be redirected. size_t kernel32_index = override_indexes[i].first; size_t asan_index = override_indexes[i].second; if (!module_kernel32.SymbolIsImported(kernel32_index)) { DCHECK_EQ(kInvalidIndex, asan_index); continue; } DCHECK_NE(kInvalidIndex, asan_index); BlockGraph::Reference src; BlockGraph::Reference dst; if (!module_kernel32.GetSymbolReference(kernel32_index, &src) || !module_asan.GetSymbolReference(asan_index, &dst)) { NOTREACHED() << "Unable to get references after a successful transform."; return false; } // Add the destination block to the set of referred blocks. dst_blocks.insert(src.referenced()); reference_redirect_map.insert( std::make_pair(ReferenceDest(src.referenced(), src.offset()), ReferenceDest(dst.referenced(), dst.offset()))); } RedirectReferences(dst_blocks, reference_redirect_map); // The timestamp 1 corresponds to Thursday, 01 Jan 1970 00:00:01 GMT. Setting // the timestamp of the image import descriptor to this value allows us to // temporarily bind the library until the loader finishes loading this module. // As the value is far in the past this means that the entries in the IAT for // this module will all be replace by pointers into the actual library. static const size_t kDateInThePast = 1; // We need to bind the IAT for our module to make sure the stub is used until // the sandbox lets the loader finish patching the IAT entries. module_asan.import_descriptor()->TimeDateStamp = kDateInThePast; return true; } bool operator<(const AsanBasicBlockTransform::MemoryAccessInfo& left, const AsanBasicBlockTransform::MemoryAccessInfo& right) { if (left.mode != right.mode) return left.mode < right.mode; if (left.size != right.size) return left.size < right.size; if (left.save_flags != right.save_flags) return left.save_flags < right.save_flags; return left.opcode < right.opcode; } } // namespace transforms } // namespace instrument Avoid running liveness analysis when not activated. R=rogerm@chromium.org, sebmarchand@chromium.org BUG= Review URL: https://codereview.appspot.com/9691043 git-svn-id: db59699583a60be9a535cd09cdc9132301867226@1534 15e8cca8-e42c-11de-a347-f34a4f72eb7d // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/instrument/transforms/asan_transform.h" #include <vector> #include "base/logging.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/memory/ref_counted.h" #include "syzygy/block_graph/basic_block_assembler.h" #include "syzygy/block_graph/block_builder.h" #include "syzygy/block_graph/block_util.h" #include "syzygy/common/defs.h" #include "syzygy/pe/block_util.h" #include "syzygy/pe/pe_utils.h" #include "syzygy/pe/transforms/add_imports_transform.h" #include "third_party/distorm/files/include/mnemonics.h" #include "third_party/distorm/files/src/x86defs.h" namespace instrument { namespace transforms { namespace { using block_graph::BasicBlock; using block_graph::BasicCodeBlock; using block_graph::BasicBlockAssembler; using block_graph::BasicBlockSubGraph; using block_graph::BasicBlockReference; using block_graph::BlockBuilder; using block_graph::BlockGraph; using block_graph::Displacement; using block_graph::Immediate; using block_graph::Instruction; using block_graph::Operand; using block_graph::TypedBlock; using block_graph::Value; using block_graph::analysis::LivenessAnalysis; using core::Register; using core::RegisterCode; using pe::transforms::AddImportsTransform; // A simple struct that can be used to let us access strings using TypedBlock. struct StringStruct { const char string[1]; }; typedef AddImportsTransform::ImportedModule ImportedModule; typedef AsanBasicBlockTransform::MemoryAccessMode AsanMemoryAccessMode; typedef AsanBasicBlockTransform::AsanHookMap HookMap; typedef std::vector<AsanBasicBlockTransform::AsanHookMapEntryKey> AccessHookParamVector; typedef TypedBlock<IMAGE_IMPORT_DESCRIPTOR> ImageImportDescriptor; typedef TypedBlock<StringStruct> String; // Returns true iff opcode should be instrumented. bool ShouldInstrumentOpcode(uint16 opcode) { switch (opcode) { case I_LEA: case I_CALL: case I_JMP: return false; default: return true; } } // Computes the correct displacement, if any, for operand // number @p operand of @p instr. Displacement ComputeDisplacementForOperand(const Instruction& instr, size_t operand) { const _DInst& repr = instr.representation(); DCHECK(repr.ops[operand].type == O_SMEM || repr.ops[operand].type == O_MEM); size_t access_size_bytes = repr.ops[operand].size / 8; if (repr.dispSize == 0) return Displacement(access_size_bytes - 1); BasicBlockReference reference; if (instr.FindOperandReference(operand, &reference)) { if (reference.referred_type() == BasicBlockReference::REFERRED_TYPE_BLOCK) { return Displacement(reference.block(), reference.offset() + access_size_bytes - 1); } else { return Displacement(reference.basic_block()); } } else { return Displacement(repr.disp + access_size_bytes - 1); } } // Returns true if operand @p op is instrumentable, e.g. // if it implies a memory access. bool IsInstrumentable(const _Operand& op) { switch (op.type) { case O_SMEM: case O_MEM: return true; default: return false; } } // Returns true if opcode @p opcode is a special instruction. // Memory checks for special instructions (string instructions, instructions // with prefix, etc) are handled by calling specialized functions rather than // the standard memory checks. bool IsSpecialInstruction(uint16_t opcode) { switch (opcode) { case I_CMPS: case I_STOS: case I_MOVS: return true; default: return false; } } // Decodes the first O_MEM or O_SMEM operand of @p instr, if any to the // corresponding Operand. bool DecodeMemoryAccess(const Instruction& instr, Operand* access, AsanBasicBlockTransform::MemoryAccessInfo* info) { DCHECK(access != NULL); DCHECK(info != NULL); const _DInst& repr = instr.representation(); // Figure out which operand we're instrumenting. size_t mem_op_id = -1; if (IsInstrumentable(repr.ops[0]) && IsInstrumentable(repr.ops[1])) { // This happens with instructions like: MOVS [EDI], [ESI]. DCHECK(repr.ops[0].size == repr.ops[1].size); mem_op_id = 0; } else if (IsInstrumentable(repr.ops[0])) { // The first operand is instrumentable. mem_op_id = 0; } else if (IsInstrumentable(repr.ops[1])) { // The second operand is instrumentable. mem_op_id = 1; } else { // Neither of the first two operands is instrumentable. return false; } // Determine the size of the access. info->size = repr.ops[mem_op_id].size / 8; // Determine the kind of access (read/write/instr/repz). if (FLAG_GET_PREFIX(repr.flags) & FLAG_REPNZ) info->mode = AsanBasicBlockTransform::kRepnzAccess; else if (FLAG_GET_PREFIX(repr.flags) & FLAG_REP) info->mode = AsanBasicBlockTransform::kRepzAccess; else if (IsSpecialInstruction(instr.opcode())) info->mode = AsanBasicBlockTransform::kInstrAccess; else if ((repr.flags & FLAG_DST_WR) && mem_op_id == 0) { // The first operand is written to. info->mode = AsanBasicBlockTransform::kWriteAccess; } else { info->mode = AsanBasicBlockTransform::kReadAccess; } // Determine the opcode of this instruction (when needed). if (info->mode == AsanBasicBlockTransform::kRepnzAccess || info->mode == AsanBasicBlockTransform::kRepzAccess || info->mode == AsanBasicBlockTransform::kInstrAccess) { info->opcode = instr.opcode(); } // Determine operand of the access. if (repr.ops[mem_op_id].type == O_SMEM) { // Simple memory dereference with optional displacement. Register base_reg(RegisterCode(repr.ops[mem_op_id].index - R_EAX)); // Get the displacement for the operand. Displacement displ = ComputeDisplacementForOperand(instr, mem_op_id); *access = Operand(base_reg, displ); } else if (repr.ops[0].type == O_MEM || repr.ops[1].type == O_MEM) { // Complex memory dereference. Register index_reg(RegisterCode(repr.ops[mem_op_id].index - R_EAX)); core::ScaleFactor scale = core::kTimes1; switch (repr.scale) { case 2: scale = core::kTimes2; break; case 4: scale = core::kTimes4; break; case 8: scale = core::kTimes8; break; default: break; } // Get the displacement for the operand (if any). Displacement displ = ComputeDisplacementForOperand(instr, mem_op_id); // Compute the full operand. if (repr.base != R_NONE) { Register base_reg(RegisterCode(repr.base - R_EAX)); if (displ.size() == core::kSizeNone) { // No displacement, it's a [base + index * scale] access. *access = Operand(base_reg, index_reg, scale); } else { // This is a [base + index * scale + displ] access. *access = Operand(base_reg, index_reg, scale, displ); } } else { // No base, this is an [index * scale + displ] access. // TODO(siggi): AFAIK, there's no encoding for [index * scale] without // a displacement. If this assert fires, I'm proven wrong. DCHECK_NE(core::kSizeNone, displ.size()); *access = Operand(index_reg, scale, displ); } } else { NOTREACHED(); return false; } return true; } // Use @p bb_asm to inject a hook to @p hook to instrument the access to the // address stored in the operand @p op. void InjectAsanHook(BasicBlockAssembler* bb_asm, const AsanBasicBlockTransform::MemoryAccessInfo& info, const Operand& op, BlockGraph::Reference* hook, const LivenessAnalysis::State& state) { DCHECK(hook != NULL); // TODO(etienneb): Use liveness information to implement more efficient hook. // Determine which kind of probe to inject. if (info.mode == AsanBasicBlockTransform::kReadAccess || info.mode == AsanBasicBlockTransform::kWriteAccess) { // The standard load/store probe assume the address is in EDX. // It restore the original version of EDX and cleanup the stack. bb_asm->push(core::edx); bb_asm->lea(core::edx, op); bb_asm->call(Operand(Displacement(hook->referenced(), hook->offset()))); } else { // The special instruction probe take addresses directly in registers. // The probe doesn't have any effects on stack, registers and flags. bb_asm->call(Operand(Displacement(hook->referenced(), hook->offset()))); } } typedef std::pair<BlockGraph::Block*, BlockGraph::Offset> ReferenceDest; typedef std::map<ReferenceDest, ReferenceDest> ReferenceMap; typedef std::set<BlockGraph::Block*> BlockSet; // For every block referencing @p dst_blocks, redirects any reference "ref" in // @p redirects to @p redirects[ref]. void RedirectReferences(const BlockSet& dst_blocks, const ReferenceMap& redirects) { // For each block referenced by any source reference. BlockSet::const_iterator dst_block_it = dst_blocks.begin(); for (; dst_block_it != dst_blocks.end(); ++dst_block_it) { // Iterate over all their referrers. BlockGraph::Block* referred_block = *dst_block_it; BlockGraph::Block::ReferrerSet referrers = referred_block->referrers(); BlockGraph::Block::ReferrerSet::iterator referrer_it = referrers.begin(); for (; referrer_it != referrers.end(); ++referrer_it) { BlockGraph::Block* referrer = referrer_it->first; // Don't redirect references from PE parsed blocks. This actually ends up // redirecting the IAT entries as well in the worst case. if (referrer->attributes() & BlockGraph::PE_PARSED) continue; // And redirect any references that happen to match a source reference. BlockGraph::Block::ReferenceMap::const_iterator reference_it = referrer->references().begin(); for (; reference_it != referrer->references().end(); ++reference_it) { const BlockGraph::Reference& ref(reference_it->second); ReferenceDest dest(std::make_pair(ref.referenced(), ref.offset())); ReferenceMap::const_iterator it(redirects.find(dest)); if (it != redirects.end()) { BlockGraph::Reference new_reference(ref.type(), ref.size(), it->second.first, it->second.second, 0); referrer->SetReference(reference_it->first, new_reference); } } } } } // Get the name of an asan check access function for an @p access_mode access. // @param info The memory access information, e.g. the size on a load/store, // the instruction opcode and the kind of access. std::string GetAsanCheckAccessFunctionName( AsanBasicBlockTransform::MemoryAccessInfo info) { DCHECK(info.mode != AsanBasicBlockTransform::kNoAccess); DCHECK(info.size != 0); DCHECK(info.mode == AsanBasicBlockTransform::kReadAccess || info.mode == AsanBasicBlockTransform::kWriteAccess || info.opcode != 0); const char* rep_str = NULL; if (info.mode == AsanBasicBlockTransform::kRepzAccess) rep_str = "_repz"; else if (info.mode == AsanBasicBlockTransform::kRepnzAccess) rep_str = "_repnz"; else rep_str = ""; const char* access_mode_str = NULL; if (info.mode == AsanBasicBlockTransform::kReadAccess) access_mode_str = "read"; else if (info.mode == AsanBasicBlockTransform::kWriteAccess) access_mode_str = "write"; else access_mode_str = reinterpret_cast<char*>(GET_MNEMONIC_NAME(info.opcode)); std::string function_name = base::StringPrintf("asan_check%s_%d_byte_%s_access%s", rep_str, info.size, access_mode_str, info.save_flags ? "" : "_no_flags"); StringToLowerASCII(&function_name); return function_name.c_str(); } // Add the imports for the asan check access hooks to the block-graph. // @param hooks_param_vector A vector of hook parameter values. // @param default_stub_map Stubs for the asan check access functions. // @param import_module The module for which the import should be added. // @param check_access_hook_map The map where the reference to the imports // should be stored. // @param block_graph The block-graph to populate. // @param header_block The block containing the module's DOS header of this // block-graph. // @returns True on success, false otherwise. bool AddAsanCheckAccessHooks( const AccessHookParamVector& hook_param_vector, const AsanBasicBlockTransform::AsanDefaultHookMap& default_stub_map, ImportedModule* import_module, HookMap* check_access_hook_map, BlockGraph* block_graph, BlockGraph::Block* header_block) { DCHECK(import_module != NULL); DCHECK(check_access_hook_map != NULL); DCHECK(block_graph != NULL); DCHECK(header_block != NULL); // Add the hooks to the import module. typedef std::map<AsanBasicBlockTransform::AsanHookMapEntryKey, size_t> HooksParamsToIdxMap; HooksParamsToIdxMap hooks_params_to_idx; AccessHookParamVector::const_iterator iter_params = hook_param_vector.begin(); for (; iter_params != hook_param_vector.end(); ++iter_params) { size_t symbol_idx = import_module->AddSymbol( GetAsanCheckAccessFunctionName(*iter_params), ImportedModule::kAlwaysImport); hooks_params_to_idx[*iter_params] = symbol_idx; } DCHECK_EQ(hooks_params_to_idx.size(), hook_param_vector.size()); // Transforms the block-graph. AddImportsTransform add_imports_transform; add_imports_transform.AddModule(import_module); if (!add_imports_transform.TransformBlockGraph(block_graph, header_block)) { LOG(ERROR) << "Unable to add imports for Asan instrumentation DLL."; return false; } // Get a reference to each hook and put it in the hooks map. HooksParamsToIdxMap::iterator iter_hooks = hooks_params_to_idx.begin(); for (; iter_hooks != hooks_params_to_idx.end(); ++iter_hooks) { BlockGraph::Reference import_reference; if (!import_module->GetSymbolReference(iter_hooks->second, &import_reference)) { LOG(ERROR) << "Unable to get import reference for Asan."; return false; } HookMap& hook_map = *check_access_hook_map; hook_map[iter_hooks->first] = import_reference; // In a Chrome sandboxed process the NtMapViewOfSection function is // intercepted by the sandbox agent. This causes execution in the executable // before imports have been resolved, as the ntdll patch invokes into the // executable while resolving imports. As the Asan instrumentation directly // refers to the IAT entries we need to temporarily stub these function // until the Asan imports are resolved. To do this we need to make the IAT // entries for those functions point to a temporarily block and we need to // mark the image import descriptor for this DLL as bound. AsanBasicBlockTransform::AsanDefaultHookMap::const_iterator stub_reference = default_stub_map.find(iter_hooks->first.mode); if (stub_reference == default_stub_map.end()) { LOG(ERROR) << "Could not find the default hook for " << GetAsanCheckAccessFunctionName(iter_hooks->first) << "."; return false; } import_reference.referenced()->SetReference(import_reference.offset(), stub_reference->second); } return true; } // Create a stub for the asan_check_access functions. For load/store, the stub // consists of a small block of code that restores the value of EDX and returns // to the caller. Otherwise, the stub do return. // @param block_graph The block-graph to populate with the stub. // @param stub_name The stub's name. // @param mode The kind of memory access. // @param A pointer to the stub's block on success, NULL otherwise. // @param reference Will receive the reference to the created hook. // @returns true on success, false otherwise. bool CreateHooksStub(BlockGraph* block_graph, const base::StringPiece& stub_name, AsanBasicBlockTransform::MemoryAccessMode mode, BlockGraph::Reference* reference) { DCHECK(reference != NULL); // Find or create the section we put our thunks in. BlockGraph::Section* thunk_section = block_graph->FindOrAddSection( common::kThunkSectionName, pe::kCodeCharacteristics); if (thunk_section == NULL) { LOG(ERROR) << "Unable to find or create .thunks section."; return false; } std::string stub_name_with_id = base::StringPrintf( "%.*s%d", stub_name.length(), stub_name.data(), mode); // Create the thunk for standard "load/store" (received address in EDX). BasicBlockSubGraph bbsg; BasicBlockSubGraph::BlockDescription* block_desc = bbsg.AddBlockDescription( stub_name_with_id, BlockGraph::CODE_BLOCK, thunk_section->id(), 1, 0); BasicCodeBlock* bb = bbsg.AddBasicCodeBlock(stub_name_with_id); block_desc->basic_block_order.push_back(bb); BasicBlockAssembler assm(bb->instructions().begin(), &bb->instructions()); if (mode == AsanBasicBlockTransform::kReadAccess || mode == AsanBasicBlockTransform::kWriteAccess) { // The thunk body restores the original value of EDX and cleans the stack on // return. assm.mov(core::edx, Operand(core::esp, Displacement(4))); assm.ret(4); } else { assm.ret(); } // Condense into a block. BlockBuilder block_builder(block_graph); if (!block_builder.Merge(&bbsg)) { LOG(ERROR) << "Failed to build thunk block."; return NULL; } // Exactly one new block should have been created. DCHECK_EQ(1u, block_builder.new_blocks().size()); BlockGraph::Block* thunk = block_builder.new_blocks().front(); *reference = BlockGraph::Reference(BlockGraph::ABSOLUTE_REF, 4, thunk, 0, 0); return true; } } // namespace const char AsanBasicBlockTransform::kTransformName[] = "SyzyAsanBasicBlockTransform"; bool AsanBasicBlockTransform::InstrumentBasicBlock( BasicCodeBlock* basic_block, StackAccessMode stack_mode) { DCHECK(basic_block != NULL); // Pre-compute liveness information for each instruction. std::list<LivenessAnalysis::State> states; LivenessAnalysis::State state; liveness_.GetStateAtExitOf(basic_block, &state); BasicBlock::Instructions::reverse_iterator rev_iter_inst = basic_block->instructions().rbegin(); for (; rev_iter_inst != basic_block->instructions().rend(); ++rev_iter_inst) { const Instruction& instr = *rev_iter_inst; liveness_.PropagateBackward(instr, &state); states.push_front(state); } DCHECK_EQ(states.size(), basic_block->instructions().size()); // Process each instruction and inject a call to Asan when we find an // instrumentable memory access. BasicBlock::Instructions::iterator iter_inst = basic_block->instructions().begin(); std::list<LivenessAnalysis::State>::iterator iter_state = states.begin(); for (; iter_inst != basic_block->instructions().end(); ++iter_inst) { Operand operand(core::eax); const Instruction& instr = *iter_inst; const _DInst& repr = instr.representation(); MemoryAccessInfo info; info.mode = kNoAccess; info.size = 0; info.opcode = 0; info.save_flags = true; // Get current instruction liveness information. state = *iter_state; ++iter_state; // Insert hook for a standard instruction. if (!DecodeMemoryAccess(instr, &operand, &info)) continue; // Bail if this is not a memory access. if (info.mode == kNoAccess) continue; // A basic block reference means that can be either a computed jump, // or a load from a case table. In either case it doesn't make sense // to instrument the access. if (operand.displacement().reference().referred_type() == BasicBlockReference::REFERRED_TYPE_BASIC_BLOCK) { continue; } // A block reference means this instruction is reading or writing to // a global variable or some such. It's viable to pad and align global // variables and to red-zone the padding, but without that, there's nothing // to gain by instrumenting these accesses. if (operand.displacement().reference().referred_type() == BasicBlockReference::REFERRED_TYPE_BLOCK) { continue; } // Is this an instruction we should be instrumenting. if (!ShouldInstrumentOpcode(repr.opcode)) continue; // If there are no unconventional manipulations of the stack frame, we can // skip instrumenting stack-based memory access (based on ESP or EBP). // Conventionally, accesses through ESP/EBP are always on stack. if (stack_mode == kSafeStackAccess && (operand.base() == core::kRegisterEsp || operand.base() == core::kRegisterEbp)) { continue; } // We do not instrument memory accesses through special segments. // FS is used for thread local specifics and GS for CPU info. uint8_t segment = SEGMENT_GET(repr.segment); if (segment == R_FS || segment == R_GS) continue; // Finally, don't instrument any filtered instructions. if (IsFiltered(*iter_inst)) continue; // Create a BasicBlockAssembler to insert new instruction. BasicBlockAssembler bb_asm(iter_inst, &basic_block->instructions()); // Configure the assembler to copy the SourceRange information of the // current instrumented instruction into newly created instructions. This is // a hack to allow valid stack walking and better error reporting, but // breaks the 1:1 OMAP mapping and may confuse some debuggers. if (debug_friendly_) bb_asm.set_source_range(instr.source_range()); if (use_liveness_analysis_ && (info.mode == kReadAccess || info.mode == kWriteAccess)) { // Use the liveness information to skip saving the flags if possible. info.save_flags = state.AreArithmeticFlagsLive(); } // Insert hook for standard instructions. AsanHookMap::iterator hook = check_access_hooks_->find(info); if (hook == check_access_hooks_->end()) { LOG(ERROR) << "Invalid access : " << GetAsanCheckAccessFunctionName(info); return false; } // Instrument this instruction. InjectAsanHook(&bb_asm, info, operand, &hook->second, state); } DCHECK(iter_state == states.end()); return true; } bool AsanBasicBlockTransform::TransformBasicBlockSubGraph( BlockGraph* block_graph, BasicBlockSubGraph* subgraph) { DCHECK(block_graph != NULL); DCHECK(subgraph != NULL); // Perform a global liveness analysis. if (use_liveness_analysis_) liveness_.Analyze(subgraph); // Determines if this subgraph uses unconventional stack pointer // manipulations. StackAccessMode stack_mode = kUnsafeStackAccess; if (!block_graph::HasUnexpectedStackFrameManipulation(subgraph)) stack_mode = kSafeStackAccess; // Iterates through each basic block and instruments it. BasicBlockSubGraph::BBCollection::iterator it = subgraph->basic_blocks().begin(); for (; it != subgraph->basic_blocks().end(); ++it) { BasicCodeBlock* bb = BasicCodeBlock::Cast(*it); if (bb != NULL && !InstrumentBasicBlock(bb, stack_mode)) return false; } return true; } const char AsanTransform::kTransformName[] = "SyzyAsanTransform"; const char AsanTransform::kAsanHookStubName[] = "asan_hook_stub"; const char AsanTransform::kSyzyAsanDll[] = "asan_rtl.dll"; AsanTransform::AsanTransform() : asan_dll_name_(kSyzyAsanDll), debug_friendly_(false), check_access_hooks_ref_() { } bool AsanTransform::PreBlockGraphIteration(BlockGraph* block_graph, BlockGraph::Block* header_block) { bool already_instrumented = false; // Ensure that this image has not already been instrumented. if (!pe::HasImportEntry(header_block, kSyzyAsanDll, &already_instrumented)) { LOG(ERROR) << "Unable to check if the image is already instrumented."; return false; } if (already_instrumented) { LOG(ERROR) << "The image is already instrumented."; return false; } AccessHookParamVector access_hook_param_vec; AsanBasicBlockTransform::AsanDefaultHookMap default_stub_map; // Create the hook stub for read/write instructions. BlockGraph::Reference read_write_hook; if (!CreateHooksStub(block_graph, kAsanHookStubName, AsanBasicBlockTransform::kReadAccess, &read_write_hook)) { return false; } // Create the hook stub for strings instructions. BlockGraph::Reference instr_hook; if (!CreateHooksStub(block_graph, kAsanHookStubName, AsanBasicBlockTransform::kInstrAccess, &instr_hook)) { return false; } // Map each memory access kind to a appropriate stub. default_stub_map[AsanBasicBlockTransform::kReadAccess] = read_write_hook; default_stub_map[AsanBasicBlockTransform::kWriteAccess] = read_write_hook; default_stub_map[AsanBasicBlockTransform::kInstrAccess] = instr_hook; default_stub_map[AsanBasicBlockTransform::kRepzAccess] = instr_hook; default_stub_map[AsanBasicBlockTransform::kRepnzAccess] = instr_hook; // Add an import entry for the ASAN runtime. ImportedModule import_module(asan_dll_name_); // Import the hooks for the read/write accesses. for (int access_size = 1; access_size <= 32; access_size *= 2) { MemoryAccessInfo read_info = { AsanBasicBlockTransform::kReadAccess, access_size, 0, true }; access_hook_param_vec.push_back(read_info); if (use_liveness_analysis()) { read_info.save_flags = false; access_hook_param_vec.push_back(read_info); } MemoryAccessInfo write_info = { AsanBasicBlockTransform::kWriteAccess, access_size, 0, true }; access_hook_param_vec.push_back(write_info); if (use_liveness_analysis()) { write_info.save_flags = false; access_hook_param_vec.push_back(write_info); } } // Import the hooks for the read/write 10-bytes accesses. MemoryAccessInfo read_info_10 = { AsanBasicBlockTransform::kReadAccess, 10, 0, true }; access_hook_param_vec.push_back(read_info_10); if (use_liveness_analysis()) { read_info_10.save_flags = false; access_hook_param_vec.push_back(read_info_10); } MemoryAccessInfo write_info_10 = { AsanBasicBlockTransform::kWriteAccess, 10, 0, true }; access_hook_param_vec.push_back(write_info_10); if (use_liveness_analysis()) { write_info_10.save_flags = false; access_hook_param_vec.push_back(write_info_10); } // Import the hooks for strings/prefix memory accesses. const _InstructionType strings[] = { I_CMPS, I_MOVS, I_STOS }; int strings_length = sizeof(strings)/sizeof(_InstructionType); for (int access_size = 1; access_size <= 4; access_size *= 2) { for (int inst = 0; inst < strings_length; ++inst) { MemoryAccessInfo repz_inst_info = { AsanBasicBlockTransform::kRepzAccess, access_size, strings[inst], true }; access_hook_param_vec.push_back(repz_inst_info); MemoryAccessInfo inst_info = { AsanBasicBlockTransform::kInstrAccess, access_size, strings[inst], true }; access_hook_param_vec.push_back(inst_info); } } if (!AddAsanCheckAccessHooks(access_hook_param_vec, default_stub_map, &import_module, &check_access_hooks_ref_, block_graph, header_block)) { return false; } return true; } bool AsanTransform::OnBlock(BlockGraph* block_graph, BlockGraph::Block* block) { DCHECK(block_graph != NULL); DCHECK(block != NULL); if (block->type() != BlockGraph::CODE_BLOCK) return true; if (!pe::CodeBlockIsBasicBlockDecomposable(block)) return true; // Use the filter that was passed to us for our child transform. AsanBasicBlockTransform transform(&check_access_hooks_ref_); transform.set_debug_friendly(debug_friendly()); transform.set_use_liveness_analysis(use_liveness_analysis()); transform.set_filter(filter()); if (!ApplyBasicBlockSubGraphTransform(&transform, block_graph, block, NULL)) return false; return true; } bool AsanTransform::PostBlockGraphIteration(BlockGraph* block_graph, BlockGraph::Block* header_block) { // This function redirects a the heap-related kernel32 imports to point to // a set of "override" imports in the ASAN runtime. static const size_t kInvalidIndex = -1; struct Kernel32ImportRedirect { const char* import_name; const char* redirect_name; }; static const Kernel32ImportRedirect kKernel32Redirects[] = { { "HeapCreate", "asan_HeapCreate" }, { "HeapDestroy", "asan_HeapDestroy" }, { "HeapAlloc", "asan_HeapAlloc" }, { "HeapReAlloc", "asan_HeapReAlloc" }, { "HeapFree", "asan_HeapFree" }, { "HeapSize", "asan_HeapSize" }, { "HeapValidate", "asan_HeapValidate" }, { "HeapCompact", "asan_HeapCompact" }, { "HeapLock", "asan_HeapLock" }, { "HeapUnlock", "asan_HeapUnlock" }, { "HeapWalk", "asan_HeapWalk" }, { "HeapSetInformation", "asan_HeapSetInformation" }, { "HeapQueryInformation", "asan_HeapQueryInformation" }, }; // Initialize the module info for querying kernel32 imports. std::vector<std::pair<size_t, size_t>> override_indexes; ImportedModule module_kernel32("kernel32.dll"); for (size_t i = 0; i < arraysize(kKernel32Redirects); ++i) { size_t kernel32_index = module_kernel32.AddSymbol(kKernel32Redirects[i].import_name, ImportedModule::kFindOnly); override_indexes.push_back(std::make_pair(kernel32_index, kInvalidIndex)); } // Query the kernel32 imports. AddImportsTransform find_kernel_imports; find_kernel_imports.AddModule(&module_kernel32); if (!find_kernel_imports.TransformBlockGraph(block_graph, header_block)) { LOG(ERROR) << "Unable to find kernel32 imports for redirection."; return false; } // Add ASAN imports for those kernel32 functions we found. These will later // be redirected. ImportedModule module_asan(asan_dll_name_); for (size_t i = 0; i < arraysize(kKernel32Redirects); ++i) { size_t kernel32_index = override_indexes[i].first; if (module_kernel32.SymbolIsImported(kernel32_index)) { size_t asan_index = module_asan.AddSymbol( kKernel32Redirects[i].redirect_name, ImportedModule::kAlwaysImport); DCHECK_EQ(kInvalidIndex, override_indexes[i].second); override_indexes[i].second = asan_index; } } // Another transform can safely be run without invalidating the results // stored in module_kernel32, as additions to the IAT will strictly be // performed at the end. AddImportsTransform add_imports_transform; add_imports_transform.AddModule(&module_asan); if (!add_imports_transform.TransformBlockGraph(block_graph, header_block)) { LOG(ERROR) << "Unable to add imports for import redirection."; return false; } // Keeps track of all the blocks referenced by the original references. BlockSet dst_blocks; // Stores the reference mapping we want to rewrite. ReferenceMap reference_redirect_map; for (size_t i = 0; i < override_indexes.size(); ++i) { // Symbols that aren't imported don't need to be redirected. size_t kernel32_index = override_indexes[i].first; size_t asan_index = override_indexes[i].second; if (!module_kernel32.SymbolIsImported(kernel32_index)) { DCHECK_EQ(kInvalidIndex, asan_index); continue; } DCHECK_NE(kInvalidIndex, asan_index); BlockGraph::Reference src; BlockGraph::Reference dst; if (!module_kernel32.GetSymbolReference(kernel32_index, &src) || !module_asan.GetSymbolReference(asan_index, &dst)) { NOTREACHED() << "Unable to get references after a successful transform."; return false; } // Add the destination block to the set of referred blocks. dst_blocks.insert(src.referenced()); reference_redirect_map.insert( std::make_pair(ReferenceDest(src.referenced(), src.offset()), ReferenceDest(dst.referenced(), dst.offset()))); } RedirectReferences(dst_blocks, reference_redirect_map); // The timestamp 1 corresponds to Thursday, 01 Jan 1970 00:00:01 GMT. Setting // the timestamp of the image import descriptor to this value allows us to // temporarily bind the library until the loader finishes loading this module. // As the value is far in the past this means that the entries in the IAT for // this module will all be replace by pointers into the actual library. static const size_t kDateInThePast = 1; // We need to bind the IAT for our module to make sure the stub is used until // the sandbox lets the loader finish patching the IAT entries. module_asan.import_descriptor()->TimeDateStamp = kDateInThePast; return true; } bool operator<(const AsanBasicBlockTransform::MemoryAccessInfo& left, const AsanBasicBlockTransform::MemoryAccessInfo& right) { if (left.mode != right.mode) return left.mode < right.mode; if (left.size != right.size) return left.size < right.size; if (left.save_flags != right.save_flags) return left.save_flags < right.save_flags; return left.opcode < right.opcode; } } // namespace transforms } // namespace instrument
//---------------------------- expand_instantiations.cc ------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2007 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- expand_instantiations.cc ------------------- // This is the program that we use to generate explicit instantiations for a // variety of template arguments. It takes two kinds of input files. The first // is given as arguments on the command line and contains entries of the // following form: // -------------------- // REAL_SCALARS := { double; float; long double } // COMPLEX_SCALARS := { std::complex<double>; // std::complex<float>; // std::complex<long double> } // VECTORS := { Vector<double>; Vector<float>; Vector<long double> } // -------------------- // // The input file of this form is typically located in the common/ directory // and is generated by ./configure to contain the list of vectors etc that // make sense for the current configuration. For example, the list of VECTORS // is going to contain PETSc vectors if so configured. // // The second intput is read from the command line and consists of a sequence // of statements of the following form: // -------------------- // for (u,v:VECTORS; z:SCALARS) { f(u, z, const v &); } // -------------------- // Here, everything between {...} will be copied as many times as there are // combinations of arguments u,v in the list of substitutions given by // VECTORS. For each copy, the arguments u,v will be replaced by one of these // combinations. // Author: Wolfgang Bangerth, 2007 #include <iostream> #include <fstream> #include <map> #include <list> // a map from the keys in the expansion lists to the list itself. For // instance, the example above will lead to the entry // expansion_lists[REAL_SCALARS] = (double, float, long double) // in this map, among others std::map<std::string, std::list<std::string> > expansion_lists; /* ======================== auxiliary functions ================= */ // extract from the start of #in the part of the string that ends with one of // the characters in #delim_list. The extracted part is deleted from #in std::string get_substring_with_delim (std::string &in, const std::string &delim_list) { std::string x; while ((in.size() != 0) && (delim_list.find (in[0]) == std::string::npos)) { x += in[0]; in.erase (0, 1); } return x; } // delete all whitespace at the beginning of the given argument void skip_space (std::string &in) { while ((in.size() != 0) && ((in[0] == ' ') || (in[0] == '\t') || (in[0] == '\n'))) in.erase (0, 1); } // read the whole file specified by the stream given as argument into a string // for simpler parsing, and return it std::string read_whole_file (std::istream &in) { std::string whole_file; while (in) { std::string line; getline (in, line); if (line.find ("//") != 0) { whole_file += line; whole_file += '\n'; } } // substitute tabs by spaces, multiple // spaces by single ones for (unsigned int i=0; i<whole_file.size(); ++i) if (whole_file[i] == '\t') whole_file[i] = ' '; while (whole_file.find(" ") != std::string::npos) whole_file.replace (whole_file.find(" "), 2, " "); return whole_file; } // split a given string assumed to consist of a list of substrings delimited // by a particular character into its components std::list<std::string> split_string_list (const std::string &s, const char delimiter) { std::string tmp = s; std::list<std::string> split_list; // split the input list while (tmp.length() != 0) { std::string name; name = tmp; if (name.find(delimiter) != std::string::npos) { name.erase (name.find(delimiter), std::string::npos); tmp.erase (0, tmp.find(delimiter)+1); } else tmp = ""; while ((name.length() != 0) && (name[0] == ' ')) name.erase (0,1); while (name[name.length()-1] == ' ') name.erase (name.length()-1, 1); split_list.push_back (name); } return split_list; } // determine whether a given substring at position #pos and length #length in // the string #text is a real token, i.e. not just part of another word bool is_real_token (const std::string &text, const std::string::size_type pos, const std::string::size_type length) { static const std::string token_chars ("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "_"); if ((pos != 0) && (token_chars.find (text[pos-1]) != std::string::npos)) return false; if ((pos+length < text.size()) && (token_chars.find (text[pos+length]) != std::string::npos)) return false; return true; } // substitute all occurrences of #token in #text by #substitute std::string substitute_tokens (const std::string &text, const std::string &token, const std::string &substitute) { std::string x_text = text; std::string::size_type pos = 0; while ((pos = x_text.find(token, pos)) != std::string::npos) { if (is_real_token (x_text, pos, token.size())) { x_text.replace (pos, token.size(), substitute); pos += substitute.size(); } else ++pos; } return x_text; } /* ======================== the main functions ================= */ // read and parse the expansion lists like // REAL_SCALARS := { double; float; long double } // as specified at the top of the file and store them in // the global expansion_lists variable void read_expansion_lists (const std::string &filename) { std::ifstream in (filename.c_str()); if (! in) { std::cerr << "Instantiation list file can not be read!" << std::endl; std::exit (1); } // read the entire file into a string for // simpler processing. replace end-of-line // characters by spaces std::string whole_file = read_whole_file (in); // now process entries of the form // NAME := { class1; class2; ...}. while (whole_file.size() != 0) { const std::string name = get_substring_with_delim (whole_file, " :"); skip_space (whole_file); if (whole_file.find (":=") != 0) { std::cerr << "Invalid entry <" << name << '>' << std::endl; std::exit (1); } whole_file.erase (0, 2); skip_space (whole_file); if (whole_file.find ("{") != 0) { std::cerr << "Invalid entry <" << name << '>' << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); std::string expansion = get_substring_with_delim (whole_file, "}"); if (whole_file.find ("}") != 0) { std::cerr << "Invalid entry <" << name << '>' << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); expansion_lists[name] = split_string_list (expansion, ';'); } } // produce all combinations of substitutions of the tokens given in the // #substitutions list in #text and output it to std::cout void substitute (const std::string &text, const std::list<std::pair<std::string, std::string> > &substitutions) { // do things recursively: if the list of // substiutions has a single entry, then // process all of them. otherwise, process // the first in the list and call the // function recursively with the rest of // the substitutions if (substitutions.size() > 1) { // do the first substitution, then call // function recursively const std::string name = substitutions.front().first, pattern = substitutions.front().second; const std::list<std::pair<std::string, std::string> > rest_of_substitutions (++substitutions.begin(), substitutions.end()); for (std::list<std::string>::const_iterator expansion = expansion_lists[pattern].begin(); expansion != expansion_lists[pattern].end(); ++expansion) { std::string new_text = substitute_tokens (text, name, *expansion); substitute (new_text, rest_of_substitutions); } } else if (substitutions.size() == 1) { // do the substitutions const std::string name = substitutions.front().first, pattern = substitutions.front().second; for (std::list<std::string>::const_iterator expansion = expansion_lists[pattern].begin(); expansion != expansion_lists[pattern].end(); ++expansion) std::cout << substitute_tokens (text, name, *expansion) << std::endl; } else { std::cout << text << std::endl; } } // process the list of instantiations given in the form // -------------------- // for (u,v:VECTORS; z:SCALARS) { f(u, z, const v &); } // -------------------- void process_instantiations () { std::string whole_file = read_whole_file (std::cin); // process entries of the form // for (X:Y; A:B) { INST } while (whole_file.size() != 0) { skip_space (whole_file); if (whole_file.find ("for") != 0) { std::cerr << "Invalid instantiation list" << std::endl; std::exit (1); } whole_file.erase (0, 3); skip_space (whole_file); if (whole_file.find ("(") != 0) { std::cerr << "Invalid instantiation list" << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); const std::list<std::string> substitutions_list = split_string_list (get_substring_with_delim (whole_file, ")"), ';'); if (whole_file.find (")") != 0) { std::cerr << "Invalid instantiation list" << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); // process the header std::list<std::pair<std::string, std::string> > substitutions; for (std::list<std::string>::const_iterator s = substitutions_list.begin(); s != substitutions_list.end(); ++s) { const std::list<std::string> names_and_type = split_string_list (*s, ':'); if (names_and_type.size() != 2) { std::cerr << "Invalid instantiation header" << std::endl; std::exit (1); } const std::list<std::string> names = split_string_list (names_and_type.front(), ','); for (std::list<std::string>::const_iterator x = names.begin(); x != names.end(); ++x) substitutions.push_back (std::make_pair (*x, names_and_type.back())); } // now read the part in {...} skip_space (whole_file); if (whole_file.find ("{") != 0) { std::cerr << "Invalid substitution text" << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); const std::string text_to_substitute = get_substring_with_delim (whole_file, "}"); whole_file.erase (0,1); skip_space (whole_file); // now produce the substitutions substitute (text_to_substitute, substitutions); } } int main (int argc, char **argv) { if (argc < 2) { std::cerr << "Usage: " << std::endl << " expand_instantiations class_list_files < in_file > out_file" << std::endl; std::exit (1); } for (int i=1; i<argc; ++i) read_expansion_lists (argv[i]); process_instantiations (); } Eat all sorts of whitespace when splitting a string. git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@15567 0785d39b-7218-0410-832d-ea1e28bc413d //---------------------------- expand_instantiations.cc ------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2007 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- expand_instantiations.cc ------------------- // This is the program that we use to generate explicit instantiations for a // variety of template arguments. It takes two kinds of input files. The first // is given as arguments on the command line and contains entries of the // following form: // -------------------- // REAL_SCALARS := { double; float; long double } // COMPLEX_SCALARS := { std::complex<double>; // std::complex<float>; // std::complex<long double> } // VECTORS := { Vector<double>; Vector<float>; Vector<long double> } // -------------------- // // The input file of this form is typically located in the common/ directory // and is generated by ./configure to contain the list of vectors etc that // make sense for the current configuration. For example, the list of VECTORS // is going to contain PETSc vectors if so configured. // // The second intput is read from the command line and consists of a sequence // of statements of the following form: // -------------------- // for (u,v:VECTORS; z:SCALARS) { f(u, z, const v &); } // -------------------- // Here, everything between {...} will be copied as many times as there are // combinations of arguments u,v in the list of substitutions given by // VECTORS. For each copy, the arguments u,v will be replaced by one of these // combinations. // Author: Wolfgang Bangerth, 2007 #include <iostream> #include <fstream> #include <map> #include <list> // a map from the keys in the expansion lists to the list itself. For // instance, the example above will lead to the entry // expansion_lists[REAL_SCALARS] = (double, float, long double) // in this map, among others std::map<std::string, std::list<std::string> > expansion_lists; /* ======================== auxiliary functions ================= */ // extract from the start of #in the part of the string that ends with one of // the characters in #delim_list. The extracted part is deleted from #in std::string get_substring_with_delim (std::string &in, const std::string &delim_list) { std::string x; while ((in.size() != 0) && (delim_list.find (in[0]) == std::string::npos)) { x += in[0]; in.erase (0, 1); } return x; } // delete all whitespace at the beginning of the given argument void skip_space (std::string &in) { while ((in.size() != 0) && ((in[0] == ' ') || (in[0] == '\t') || (in[0] == '\n'))) in.erase (0, 1); } // read the whole file specified by the stream given as argument into a string // for simpler parsing, and return it std::string read_whole_file (std::istream &in) { std::string whole_file; while (in) { std::string line; getline (in, line); if (line.find ("//") != 0) { whole_file += line; whole_file += '\n'; } } // substitute tabs by spaces, multiple // spaces by single ones for (unsigned int i=0; i<whole_file.size(); ++i) if (whole_file[i] == '\t') whole_file[i] = ' '; while (whole_file.find(" ") != std::string::npos) whole_file.replace (whole_file.find(" "), 2, " "); return whole_file; } // split a given string assumed to consist of a list of substrings delimited // by a particular character into its components std::list<std::string> split_string_list (const std::string &s, const char delimiter) { std::string tmp = s; std::list<std::string> split_list; // split the input list while (tmp.length() != 0) { std::string name; name = tmp; if (name.find(delimiter) != std::string::npos) { name.erase (name.find(delimiter), std::string::npos); tmp.erase (0, tmp.find(delimiter)+1); } else tmp = ""; skip_space (name); while (name[name.length()-1] == ' ') name.erase (name.length()-1, 1); split_list.push_back (name); } return split_list; } // determine whether a given substring at position #pos and length #length in // the string #text is a real token, i.e. not just part of another word bool is_real_token (const std::string &text, const std::string::size_type pos, const std::string::size_type length) { static const std::string token_chars ("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "_"); if ((pos != 0) && (token_chars.find (text[pos-1]) != std::string::npos)) return false; if ((pos+length < text.size()) && (token_chars.find (text[pos+length]) != std::string::npos)) return false; return true; } // substitute all occurrences of #token in #text by #substitute std::string substitute_tokens (const std::string &text, const std::string &token, const std::string &substitute) { std::string x_text = text; std::string::size_type pos = 0; while ((pos = x_text.find(token, pos)) != std::string::npos) { if (is_real_token (x_text, pos, token.size())) { x_text.replace (pos, token.size(), substitute); pos += substitute.size(); } else ++pos; } return x_text; } /* ======================== the main functions ================= */ // read and parse the expansion lists like // REAL_SCALARS := { double; float; long double } // as specified at the top of the file and store them in // the global expansion_lists variable void read_expansion_lists (const std::string &filename) { std::ifstream in (filename.c_str()); if (! in) { std::cerr << "Instantiation list file can not be read!" << std::endl; std::exit (1); } // read the entire file into a string for // simpler processing. replace end-of-line // characters by spaces std::string whole_file = read_whole_file (in); // now process entries of the form // NAME := { class1; class2; ...}. while (whole_file.size() != 0) { const std::string name = get_substring_with_delim (whole_file, " :"); skip_space (whole_file); if (whole_file.find (":=") != 0) { std::cerr << "Invalid entry <" << name << '>' << std::endl; std::exit (1); } whole_file.erase (0, 2); skip_space (whole_file); if (whole_file.find ("{") != 0) { std::cerr << "Invalid entry <" << name << '>' << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); std::string expansion = get_substring_with_delim (whole_file, "}"); if (whole_file.find ("}") != 0) { std::cerr << "Invalid entry <" << name << '>' << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); expansion_lists[name] = split_string_list (expansion, ';'); } } // produce all combinations of substitutions of the tokens given in the // #substitutions list in #text and output it to std::cout void substitute (const std::string &text, const std::list<std::pair<std::string, std::string> > &substitutions) { // do things recursively: if the list of // substiutions has a single entry, then // process all of them. otherwise, process // the first in the list and call the // function recursively with the rest of // the substitutions if (substitutions.size() > 1) { // do the first substitution, then call // function recursively const std::string name = substitutions.front().first, pattern = substitutions.front().second; const std::list<std::pair<std::string, std::string> > rest_of_substitutions (++substitutions.begin(), substitutions.end()); for (std::list<std::string>::const_iterator expansion = expansion_lists[pattern].begin(); expansion != expansion_lists[pattern].end(); ++expansion) { std::string new_text = substitute_tokens (text, name, *expansion); substitute (new_text, rest_of_substitutions); } } else if (substitutions.size() == 1) { // do the substitutions const std::string name = substitutions.front().first, pattern = substitutions.front().second; for (std::list<std::string>::const_iterator expansion = expansion_lists[pattern].begin(); expansion != expansion_lists[pattern].end(); ++expansion) std::cout << substitute_tokens (text, name, *expansion) << std::endl; } else { std::cout << text << std::endl; } } // process the list of instantiations given in the form // -------------------- // for (u,v:VECTORS; z:SCALARS) { f(u, z, const v &); } // -------------------- void process_instantiations () { std::string whole_file = read_whole_file (std::cin); // process entries of the form // for (X:Y; A:B) { INST } while (whole_file.size() != 0) { skip_space (whole_file); if (whole_file.find ("for") != 0) { std::cerr << "Invalid instantiation list" << std::endl; std::exit (1); } whole_file.erase (0, 3); skip_space (whole_file); if (whole_file.find ("(") != 0) { std::cerr << "Invalid instantiation list" << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); const std::list<std::string> substitutions_list = split_string_list (get_substring_with_delim (whole_file, ")"), ';'); if (whole_file.find (")") != 0) { std::cerr << "Invalid instantiation list" << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); // process the header std::list<std::pair<std::string, std::string> > substitutions; for (std::list<std::string>::const_iterator s = substitutions_list.begin(); s != substitutions_list.end(); ++s) { const std::list<std::string> names_and_type = split_string_list (*s, ':'); if (names_and_type.size() != 2) { std::cerr << "Invalid instantiation header" << std::endl; std::exit (1); } const std::list<std::string> names = split_string_list (names_and_type.front(), ','); for (std::list<std::string>::const_iterator x = names.begin(); x != names.end(); ++x) substitutions.push_back (std::make_pair (*x, names_and_type.back())); } // now read the part in {...} skip_space (whole_file); if (whole_file.find ("{") != 0) { std::cerr << "Invalid substitution text" << std::endl; std::exit (1); } whole_file.erase (0, 1); skip_space (whole_file); const std::string text_to_substitute = get_substring_with_delim (whole_file, "}"); whole_file.erase (0,1); skip_space (whole_file); // now produce the substitutions substitute (text_to_substitute, substitutions); } } int main (int argc, char **argv) { if (argc < 2) { std::cerr << "Usage: " << std::endl << " expand_instantiations class_list_files < in_file > out_file" << std::endl; std::exit (1); } for (int i=1; i<argc; ++i) read_expansion_lists (argv[i]); process_instantiations (); }
// // Aspia Project // Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "base/desktop/screen_capturer_wrapper.h" #include "base/logging.h" #include "base/desktop/desktop_environment.h" #include "base/desktop/desktop_resizer.h" #include "base/desktop/mouse_cursor.h" #include "base/desktop/power_save_blocker.h" #include "base/ipc/shared_memory_factory.h" #if defined(OS_WIN) #include "base/desktop/screen_capturer_dxgi.h" #include "base/desktop/screen_capturer_gdi.h" #include "base/desktop/screen_capturer_mirror.h" #include "base/win/windows_version.h" #elif defined(OS_LINUX) // TODO #elif defined(OS_MAC) // TODO #else #error Platform support not implemented #endif namespace base { ScreenCapturerWrapper::ScreenCapturerWrapper(ScreenCapturer::Type preferred_type, Delegate* delegate) : preferred_type_(preferred_type), delegate_(delegate), power_save_blocker_(std::make_unique<PowerSaveBlocker>()), environment_(std::make_unique<DesktopEnvironment>()) { LOG(LS_INFO) << "Ctor"; #if defined(OS_WIN) // If the monitor is turned off, this call will turn it on. SetThreadExecutionState(ES_DISPLAY_REQUIRED); #endif // defined(OS_WIN) switchToInputDesktop(); selectCapturer(); } ScreenCapturerWrapper::~ScreenCapturerWrapper() { LOG(LS_INFO) << "Dtor"; } void ScreenCapturerWrapper::selectScreen(ScreenCapturer::ScreenId screen_id, const Size& resolution) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (screen_id == screen_capturer_->currentScreen()) { if (resolution.isEmpty()) { LOG(LS_WARNING) << "Empty resolution"; } else { if (!resizer_) { LOG(LS_WARNING) << "No desktop resizer"; } else { LOG(LS_INFO) << "Change resolution for screen " << screen_id << " to: " << resolution; resizer_->setResolution(screen_id, resolution); } } } else { LOG(LS_INFO) << "Try to select screen: " << screen_id; if (!screen_capturer_->selectScreen(screen_id)) { LOG(LS_ERROR) << "ScreenCapturer::selectScreen failed"; } else { LOG(LS_INFO) << "Screen " << screen_id << " selected"; last_screen_id_ = screen_id; } } ScreenCapturer::ScreenList screen_list; if (screen_capturer_->screenList(&screen_list)) { LOG(LS_INFO) << "Received an updated list of screens"; if (resizer_) { screen_list.resolutions = resizer_->supportedResolutions(screen_id); if (screen_list.resolutions.empty()) { LOG(LS_INFO) << "No supported resolutions"; } for (const auto& resolition : screen_list.resolutions) { LOG(LS_INFO) << "Supported resolution: " << resolition; } } else { LOG(LS_INFO) << "No desktop resizer"; } for (const auto& screen : screen_list.screens) { LOG(LS_INFO) << "Screen #" << screen.id << " (position: " << screen.position << " resolution: " << screen.resolution << " DPI: " << screen.dpi << ")"; } delegate_->onScreenListChanged(screen_list, screen_id); } else { LOG(LS_ERROR) << "ScreenCapturer::screenList failed"; } } void ScreenCapturerWrapper::captureFrame() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!screen_capturer_) { LOG(LS_ERROR) << "Screen capturer NOT initialized"; return; } switchToInputDesktop(); int count = screen_capturer_->screenCount(); if (screen_count_ != count) { LOG(LS_INFO) << "Screen count changed: " << count << " (old: " << screen_count_ << ")"; resizer_.reset(); resizer_ = DesktopResizer::create(); screen_count_ = count; selectScreen(defaultScreen(), Size()); } ScreenCapturer::Error error; const Frame* frame = screen_capturer_->captureFrame(&error); if (!frame) { switch (error) { case ScreenCapturer::Error::TEMPORARY: break; case ScreenCapturer::Error::PERMANENT: { ++permanent_error_count_; selectCapturer(); } break; default: NOTREACHED(); break; } } delegate_->onScreenCaptured(frame, screen_capturer_->captureCursor()); if (enable_cursor_position_) { Point cursor_pos = screen_capturer_->cursorPosition(); int32_t delta_x = std::abs(cursor_pos.x() - last_cursor_pos_.x()); int32_t delta_y = std::abs(cursor_pos.y() - last_cursor_pos_.y()); if (delta_x > 1 || delta_y > 1) { delegate_->onCursorPositionChanged(cursor_pos); last_cursor_pos_ = cursor_pos; } } } void ScreenCapturerWrapper::setSharedMemoryFactory(SharedMemoryFactory* shared_memory_factory) { shared_memory_factory_ = shared_memory_factory; if (screen_capturer_) screen_capturer_->setSharedMemoryFactory(shared_memory_factory); } void ScreenCapturerWrapper::enableWallpaper(bool enable) { environment_->setWallpaper(enable); } void ScreenCapturerWrapper::enableEffects(bool enable) { environment_->setEffects(enable); } void ScreenCapturerWrapper::enableFontSmoothing(bool enable) { environment_->setFontSmoothing(enable); } void ScreenCapturerWrapper::enableCursorPosition(bool enable) { enable_cursor_position_ = enable; } ScreenCapturer::ScreenId ScreenCapturerWrapper::defaultScreen() { ScreenCapturer::ScreenList screen_list; if (screen_capturer_->screenList(&screen_list)) { for (const auto& screen : screen_list.screens) { if (screen.is_primary) { LOG(LS_INFO) << "Primary screen found: " << screen.id; return screen.id; } } } LOG(LS_INFO) << "Primary screen NOT found"; return ScreenCapturer::kFullDesktopScreenId; } void ScreenCapturerWrapper::selectCapturer() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); #if defined(OS_WIN) auto try_mirror_capturer = [this]() { // Mirror screen capture is available only in Windows 7/2008 R2. if (win::windowsVersion() == base::win::VERSION_WIN7) { std::unique_ptr<ScreenCapturerMirror> capturer_mirror = std::make_unique<ScreenCapturerMirror>(); if (capturer_mirror->isSupported()) { LOG(LS_INFO) << "Using MIRROR capturer"; screen_capturer_ = std::move(capturer_mirror); } } }; static const int kMaxPermanentErrorCount = 3; if (permanent_error_count_ >= kMaxPermanentErrorCount) { // Skip other capturer types and using GDI capturer. permanent_error_count_ = 0; } else if (preferred_type_ == ScreenCapturer::Type::WIN_DXGI || preferred_type_ == ScreenCapturer::Type::DEFAULT) { if (win::windowsVersion() >= win::VERSION_WIN8) { // Desktop Duplication API is available in Windows 8+. std::unique_ptr<ScreenCapturerDxgi> capturer_dxgi = std::make_unique<ScreenCapturerDxgi>(); if (capturer_dxgi->isSupported()) { LOG(LS_INFO) << "Using DXGI capturer"; screen_capturer_ = std::move(capturer_dxgi); } } else { try_mirror_capturer(); } } else if (preferred_type_ == ScreenCapturer::Type::WIN_MIRROR) { try_mirror_capturer(); } if (!screen_capturer_) { LOG(LS_INFO) << "Using GDI capturer"; screen_capturer_ = std::make_unique<ScreenCapturerGdi>(); } #elif defined(OS_LINUX) NOTIMPLEMENTED(); #elif defined(OS_MAC) NOTIMPLEMENTED(); #else NOTIMPLEMENTED(); #endif screen_capturer_->setSharedMemoryFactory(shared_memory_factory_); if (last_screen_id_ != ScreenCapturer::kInvalidScreenId) { LOG(LS_INFO) << "Restore selected screen: " << last_screen_id_; selectScreen(last_screen_id_, Size()); } } void ScreenCapturerWrapper::switchToInputDesktop() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); #if defined(OS_WIN) // Switch to the desktop receiving user input if different from the current one. Desktop input_desktop(Desktop::inputDesktop()); if (input_desktop.isValid() && !desktop_.isSame(input_desktop)) { wchar_t desktop_name[128] = { 0 }; input_desktop.name(desktop_name, sizeof(desktop_name)); LOG(LS_INFO) << "Input desktop changed to " << desktop_name; if (screen_capturer_) screen_capturer_->reset(); // If setThreadDesktop() fails, the thread is still assigned a desktop. // So we can continue capture screen bits, just from the wrong desktop. desktop_.setThreadDesktop(std::move(input_desktop)); } #endif // defined(OS_WIN) } } // namespace base Add debug messages. // // Aspia Project // Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "base/desktop/screen_capturer_wrapper.h" #include "base/logging.h" #include "base/desktop/desktop_environment.h" #include "base/desktop/desktop_resizer.h" #include "base/desktop/mouse_cursor.h" #include "base/desktop/power_save_blocker.h" #include "base/ipc/shared_memory_factory.h" #if defined(OS_WIN) #include "base/desktop/screen_capturer_dxgi.h" #include "base/desktop/screen_capturer_gdi.h" #include "base/desktop/screen_capturer_mirror.h" #include "base/win/windows_version.h" #elif defined(OS_LINUX) // TODO #elif defined(OS_MAC) // TODO #else #error Platform support not implemented #endif namespace base { ScreenCapturerWrapper::ScreenCapturerWrapper(ScreenCapturer::Type preferred_type, Delegate* delegate) : preferred_type_(preferred_type), delegate_(delegate), power_save_blocker_(std::make_unique<PowerSaveBlocker>()), environment_(std::make_unique<DesktopEnvironment>()) { LOG(LS_INFO) << "Ctor"; #if defined(OS_WIN) // If the monitor is turned off, this call will turn it on. if (!SetThreadExecutionState(ES_DISPLAY_REQUIRED)) { PLOG(LS_WARNING) << "SetThreadExecutionState failed"; } #endif // defined(OS_WIN) switchToInputDesktop(); selectCapturer(); } ScreenCapturerWrapper::~ScreenCapturerWrapper() { LOG(LS_INFO) << "Dtor"; } void ScreenCapturerWrapper::selectScreen(ScreenCapturer::ScreenId screen_id, const Size& resolution) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (screen_id == screen_capturer_->currentScreen()) { if (resolution.isEmpty()) { LOG(LS_WARNING) << "Empty resolution"; } else { if (!resizer_) { LOG(LS_WARNING) << "No desktop resizer"; } else { LOG(LS_INFO) << "Change resolution for screen " << screen_id << " to: " << resolution; resizer_->setResolution(screen_id, resolution); } } } else { LOG(LS_INFO) << "Try to select screen: " << screen_id; if (!screen_capturer_->selectScreen(screen_id)) { LOG(LS_ERROR) << "ScreenCapturer::selectScreen failed"; } else { LOG(LS_INFO) << "Screen " << screen_id << " selected"; last_screen_id_ = screen_id; } } ScreenCapturer::ScreenList screen_list; if (screen_capturer_->screenList(&screen_list)) { LOG(LS_INFO) << "Received an updated list of screens"; if (resizer_) { screen_list.resolutions = resizer_->supportedResolutions(screen_id); if (screen_list.resolutions.empty()) { LOG(LS_INFO) << "No supported resolutions"; } for (const auto& resolition : screen_list.resolutions) { LOG(LS_INFO) << "Supported resolution: " << resolition; } } else { LOG(LS_INFO) << "No desktop resizer"; } for (const auto& screen : screen_list.screens) { LOG(LS_INFO) << "Screen #" << screen.id << " (position: " << screen.position << " resolution: " << screen.resolution << " DPI: " << screen.dpi << ")"; } delegate_->onScreenListChanged(screen_list, screen_id); } else { LOG(LS_ERROR) << "ScreenCapturer::screenList failed"; } } void ScreenCapturerWrapper::captureFrame() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!screen_capturer_) { LOG(LS_ERROR) << "Screen capturer NOT initialized"; return; } switchToInputDesktop(); int count = screen_capturer_->screenCount(); if (screen_count_ != count) { LOG(LS_INFO) << "Screen count changed: " << count << " (old: " << screen_count_ << ")"; resizer_.reset(); resizer_ = DesktopResizer::create(); screen_count_ = count; selectScreen(defaultScreen(), Size()); } ScreenCapturer::Error error; const Frame* frame = screen_capturer_->captureFrame(&error); if (!frame) { switch (error) { case ScreenCapturer::Error::TEMPORARY: break; case ScreenCapturer::Error::PERMANENT: { ++permanent_error_count_; LOG(LS_WARNING) << "Permanent error detected (" << permanent_error_count_ << ")"; selectCapturer(); } break; default: NOTREACHED(); break; } } else { permanent_error_count_ = 0; } delegate_->onScreenCaptured(frame, screen_capturer_->captureCursor()); if (enable_cursor_position_) { Point cursor_pos = screen_capturer_->cursorPosition(); int32_t delta_x = std::abs(cursor_pos.x() - last_cursor_pos_.x()); int32_t delta_y = std::abs(cursor_pos.y() - last_cursor_pos_.y()); if (delta_x > 1 || delta_y > 1) { delegate_->onCursorPositionChanged(cursor_pos); last_cursor_pos_ = cursor_pos; } } } void ScreenCapturerWrapper::setSharedMemoryFactory(SharedMemoryFactory* shared_memory_factory) { shared_memory_factory_ = shared_memory_factory; if (screen_capturer_) screen_capturer_->setSharedMemoryFactory(shared_memory_factory); } void ScreenCapturerWrapper::enableWallpaper(bool enable) { environment_->setWallpaper(enable); } void ScreenCapturerWrapper::enableEffects(bool enable) { environment_->setEffects(enable); } void ScreenCapturerWrapper::enableFontSmoothing(bool enable) { environment_->setFontSmoothing(enable); } void ScreenCapturerWrapper::enableCursorPosition(bool enable) { enable_cursor_position_ = enable; } ScreenCapturer::ScreenId ScreenCapturerWrapper::defaultScreen() { ScreenCapturer::ScreenList screen_list; if (screen_capturer_->screenList(&screen_list)) { for (const auto& screen : screen_list.screens) { if (screen.is_primary) { LOG(LS_INFO) << "Primary screen found: " << screen.id; return screen.id; } } } else { LOG(LS_WARNING) << "ScreenCapturer::screenList failed"; } LOG(LS_INFO) << "Primary screen NOT found"; return ScreenCapturer::kFullDesktopScreenId; } void ScreenCapturerWrapper::selectCapturer() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); LOG(LS_INFO) << "Selecting screen capturer. Preferred capturer: " << static_cast<int>(preferred_type_); #if defined(OS_WIN) auto try_mirror_capturer = [this]() { // Mirror screen capture is available only in Windows 7/2008 R2. if (win::windowsVersion() == base::win::VERSION_WIN7) { LOG(LS_INFO) << "Windows 7/2008R2 detected. Try to initialize MIRROR capturer"; std::unique_ptr<ScreenCapturerMirror> capturer_mirror = std::make_unique<ScreenCapturerMirror>(); if (capturer_mirror->isSupported()) { LOG(LS_INFO) << "Using MIRROR capturer"; screen_capturer_ = std::move(capturer_mirror); } else { LOG(LS_INFO) << "MIRROR capturer unavailable"; } } else { LOG(LS_INFO) << "Windows version is not equal to 7/2008R2. MIRROR capturer unavailable"; } }; static const int kMaxPermanentErrorCount = 3; if (permanent_error_count_ >= kMaxPermanentErrorCount) { // Skip other capturer types and using GDI capturer. LOG(LS_INFO) << "Number of permanent errors has been exceeded. Reset to GDI capturer"; permanent_error_count_ = 0; } else if (preferred_type_ == ScreenCapturer::Type::WIN_DXGI || preferred_type_ == ScreenCapturer::Type::DEFAULT) { if (win::windowsVersion() >= win::VERSION_WIN8) { // Desktop Duplication API is available in Windows 8+. std::unique_ptr<ScreenCapturerDxgi> capturer_dxgi = std::make_unique<ScreenCapturerDxgi>(); if (capturer_dxgi->isSupported()) { LOG(LS_INFO) << "Using DXGI capturer"; screen_capturer_ = std::move(capturer_dxgi); } } else { try_mirror_capturer(); } } else if (preferred_type_ == ScreenCapturer::Type::WIN_MIRROR) { try_mirror_capturer(); } if (!screen_capturer_) { LOG(LS_INFO) << "Using GDI capturer"; screen_capturer_ = std::make_unique<ScreenCapturerGdi>(); } #elif defined(OS_LINUX) NOTIMPLEMENTED(); #elif defined(OS_MAC) NOTIMPLEMENTED(); #else NOTIMPLEMENTED(); #endif screen_capturer_->setSharedMemoryFactory(shared_memory_factory_); if (last_screen_id_ != ScreenCapturer::kInvalidScreenId) { LOG(LS_INFO) << "Restore selected screen: " << last_screen_id_; selectScreen(last_screen_id_, Size()); } } void ScreenCapturerWrapper::switchToInputDesktop() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); #if defined(OS_WIN) // Switch to the desktop receiving user input if different from the current one. Desktop input_desktop(Desktop::inputDesktop()); if (input_desktop.isValid() && !desktop_.isSame(input_desktop)) { wchar_t desktop_name[128] = { 0 }; input_desktop.name(desktop_name, sizeof(desktop_name)); LOG(LS_INFO) << "Input desktop changed to " << desktop_name; if (screen_capturer_) screen_capturer_->reset(); // If setThreadDesktop() fails, the thread is still assigned a desktop. // So we can continue capture screen bits, just from the wrong desktop. desktop_.setThreadDesktop(std::move(input_desktop)); } #endif // defined(OS_WIN) } } // namespace base
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/contrib/tensorrt/segment/segment.h" #include <queue> #include <set> #include <unordered_map> #include <vector> #include "tensorflow/contrib/tensorrt/segment/union_find.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace tensorrt { namespace segment { using ::tensorflow::strings::StrAppend; // A simple graph representation to mirror tensorflow::Graph. This structure // helps saving memory since segmenter modifies the graph in place, preventing // the need to create a copy of the graph. It is composed of edges and nodes. // Nodes keep pointers to original TF nodes. class SimpleNode; class SimpleGraph; class SimpleEdge { public: SimpleEdge(int id, SimpleNode* src, int src_port, SimpleNode* dst, int dst_port, bool is_control = false) : id_(id), src_(src), src_port_(src_port), dst_(dst), dst_port_(dst_port), control_(is_control) {} ~SimpleEdge() {} SimpleNode* src() const { return src_; } SimpleNode* dst() const { return dst_; } int src_output() const { return src_port_; } int dst_input() const { return dst_port_; } int id() const { return id_; } bool IsControlEdge() const { return control_; } private: int id_; SimpleNode* src_; int src_port_; SimpleNode* dst_; int dst_port_; bool control_; }; class SimpleNode { public: SimpleNode(const tensorflow::Node* node, const int id); const std::vector<SimpleEdge*>& in_edges() const { return in_edges_; } const std::vector<SimpleEdge*>& out_edges() const { return out_edges_; } std::vector<SimpleNode*> in_nodes() const { std::vector<SimpleNode*> res; res.reserve(in_edges_.size()); for (const auto e : in_edges_) { if (e) res.push_back(e->src()); } return res; } std::vector<SimpleNode*> out_nodes() const { std::vector<SimpleNode*> res; res.reserve(out_edges_.size()); for (const auto e : out_edges_) { if (e) res.push_back(e->dst()); } return res; } const string& name() const { return node_->name(); } const tensorflow::Node* tf_node() const { return node_; } int id() const { return id_; } private: const tensorflow::Node* node_; std::vector<SimpleEdge*> in_edges_; std::vector<SimpleEdge*> out_edges_; int id_; friend class SimpleGraph; }; class SimpleGraph { public: explicit SimpleGraph(const tensorflow::Graph* g); ~SimpleGraph(); void AddControlEdge(SimpleNode* src, SimpleNode* dst); void AddEdge(SimpleNode* src, int out_port, SimpleNode* dst, int in_port); void RemoveEdge(const SimpleEdge*); SimpleNode* FindNodeId(int node_id) { if (node_id < 0 || node_id > static_cast<int>(nodes_.size())) { return nullptr; } return nodes_[node_id]; } int num_node_ids() const { return nodes_.size(); } const SimpleNode* source_node() const { return nodes_[tensorflow::Graph::kSourceId]; } const SimpleNode* sink_node() const { return nodes_[tensorflow::Graph::kSinkId]; } private: const tensorflow::Graph* g_; std::vector<SimpleNode*> nodes_; std::vector<SimpleEdge*> edges_; // free_edge_ids_ and free_node_ids_ contain freed indices. std::set<int> free_edge_ids_; std::set<int> free_node_ids_; }; SimpleNode::SimpleNode(const tensorflow::Node* node, const int id) : node_(node), id_(id) { if (node_) { in_edges_.reserve(node_->in_edges().size()); out_edges_.reserve(node_->out_edges().size()); } } SimpleGraph::SimpleGraph(const tensorflow::Graph* g) : g_(g) { int n_nodes = g_->num_node_ids(); nodes_.resize(n_nodes, nullptr); nodes_[g->kSourceId] = new SimpleNode(g->source_node(), g->kSourceId); nodes_[g->kSinkId] = new SimpleNode(g->sink_node(), g->kSinkId); int n_edges = g->num_edge_ids(); edges_.resize(n_edges, nullptr); for (int i = 2; i < n_nodes; i++) { const auto n = g->FindNodeId(i); if (n) { nodes_[i] = new SimpleNode(n, i); } else { free_node_ids_.insert(i); } } for (int i = 0; i < n_edges; i++) { const auto e = g->FindEdgeId(i); if (e) { const auto tfsrc = e->src(); const auto tfdst = e->dst(); bool is_control = e->IsControlEdge(); auto src = nodes_[tfsrc->id()]; auto dst = nodes_[tfdst->id()]; auto edge = new SimpleEdge(i, src, e->src_output(), dst, e->dst_input(), is_control); edges_[i] = edge; src->out_edges_.push_back(edge); dst->in_edges_.push_back(edge); } else { free_edge_ids_.insert(i); } } } void SimpleGraph::AddEdge(SimpleNode* src, int out_port, SimpleNode* dst, int in_port) { int i = edges_.size(); if (!free_edge_ids_.empty()) { auto it = free_edge_ids_.begin(); i = *it; free_edge_ids_.erase(it); } else { edges_.push_back(nullptr); } bool is_control = (out_port == tensorflow::Graph::kControlSlot); is_control |= (in_port == tensorflow::Graph::kControlSlot); auto edge = new SimpleEdge(i, src, out_port, dst, in_port, is_control); edges_[i] = edge; src->out_edges_.push_back(edge); dst->in_edges_.push_back(edge); } void SimpleGraph::AddControlEdge(SimpleNode* src, SimpleNode* dst) { AddEdge(src, tensorflow::Graph::kControlSlot, dst, tensorflow::Graph::kControlSlot); } void SimpleGraph::RemoveEdge(const SimpleEdge* edge) { auto src = edge->src(); auto dst = edge->dst(); for (auto it = src->out_edges_.begin(); it != src->out_edges_.end(); ++it) { if (*it == edge) { src->out_edges_.erase(it); break; } } for (auto it = dst->in_edges_.begin(); it != dst->in_edges_.end(); ++it) { if (*it == edge) { dst->in_edges_.erase(it); break; } } } SimpleGraph::~SimpleGraph() { for (auto x : nodes_) delete x; for (auto x : edges_) delete x; } namespace { // Copied from TF ReverseDFS, which only works for tensorflow::Graph. void StableDFS(const SimpleGraph& g, bool reverse, const std::vector<const SimpleNode*>& start, const std::function<bool(const SimpleNode*)>& enter, const std::function<bool(const SimpleNode*)>& leave) { // Stack of work to do. struct Work { const SimpleNode* node; bool leave; // Are we entering or leaving n? }; std::vector<Work> stack(start.size()); for (int i = 0; i < start.size(); ++i) { stack[i] = Work{start[i], false}; } auto get_nodes = reverse ? [](const SimpleNode* n) { return n->in_nodes(); } : [](const SimpleNode* n) { return n->out_nodes(); }; std::vector<bool> visited(g.num_node_ids(), false); while (!stack.empty()) { Work w = stack.back(); stack.pop_back(); auto n = w.node; if (w.leave) { if (leave && !leave(n)) return; continue; } if (visited[n->id()]) continue; visited[n->id()] = true; if (enter && !enter(n)) return; // Arrange to call leave(n) when all done with descendants. if (leave) stack.push_back(Work{n, true}); auto nodes = get_nodes(n); std::vector<const SimpleNode*> nodes_sorted(nodes.begin(), nodes.end()); std::sort(nodes_sorted.begin(), nodes_sorted.end(), [](const SimpleNode* lhs, const SimpleNode* rhs) { return lhs->name() < rhs->name(); }); for (const SimpleNode* node : nodes_sorted) { if (!visited[node->id()]) { stack.push_back(Work{node, false}); } } } } bool CanContractEdge(const SimpleEdge* edge, const std::unique_ptr<SimpleGraph>& graph) { const auto src = edge->src(); const auto dst = edge->dst(); // Can't contract edge if doing so would cause a cycle in the // graph. So, if there is a directed path from 'src' to 'dst', other // than 'edge' (or any other direct edge from 'src' to 'dst'), then // combining 'src' and 'dst' will cause a cycle along that path. // // In practice, to avoid modifying the graph and to take advantage // of existing graph functions, we perform an equivalent. // 1. Get all nodes incoming to 'dst', excluding 'src' // 2. Reverse DFS from those nodes // 3. If reverse DFS reaches 'src' then we have a cycle // // TODO(aaroey): there are several problems with the current approach: // 1. src->dst->src, this is not detected but it should be; // 2. src->dst->...(any node sequence that doesn't contain src)...->dst, this // is detected but it should not be. // // Note that it's fine that dst connects back to src indirectly (i.e. through // a path with length > 1 that consists of intermedia nodes other than src). // While loops is one example. // // The goal is to make sure that the trt subgraph: // 1. has no loops (i.e. is a DAG), and // 2. if there is a path in the subgraph from X to Y (X and Y are both nodes // in the subgraph), then all paths from X to Y are in the subgraph. // // To achieve this goal, the correct way seems to be: // 1. remove any direct edge from src->dst; // 2. detect if src can reach dst, if so they cannot be merged. std::vector<const SimpleNode*> dfs_start_nodes; for (const SimpleNode* node : dst->in_nodes()) { if (node != src) { dfs_start_nodes.push_back(node); } } bool has_cycle = false; StableDFS(*graph, /*reverse=*/true, dfs_start_nodes, /*enter=*/nullptr, [&has_cycle, src](const SimpleNode* n) { if (n == src) { has_cycle = true; return false; } return true; }); return !has_cycle; } } // namespace void ContractEdge(SimpleEdge* edge, SimpleGraph* graph, std::vector<const SimpleEdge*>* remove_edges) { // Transfer all inputs and outputs of 'dst' to 'src' except edges // connecting the two. auto src = edge->src(); auto dst = edge->dst(); // We can use '0' for input/output index because we don't need them // to be accurate for the way we are using the graph. std::vector<const SimpleEdge*> in_edges(dst->in_edges().begin(), dst->in_edges().end()); for (const SimpleEdge* in_edge : in_edges) { if (in_edge->IsControlEdge()) { if (in_edge->src() != src) { SimpleEdge* e = const_cast<SimpleEdge*>(in_edge); graph->AddControlEdge(e->src(), src); } } else { if (in_edge->src() != src) { SimpleEdge* e = const_cast<SimpleEdge*>(in_edge); if (e->src() == graph->source_node()) { graph->AddEdge(e->src(), e->src_output(), src, tensorflow::Graph::kControlSlot); } else { graph->AddEdge(e->src(), e->src_output(), src, 0 /* input index */); } } } } std::vector<const SimpleEdge*> out_edges(dst->out_edges().begin(), dst->out_edges().end()); for (const SimpleEdge* out_edge : out_edges) { if (out_edge->IsControlEdge()) { SimpleEdge* e = const_cast<SimpleEdge*>(out_edge); graph->AddControlEdge(src, e->dst()); } else { SimpleEdge* e = const_cast<SimpleEdge*>(out_edge); if (e->dst() == graph->sink_node()) { VLOG(1) << " edge to sink node " << src->name() << " -> " << e->dst()->name(); graph->AddEdge(src, tensorflow::Graph::kControlSlot, e->dst(), e->dst_input()); } else { graph->AddEdge(src, 0 /* output index */, e->dst(), e->dst_input()); } } } // Return the edges that must be removed to disconnect 'dst' from // the graph. We don't actually remove 'dst' since the caller holds // references to all the nodes. for (const auto& in_edge : dst->in_edges()) { remove_edges->push_back(in_edge); } for (const auto& out_edge : dst->out_edges()) { remove_edges->push_back(out_edge); } } tensorflow::Status SegmentGraph( const tensorflow::Graph* tf_graph, const std::function<Status(const tensorflow::Node*)>& candidate_fn, const std::function<bool(const tensorflow::Edge*)>& input_candidate_fn, const std::function<bool(const tensorflow::Edge*)>& output_candidate_fn, const SegmentOptions& options, SegmentNodesVector* segments) { // Steps: // 1. run the segmentation algorithm to find all the segments, which uses // candidate_fn to determine the candidates segment nodes; // 2. for each segments, remove the nodes that are inputs/outputs of the // segment but are not eligible, using input/output_candidate_fn to // determine the eligibilities; // 3. convert the segment into expected return format and return the result. // --------------------------------- Step 1 --------------------------------- auto graph = std::unique_ptr<SimpleGraph>(new SimpleGraph(tf_graph)); // Use a union-find to collect the nodes that belong to the same // segment. A node value of nullptr indicates that the node is not a candidate // for TRT. std::unordered_set<string> unsupported_ops; int num_unsupported_ops = 0; std::vector<UnionFind<SimpleNode*>> node_segments; for (int i = 0; i < graph->num_node_ids(); ++i) { SimpleNode* node = graph->FindNodeId(i); if (options.exclude_node_list.count(node->name()) != 0) { VLOG(1) << "Not a TF-TRT candidate, " << "(Op type: " << node->tf_node()->type_string() << "), " << "(Op name: " << node->name() << "), " << "(Reason: excluded by segmenter option)"; unsupported_ops.emplace(node->tf_node()->type_string()); num_unsupported_ops++; node = nullptr; } else { const Status status = candidate_fn(node->tf_node()); if (!status.ok()) { VLOG(1) << "Not a TF-TRT candidate, " << "(Op type: " << node->tf_node()->type_string() << "), " << "(Op name: " << node->name() << "), " << "(Reason: " << status << ")"; unsupported_ops.emplace(node->tf_node()->type_string()); num_unsupported_ops++; node = nullptr; } } node_segments.emplace_back(node); } string msg = "There are " + std::to_string(num_unsupported_ops) + " unsupported ops of " + std::to_string(unsupported_ops.size()) + " different types in the graph: "; for (const auto& elem: unsupported_ops) { msg += elem + ", "; } LOG(INFO) << msg << "(For more information see " << "https://docs.nvidia.com/deeplearning" << "/dgx/integrate-tf-trt/index.html#support-ops)."; // The segmentation algorithm below visits nodes in reverse topological order // and attempts to merge nodes along output edges. That means that subgraphs // grow from the output-side of the network towards the inputs. // // In general this is not guaranteed to produce a globally optimal // segmentation. For exaample, consider graph with node {A, B, C, D} and edges // {A->B, A->C, B->D, C->D), where A, B, D are trt compatible but C is not, so // in theory we can choose to contract either A, B or B, D but not both, but // here it always choose to contract B, D. // // In the future if we have a measure of how beneficial it is to include a // given node in a TRT subgraph then we can revisit this algorithm to take // advantage of that information. std::vector<const SimpleNode*> order; order.reserve(graph->num_node_ids()); StableDFS(*graph, /*reverse=*/false, {graph->source_node()}, /*enter=*/nullptr, [&order](const SimpleNode* n) { order.push_back(n); return true; }); for (const SimpleNode* node : order) { // All output nodes of 'node' have been visited... VLOG(3) << "Trying node " << node->name() << " id=" << node->id(); // 'node' must be a TRT candidate... if (node_segments[node->id()].Value() == nullptr) { VLOG(3) << "... not a TRT candidate"; continue; } // Contract output edges to combine 'node' with output // nodes. Iterate since combining two nodes may unblock other // combining. while (true) { std::set<const SimpleEdge*> contract_edges; for (const SimpleEdge* out_edge : node->out_edges()) { VLOG(3) << "... out node " << out_edge->dst()->name() << " ( " << out_edge->dst()->id() << " <- " << node->id() << " )"; if (out_edge->IsControlEdge()) { VLOG(3) << "... ... Control Edge, Skipping"; continue; } // Out node must be TRT candidate... if (node_segments[out_edge->dst()->id()].Value() == nullptr) { VLOG(3) << "... ... not a TRT candidate"; continue; } if (CanContractEdge(out_edge, graph)) { VLOG(3) << "... ... can contract"; contract_edges.insert(out_edge); } else { VLOG(3) << "... ... cannot contract, would form cycle"; } } if (contract_edges.empty()) { break; } // Contract edges and collect the adjacent nodes into the same // segment/subgraph. while (!contract_edges.empty()) { const SimpleEdge* contract_edge = *contract_edges.begin(); const SimpleNode* src = contract_edge->src(); const SimpleNode* dst = contract_edge->dst(); VLOG(3) << "Merge " << src->name() << " <- " << dst->name() << " (" << src->id() << " <- " << dst->id(); node_segments[src->id()].Merge(&node_segments[dst->id()]); // Contracting the edge leaves disconnected graph edges. // Remove these from the graph and from 'contract_edges' so we // don't visit them again. SimpleEdge* e = const_cast<SimpleEdge*>(contract_edge); std::vector<const SimpleEdge*> remove_edges; ContractEdge(e, graph.get(), &remove_edges); for (const SimpleEdge* r : remove_edges) { contract_edges.erase(r); graph->RemoveEdge(r); } } } } // Collect the segments/subgraphs. Each subgraph is represented by a // set of the names of the nodes in that subgraph. // A map from the segment identifier (currently the name of the root node of // the segment tree) to the segment nodes set. std::map<string, std::set<const tensorflow::Node*>> sg_map; // A map from the segment identifier (currently the name of the root node of // the segment tree) to the device names that the nodes in the segment are // assigned to. // // TODO(aaroey): nodes assigned to different devices should not be merged, // fix this. std::unordered_map<string, std::set<string>> device_maps; for (auto& u : node_segments) { if ((u.Value() != nullptr) && (u.ParentValue() != nullptr)) { sg_map[u.ParentValue()->name()].insert(u.Value()->tf_node()); auto tf_node = u.Value()->tf_node(); // has_assigned_device_name() is expected to return true // when called from optimization pass. However, since graph // is converted back and forth between graph and graphdef, // assigned devices demoted to requested devices. If the graph // is passed directly to this module, assigned devices will be set. if (tf_node->has_assigned_device_name()) { device_maps[u.ParentValue()->name()].insert( tf_node->assigned_device_name()); } else if (!tf_node->requested_device().empty()) { device_maps[u.ParentValue()->name()].insert( tf_node->requested_device()); } else { VLOG(1) << "Node " << tf_node->name() << " has no device assigned requested device is: " << tf_node->requested_device(); } } } // --------------------------------- Step 2 --------------------------------- // Remove ineligible input/output nodes. for (auto& itr : sg_map) { std::set<const tensorflow::Node*>& segment_nodes = itr.second; VLOG(1) << "Segment original size: " << segment_nodes.size(); while (true) { std::deque<const tensorflow::Node*> in_nodes_que, out_nodes_que; // Find an input node that is not eligible and add it to the queue. // Nodes that has no incoming edges should not be treated as "input", // as there are really no inputs to them. Similar for output nodes. for (auto node : segment_nodes) { bool added = false; for (const tensorflow::Edge* edge : node->in_edges()) { if (!edge->IsControlEdge() && !edge->src()->IsSource() && !segment_nodes.count(edge->src())) { // 'node' is an input node. if (!input_candidate_fn(edge)) { in_nodes_que.push_back(node); added = true; break; } } } if (added) continue; // Only adding the node once to either queue. for (const tensorflow::Edge* edge : node->out_edges()) { if (!edge->dst()->IsSink() && !edge->IsControlEdge() && !segment_nodes.count(edge->dst())) { // 'node' is an output node. if (!output_candidate_fn(edge)) { out_nodes_que.push_back(node); break; } } } } if (in_nodes_que.empty() && out_nodes_que.empty()) { // No more ineligible input/output nodes. break; } // Now for each ineligible node, remove all of its inputs or outputs from // the subgraph. // // It can be proven that, if the original subgraph: // 1. is a DAG, and // 2. all paths between two nodes in the subgraph are all inside the // subgraph // then after doing this operation the resulting subgraph will keep the // same properties 1 and 2. // // For simplicity we use heuristics: for input and const output nodes // remove all their inputs, and for non-const output nodes remove all // their outputs. In this way, for common cases the number of removed // nodes should be minimum. auto remove_nodes = [&segment_nodes]( bool is_input_nodes, std::deque<const tensorflow::Node*>* que) { // Run a BFS on the queue to find all the input/output nodes. std::set<const tensorflow::Node*> visited; std::set<const tensorflow::Node*> logged(que->begin(), que->end()); while (!que->empty()) { auto node = que->front(); que->pop_front(); if (!visited.insert(node).second) continue; segment_nodes.erase(node); for (auto in : (is_input_nodes || node->type_string() == "Const") ? node->in_nodes() : node->out_nodes()) { if (segment_nodes.count(in)) { que->push_back(in); if (VLOG_IS_ON(2)) { if (!logged.count(in)) { VLOG(2) << "----> Need to remove node " << in->name() << " because one of its " << (is_input_nodes ? "output" : "input") << " nodes in the graph was removed: " << node->name(); logged.insert(in); } } } } } }; remove_nodes(true, &in_nodes_que); remove_nodes(false, &out_nodes_que); } VLOG(1) << "Segment new size: " << segment_nodes.size(); } // --------------------------------- Step 3 --------------------------------- // Convert the segments into the expected return format for (const auto& itr : sg_map) { const std::set<const tensorflow::Node*>& segment_nodes = itr.second; if (VLOG_IS_ON(1)) { string s = "parent=" + itr.first + ":"; for (auto node : segment_nodes) s += " " + node->name(); VLOG(1) << "Segment " << segments->size() << ": " << s; } // Don't use small segments. if (static_cast<int>(segment_nodes.size()) < options.minimum_segment_size) { VLOG(1) << "Segment " << segments->size() << " has only " << segment_nodes.size() << " nodes, dropping"; continue; } // TODO(sami): Make segmenter placement aware once trtscopes are in place std::set<string> segment_node_names; for (auto node : itr.second) segment_node_names.insert(node->name()); const auto& dev_itr = device_maps.find(itr.first); if (dev_itr == device_maps.end() || dev_itr->second.empty()) { VLOG(1) << "No device assigned to segment " << segments->size(); segments->emplace_back(std::make_pair(segment_node_names, string())); } else if (dev_itr->second.size() > 1) { string s("Segment "); StrAppend(&s, segments->size(), " has multiple devices attached: "); for (const auto& dev : dev_itr->second) { StrAppend(&s, dev, ", "); } LOG(WARNING) << s << " choosing " << *(dev_itr->second.begin()); segments->emplace_back( std::make_pair(segment_node_names, *(dev_itr->second.begin()))); } else { segments->emplace_back( std::make_pair(segment_node_names, *(dev_itr->second.begin()))); } } if (VLOG_IS_ON(1)) { for (const auto& d : device_maps) { string s("Segment "); StrAppend(&s, ": '", d.first, "' "); for (const auto& dd : d.second) { StrAppend(&s, dd, ", "); } VLOG(1) << "Devices " << s; } } return tensorflow::Status::OK(); } } // namespace segment } // namespace tensorrt } // namespace tensorflow TFTRT: use StrCat and StrAppend in the log /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/contrib/tensorrt/segment/segment.h" #include <queue> #include <set> #include <unordered_map> #include <vector> #include "tensorflow/contrib/tensorrt/segment/union_find.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace tensorrt { namespace segment { using ::tensorflow::strings::StrAppend; using ::tensorflow::strings::StrCat; // A simple graph representation to mirror tensorflow::Graph. This structure // helps saving memory since segmenter modifies the graph in place, preventing // the need to create a copy of the graph. It is composed of edges and nodes. // Nodes keep pointers to original TF nodes. class SimpleNode; class SimpleGraph; class SimpleEdge { public: SimpleEdge(int id, SimpleNode* src, int src_port, SimpleNode* dst, int dst_port, bool is_control = false) : id_(id), src_(src), src_port_(src_port), dst_(dst), dst_port_(dst_port), control_(is_control) {} ~SimpleEdge() {} SimpleNode* src() const { return src_; } SimpleNode* dst() const { return dst_; } int src_output() const { return src_port_; } int dst_input() const { return dst_port_; } int id() const { return id_; } bool IsControlEdge() const { return control_; } private: int id_; SimpleNode* src_; int src_port_; SimpleNode* dst_; int dst_port_; bool control_; }; class SimpleNode { public: SimpleNode(const tensorflow::Node* node, const int id); const std::vector<SimpleEdge*>& in_edges() const { return in_edges_; } const std::vector<SimpleEdge*>& out_edges() const { return out_edges_; } std::vector<SimpleNode*> in_nodes() const { std::vector<SimpleNode*> res; res.reserve(in_edges_.size()); for (const auto e : in_edges_) { if (e) res.push_back(e->src()); } return res; } std::vector<SimpleNode*> out_nodes() const { std::vector<SimpleNode*> res; res.reserve(out_edges_.size()); for (const auto e : out_edges_) { if (e) res.push_back(e->dst()); } return res; } const string& name() const { return node_->name(); } const tensorflow::Node* tf_node() const { return node_; } int id() const { return id_; } private: const tensorflow::Node* node_; std::vector<SimpleEdge*> in_edges_; std::vector<SimpleEdge*> out_edges_; int id_; friend class SimpleGraph; }; class SimpleGraph { public: explicit SimpleGraph(const tensorflow::Graph* g); ~SimpleGraph(); void AddControlEdge(SimpleNode* src, SimpleNode* dst); void AddEdge(SimpleNode* src, int out_port, SimpleNode* dst, int in_port); void RemoveEdge(const SimpleEdge*); SimpleNode* FindNodeId(int node_id) { if (node_id < 0 || node_id > static_cast<int>(nodes_.size())) { return nullptr; } return nodes_[node_id]; } int num_node_ids() const { return nodes_.size(); } const SimpleNode* source_node() const { return nodes_[tensorflow::Graph::kSourceId]; } const SimpleNode* sink_node() const { return nodes_[tensorflow::Graph::kSinkId]; } private: const tensorflow::Graph* g_; std::vector<SimpleNode*> nodes_; std::vector<SimpleEdge*> edges_; // free_edge_ids_ and free_node_ids_ contain freed indices. std::set<int> free_edge_ids_; std::set<int> free_node_ids_; }; SimpleNode::SimpleNode(const tensorflow::Node* node, const int id) : node_(node), id_(id) { if (node_) { in_edges_.reserve(node_->in_edges().size()); out_edges_.reserve(node_->out_edges().size()); } } SimpleGraph::SimpleGraph(const tensorflow::Graph* g) : g_(g) { int n_nodes = g_->num_node_ids(); nodes_.resize(n_nodes, nullptr); nodes_[g->kSourceId] = new SimpleNode(g->source_node(), g->kSourceId); nodes_[g->kSinkId] = new SimpleNode(g->sink_node(), g->kSinkId); int n_edges = g->num_edge_ids(); edges_.resize(n_edges, nullptr); for (int i = 2; i < n_nodes; i++) { const auto n = g->FindNodeId(i); if (n) { nodes_[i] = new SimpleNode(n, i); } else { free_node_ids_.insert(i); } } for (int i = 0; i < n_edges; i++) { const auto e = g->FindEdgeId(i); if (e) { const auto tfsrc = e->src(); const auto tfdst = e->dst(); bool is_control = e->IsControlEdge(); auto src = nodes_[tfsrc->id()]; auto dst = nodes_[tfdst->id()]; auto edge = new SimpleEdge(i, src, e->src_output(), dst, e->dst_input(), is_control); edges_[i] = edge; src->out_edges_.push_back(edge); dst->in_edges_.push_back(edge); } else { free_edge_ids_.insert(i); } } } void SimpleGraph::AddEdge(SimpleNode* src, int out_port, SimpleNode* dst, int in_port) { int i = edges_.size(); if (!free_edge_ids_.empty()) { auto it = free_edge_ids_.begin(); i = *it; free_edge_ids_.erase(it); } else { edges_.push_back(nullptr); } bool is_control = (out_port == tensorflow::Graph::kControlSlot); is_control |= (in_port == tensorflow::Graph::kControlSlot); auto edge = new SimpleEdge(i, src, out_port, dst, in_port, is_control); edges_[i] = edge; src->out_edges_.push_back(edge); dst->in_edges_.push_back(edge); } void SimpleGraph::AddControlEdge(SimpleNode* src, SimpleNode* dst) { AddEdge(src, tensorflow::Graph::kControlSlot, dst, tensorflow::Graph::kControlSlot); } void SimpleGraph::RemoveEdge(const SimpleEdge* edge) { auto src = edge->src(); auto dst = edge->dst(); for (auto it = src->out_edges_.begin(); it != src->out_edges_.end(); ++it) { if (*it == edge) { src->out_edges_.erase(it); break; } } for (auto it = dst->in_edges_.begin(); it != dst->in_edges_.end(); ++it) { if (*it == edge) { dst->in_edges_.erase(it); break; } } } SimpleGraph::~SimpleGraph() { for (auto x : nodes_) delete x; for (auto x : edges_) delete x; } namespace { // Copied from TF ReverseDFS, which only works for tensorflow::Graph. void StableDFS(const SimpleGraph& g, bool reverse, const std::vector<const SimpleNode*>& start, const std::function<bool(const SimpleNode*)>& enter, const std::function<bool(const SimpleNode*)>& leave) { // Stack of work to do. struct Work { const SimpleNode* node; bool leave; // Are we entering or leaving n? }; std::vector<Work> stack(start.size()); for (int i = 0; i < start.size(); ++i) { stack[i] = Work{start[i], false}; } auto get_nodes = reverse ? [](const SimpleNode* n) { return n->in_nodes(); } : [](const SimpleNode* n) { return n->out_nodes(); }; std::vector<bool> visited(g.num_node_ids(), false); while (!stack.empty()) { Work w = stack.back(); stack.pop_back(); auto n = w.node; if (w.leave) { if (leave && !leave(n)) return; continue; } if (visited[n->id()]) continue; visited[n->id()] = true; if (enter && !enter(n)) return; // Arrange to call leave(n) when all done with descendants. if (leave) stack.push_back(Work{n, true}); auto nodes = get_nodes(n); std::vector<const SimpleNode*> nodes_sorted(nodes.begin(), nodes.end()); std::sort(nodes_sorted.begin(), nodes_sorted.end(), [](const SimpleNode* lhs, const SimpleNode* rhs) { return lhs->name() < rhs->name(); }); for (const SimpleNode* node : nodes_sorted) { if (!visited[node->id()]) { stack.push_back(Work{node, false}); } } } } bool CanContractEdge(const SimpleEdge* edge, const std::unique_ptr<SimpleGraph>& graph) { const auto src = edge->src(); const auto dst = edge->dst(); // Can't contract edge if doing so would cause a cycle in the // graph. So, if there is a directed path from 'src' to 'dst', other // than 'edge' (or any other direct edge from 'src' to 'dst'), then // combining 'src' and 'dst' will cause a cycle along that path. // // In practice, to avoid modifying the graph and to take advantage // of existing graph functions, we perform an equivalent. // 1. Get all nodes incoming to 'dst', excluding 'src' // 2. Reverse DFS from those nodes // 3. If reverse DFS reaches 'src' then we have a cycle // // TODO(aaroey): there are several problems with the current approach: // 1. src->dst->src, this is not detected but it should be; // 2. src->dst->...(any node sequence that doesn't contain src)...->dst, this // is detected but it should not be. // // Note that it's fine that dst connects back to src indirectly (i.e. through // a path with length > 1 that consists of intermedia nodes other than src). // While loops is one example. // // The goal is to make sure that the trt subgraph: // 1. has no loops (i.e. is a DAG), and // 2. if there is a path in the subgraph from X to Y (X and Y are both nodes // in the subgraph), then all paths from X to Y are in the subgraph. // // To achieve this goal, the correct way seems to be: // 1. remove any direct edge from src->dst; // 2. detect if src can reach dst, if so they cannot be merged. std::vector<const SimpleNode*> dfs_start_nodes; for (const SimpleNode* node : dst->in_nodes()) { if (node != src) { dfs_start_nodes.push_back(node); } } bool has_cycle = false; StableDFS(*graph, /*reverse=*/true, dfs_start_nodes, /*enter=*/nullptr, [&has_cycle, src](const SimpleNode* n) { if (n == src) { has_cycle = true; return false; } return true; }); return !has_cycle; } } // namespace void ContractEdge(SimpleEdge* edge, SimpleGraph* graph, std::vector<const SimpleEdge*>* remove_edges) { // Transfer all inputs and outputs of 'dst' to 'src' except edges // connecting the two. auto src = edge->src(); auto dst = edge->dst(); // We can use '0' for input/output index because we don't need them // to be accurate for the way we are using the graph. std::vector<const SimpleEdge*> in_edges(dst->in_edges().begin(), dst->in_edges().end()); for (const SimpleEdge* in_edge : in_edges) { if (in_edge->IsControlEdge()) { if (in_edge->src() != src) { SimpleEdge* e = const_cast<SimpleEdge*>(in_edge); graph->AddControlEdge(e->src(), src); } } else { if (in_edge->src() != src) { SimpleEdge* e = const_cast<SimpleEdge*>(in_edge); if (e->src() == graph->source_node()) { graph->AddEdge(e->src(), e->src_output(), src, tensorflow::Graph::kControlSlot); } else { graph->AddEdge(e->src(), e->src_output(), src, 0 /* input index */); } } } } std::vector<const SimpleEdge*> out_edges(dst->out_edges().begin(), dst->out_edges().end()); for (const SimpleEdge* out_edge : out_edges) { if (out_edge->IsControlEdge()) { SimpleEdge* e = const_cast<SimpleEdge*>(out_edge); graph->AddControlEdge(src, e->dst()); } else { SimpleEdge* e = const_cast<SimpleEdge*>(out_edge); if (e->dst() == graph->sink_node()) { VLOG(1) << " edge to sink node " << src->name() << " -> " << e->dst()->name(); graph->AddEdge(src, tensorflow::Graph::kControlSlot, e->dst(), e->dst_input()); } else { graph->AddEdge(src, 0 /* output index */, e->dst(), e->dst_input()); } } } // Return the edges that must be removed to disconnect 'dst' from // the graph. We don't actually remove 'dst' since the caller holds // references to all the nodes. for (const auto& in_edge : dst->in_edges()) { remove_edges->push_back(in_edge); } for (const auto& out_edge : dst->out_edges()) { remove_edges->push_back(out_edge); } } tensorflow::Status SegmentGraph( const tensorflow::Graph* tf_graph, const std::function<Status(const tensorflow::Node*)>& candidate_fn, const std::function<bool(const tensorflow::Edge*)>& input_candidate_fn, const std::function<bool(const tensorflow::Edge*)>& output_candidate_fn, const SegmentOptions& options, SegmentNodesVector* segments) { // Steps: // 1. run the segmentation algorithm to find all the segments, which uses // candidate_fn to determine the candidates segment nodes; // 2. for each segments, remove the nodes that are inputs/outputs of the // segment but are not eligible, using input/output_candidate_fn to // determine the eligibilities; // 3. convert the segment into expected return format and return the result. // --------------------------------- Step 1 --------------------------------- auto graph = std::unique_ptr<SimpleGraph>(new SimpleGraph(tf_graph)); // Use a union-find to collect the nodes that belong to the same // segment. A node value of nullptr indicates that the node is not a candidate // for TRT. std::unordered_set<string> unsupported_ops; int num_unsupported_ops = 0; std::vector<UnionFind<SimpleNode*>> node_segments; for (int i = 0; i < graph->num_node_ids(); ++i) { SimpleNode* node = graph->FindNodeId(i); if (options.exclude_node_list.count(node->name()) != 0) { VLOG(1) << "Not a TF-TRT candidate, " << "(Op type: " << node->tf_node()->type_string() << "), " << "(Op name: " << node->name() << "), " << "(Reason: excluded by segmenter option)"; unsupported_ops.emplace(node->tf_node()->type_string()); num_unsupported_ops++; node = nullptr; } else { const Status status = candidate_fn(node->tf_node()); if (!status.ok()) { VLOG(1) << "Not a TF-TRT candidate, " << "(Op type: " << node->tf_node()->type_string() << "), " << "(Op name: " << node->name() << "), " << "(Reason: " << status << ")"; unsupported_ops.emplace(node->tf_node()->type_string()); num_unsupported_ops++; node = nullptr; } } node_segments.emplace_back(node); } string msg = StrCat("There are ", num_unsupported_ops, " ops of ", unsupported_ops.size(), " different types in the graph that", " are not converted to TensorRT: "); for (const auto& elem: unsupported_ops) { StrAppend(&msg, elem, ", "); } LOG(INFO) << msg << "(For more information see " << "https://docs.nvidia.com/deeplearning" << "/dgx/integrate-tf-trt/index.html#support-ops)."; // The segmentation algorithm below visits nodes in reverse topological order // and attempts to merge nodes along output edges. That means that subgraphs // grow from the output-side of the network towards the inputs. // // In general this is not guaranteed to produce a globally optimal // segmentation. For exaample, consider graph with node {A, B, C, D} and edges // {A->B, A->C, B->D, C->D), where A, B, D are trt compatible but C is not, so // in theory we can choose to contract either A, B or B, D but not both, but // here it always choose to contract B, D. // // In the future if we have a measure of how beneficial it is to include a // given node in a TRT subgraph then we can revisit this algorithm to take // advantage of that information. std::vector<const SimpleNode*> order; order.reserve(graph->num_node_ids()); StableDFS(*graph, /*reverse=*/false, {graph->source_node()}, /*enter=*/nullptr, [&order](const SimpleNode* n) { order.push_back(n); return true; }); for (const SimpleNode* node : order) { // All output nodes of 'node' have been visited... VLOG(3) << "Trying node " << node->name() << " id=" << node->id(); // 'node' must be a TRT candidate... if (node_segments[node->id()].Value() == nullptr) { VLOG(3) << "... not a TRT candidate"; continue; } // Contract output edges to combine 'node' with output // nodes. Iterate since combining two nodes may unblock other // combining. while (true) { std::set<const SimpleEdge*> contract_edges; for (const SimpleEdge* out_edge : node->out_edges()) { VLOG(3) << "... out node " << out_edge->dst()->name() << " ( " << out_edge->dst()->id() << " <- " << node->id() << " )"; if (out_edge->IsControlEdge()) { VLOG(3) << "... ... Control Edge, Skipping"; continue; } // Out node must be TRT candidate... if (node_segments[out_edge->dst()->id()].Value() == nullptr) { VLOG(3) << "... ... not a TRT candidate"; continue; } if (CanContractEdge(out_edge, graph)) { VLOG(3) << "... ... can contract"; contract_edges.insert(out_edge); } else { VLOG(3) << "... ... cannot contract, would form cycle"; } } if (contract_edges.empty()) { break; } // Contract edges and collect the adjacent nodes into the same // segment/subgraph. while (!contract_edges.empty()) { const SimpleEdge* contract_edge = *contract_edges.begin(); const SimpleNode* src = contract_edge->src(); const SimpleNode* dst = contract_edge->dst(); VLOG(3) << "Merge " << src->name() << " <- " << dst->name() << " (" << src->id() << " <- " << dst->id(); node_segments[src->id()].Merge(&node_segments[dst->id()]); // Contracting the edge leaves disconnected graph edges. // Remove these from the graph and from 'contract_edges' so we // don't visit them again. SimpleEdge* e = const_cast<SimpleEdge*>(contract_edge); std::vector<const SimpleEdge*> remove_edges; ContractEdge(e, graph.get(), &remove_edges); for (const SimpleEdge* r : remove_edges) { contract_edges.erase(r); graph->RemoveEdge(r); } } } } // Collect the segments/subgraphs. Each subgraph is represented by a // set of the names of the nodes in that subgraph. // A map from the segment identifier (currently the name of the root node of // the segment tree) to the segment nodes set. std::map<string, std::set<const tensorflow::Node*>> sg_map; // A map from the segment identifier (currently the name of the root node of // the segment tree) to the device names that the nodes in the segment are // assigned to. // // TODO(aaroey): nodes assigned to different devices should not be merged, // fix this. std::unordered_map<string, std::set<string>> device_maps; for (auto& u : node_segments) { if ((u.Value() != nullptr) && (u.ParentValue() != nullptr)) { sg_map[u.ParentValue()->name()].insert(u.Value()->tf_node()); auto tf_node = u.Value()->tf_node(); // has_assigned_device_name() is expected to return true // when called from optimization pass. However, since graph // is converted back and forth between graph and graphdef, // assigned devices demoted to requested devices. If the graph // is passed directly to this module, assigned devices will be set. if (tf_node->has_assigned_device_name()) { device_maps[u.ParentValue()->name()].insert( tf_node->assigned_device_name()); } else if (!tf_node->requested_device().empty()) { device_maps[u.ParentValue()->name()].insert( tf_node->requested_device()); } else { VLOG(1) << "Node " << tf_node->name() << " has no device assigned requested device is: " << tf_node->requested_device(); } } } // --------------------------------- Step 2 --------------------------------- // Remove ineligible input/output nodes. for (auto& itr : sg_map) { std::set<const tensorflow::Node*>& segment_nodes = itr.second; VLOG(1) << "Segment original size: " << segment_nodes.size(); while (true) { std::deque<const tensorflow::Node*> in_nodes_que, out_nodes_que; // Find an input node that is not eligible and add it to the queue. // Nodes that has no incoming edges should not be treated as "input", // as there are really no inputs to them. Similar for output nodes. for (auto node : segment_nodes) { bool added = false; for (const tensorflow::Edge* edge : node->in_edges()) { if (!edge->IsControlEdge() && !edge->src()->IsSource() && !segment_nodes.count(edge->src())) { // 'node' is an input node. if (!input_candidate_fn(edge)) { in_nodes_que.push_back(node); added = true; break; } } } if (added) continue; // Only adding the node once to either queue. for (const tensorflow::Edge* edge : node->out_edges()) { if (!edge->dst()->IsSink() && !edge->IsControlEdge() && !segment_nodes.count(edge->dst())) { // 'node' is an output node. if (!output_candidate_fn(edge)) { out_nodes_que.push_back(node); break; } } } } if (in_nodes_que.empty() && out_nodes_que.empty()) { // No more ineligible input/output nodes. break; } // Now for each ineligible node, remove all of its inputs or outputs from // the subgraph. // // It can be proven that, if the original subgraph: // 1. is a DAG, and // 2. all paths between two nodes in the subgraph are all inside the // subgraph // then after doing this operation the resulting subgraph will keep the // same properties 1 and 2. // // For simplicity we use heuristics: for input and const output nodes // remove all their inputs, and for non-const output nodes remove all // their outputs. In this way, for common cases the number of removed // nodes should be minimum. auto remove_nodes = [&segment_nodes]( bool is_input_nodes, std::deque<const tensorflow::Node*>* que) { // Run a BFS on the queue to find all the input/output nodes. std::set<const tensorflow::Node*> visited; std::set<const tensorflow::Node*> logged(que->begin(), que->end()); while (!que->empty()) { auto node = que->front(); que->pop_front(); if (!visited.insert(node).second) continue; segment_nodes.erase(node); for (auto in : (is_input_nodes || node->type_string() == "Const") ? node->in_nodes() : node->out_nodes()) { if (segment_nodes.count(in)) { que->push_back(in); if (VLOG_IS_ON(2)) { if (!logged.count(in)) { VLOG(2) << "----> Need to remove node " << in->name() << " because one of its " << (is_input_nodes ? "output" : "input") << " nodes in the graph was removed: " << node->name(); logged.insert(in); } } } } } }; remove_nodes(true, &in_nodes_que); remove_nodes(false, &out_nodes_que); } VLOG(1) << "Segment new size: " << segment_nodes.size(); } // --------------------------------- Step 3 --------------------------------- // Convert the segments into the expected return format for (const auto& itr : sg_map) { const std::set<const tensorflow::Node*>& segment_nodes = itr.second; if (VLOG_IS_ON(1)) { string s = "parent=" + itr.first + ":"; for (auto node : segment_nodes) s += " " + node->name(); VLOG(1) << "Segment " << segments->size() << ": " << s; } // Don't use small segments. if (static_cast<int>(segment_nodes.size()) < options.minimum_segment_size) { VLOG(1) << "Segment " << segments->size() << " has only " << segment_nodes.size() << " nodes, dropping"; continue; } // TODO(sami): Make segmenter placement aware once trtscopes are in place std::set<string> segment_node_names; for (auto node : itr.second) segment_node_names.insert(node->name()); const auto& dev_itr = device_maps.find(itr.first); if (dev_itr == device_maps.end() || dev_itr->second.empty()) { VLOG(1) << "No device assigned to segment " << segments->size(); segments->emplace_back(std::make_pair(segment_node_names, string())); } else if (dev_itr->second.size() > 1) { string s("Segment "); StrAppend(&s, segments->size(), " has multiple devices attached: "); for (const auto& dev : dev_itr->second) { StrAppend(&s, dev, ", "); } LOG(WARNING) << s << " choosing " << *(dev_itr->second.begin()); segments->emplace_back( std::make_pair(segment_node_names, *(dev_itr->second.begin()))); } else { segments->emplace_back( std::make_pair(segment_node_names, *(dev_itr->second.begin()))); } } if (VLOG_IS_ON(1)) { for (const auto& d : device_maps) { string s("Segment "); StrAppend(&s, ": '", d.first, "' "); for (const auto& dd : d.second) { StrAppend(&s, dd, ", "); } VLOG(1) << "Devices " << s; } } return tensorflow::Status::OK(); } } // namespace segment } // namespace tensorrt } // namespace tensorflow
// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) //#ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS //# define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1 //#endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1 #endif // This one has to come first (includes the config.h)! #include <dune/stuff/test/main.hxx> #if HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE #include "OS2014_nonparametric_convergence_study.hh" TEST(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) { nonparametric_convergence_study(/*"nonparametric_convergence_study"*/); } TEST(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation_alternative_summation) { nonparametric_convergence_study_alternative_summation(); } TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_01_subdomain) { nonparametric_block_convergence_study("[1 1 1]"); } TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_04_subdomains) { nonparametric_block_convergence_study("[2 2 1]"); } TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_16_subdomains) { nonparametric_block_convergence_study("[4 4 1]"); } TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_64_subdomains) { nonparametric_block_convergence_study("[8 8 1]"); } #else // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE TEST(DISABLED_OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation_alternative_summation) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_01_subdomain) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_04_subdomains) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_16_subdomains) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_64_subdomains) {} #endif // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE [test...] remove dead code // This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1 #endif // This one has to come first (includes the config.h)! #include <dune/stuff/test/main.hxx> #if HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE #include "OS2014_nonparametric_convergence_study.hh" TEST(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) { nonparametric_convergence_study(/*"nonparametric_convergence_study"*/); } TEST(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation_alternative_summation) { nonparametric_convergence_study_alternative_summation(); } TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_01_subdomain) { nonparametric_block_convergence_study("[1 1 1]"); } TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_04_subdomains) { nonparametric_block_convergence_study("[2 2 1]"); } TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_16_subdomains) { nonparametric_block_convergence_study("[4 4 1]"); } TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_64_subdomains) { nonparametric_block_convergence_study("[8 8 1]"); } #else // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE TEST(DISABLED_OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation_alternative_summation) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_01_subdomain) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_04_subdomains) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_16_subdomains) {} TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_64_subdomains) {} #endif // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE
#ifndef CONTROL_H #define CONTROL_H #include "SPECTYPES.H" // guessed, some may be wrong on PSX enum input_buttons { IN_NONE = 0, // 0x00000000 IN_FORWARD = (1 << 0), // 0x00000001 IN_BACK = (1 << 1), // 0x00000002 IN_LEFT = (1 << 2), // 0x00000004 IN_RIGHT = (1 << 3), // 0x00000008 IN_JUMP = (1 << 4), // 0x00000010 IN_DRAW = (1 << 5), // Space / Triangle // 0x00000020 IN_ACTION = (1 << 6), // Ctrl / X // 0x00000040 IN_WALK = (1 << 7), // Shift / R1 // 0x00000080 IN_OPTION = (1 << 8), // 0x00000100 IN_LOOK = (1 << 9), // 0x00000200 IN_LSTEP = (1 << 10), // 0x00000400 IN_RSTEP = (1 << 11), // 0x00000800 IN_ROLL = (1 << 12), // End / O // 0x00001000 IN_PAUSE = (1 << 13), // 0x00002000 IN_FLARE = (1 << 19), // 0x00080000 IN_SELECT = (1 << 20), // 0x00100000 IN_DESELECT = (1 << 21), // 0x00200000 IN_SAVE = (1 << 22), // F5 // 0x00400000 IN_LOAD = (1 << 23), // F6 // 0x00800000 IN_DUCK = (1 << 29), // 0x20000000 IN_SPRINT = (1 << 30), // 0x40000000 IN_ALL = ~0, // 0xFFFFFFFF (-1) }; enum flipeffects { FE_ROTATE_180 = 0, FE_FLOOR_SHAKE = 1, FE_FLOOD_FX = 2, FE_LARA_BUBBLES = 3, FE_FINISH_LEVEL = 4, FE_ACTIVATE_CAMERA = 5, FE_ACTIVATE_KEY = 6, FE_RUBBLE_FX = 7, FE_SWAP_CROWBAR = 8, FE_TIMER_FIELD_FX = 10, FE_EXPLOSION_FX = 11, FE_LARA_HANDSFREE = 12, FE_SHOOT_RIGHTGUN = 16, FE_SHOOT_LEFTGUN = 17, FE_INV_ON = 21, FE_INV_OFF = 22, FE_RESET_HAIR = 26, FE_SETFOG = 28, FE_LARALOCATION = 30, FE_RESET_TEST = 31, FE_FOOTPRINT_FX = 32, FE_CLEAR_SPIDERS_PATCH = 33, FE_LARALOCATIONPAD = 45, FE_KILLACTIVEBADDIES = 46, FE_TUT_HINT_1 = 47, FE_TUT_HINT_2 = 48, FE_TUT_HINT_3 = 49, FE_TUT_HINT_4 = 50, FE_TUT_HINT_5 = 51, FE_TUT_HINT_6 = 52, FE_TUT_HINT_7 = 53, FE_TUT_HINT_8 = 54, FE_TUT_HINT_9 = 55, FE_TUT_HINT_10 = 56, FE_TUT_HINT_11 = 57, FE_TUT_HINT_12 = 58, NUM_FLIPEFFECTS }; extern int flipeffect; extern int fliptimer; extern unsigned char ShatterSounds[18][10]; extern unsigned char WeaponDelay; extern unsigned char KeyTriggerActive; extern unsigned short GlobalCounter; extern char TriggerTimer; extern int reset_flag; extern short SlowMotion; extern short SlowMoFrameCount; extern unsigned char InItemControlLoop; extern short ItemNewRoomNo; extern short SmashedMeshCount; extern char richcutfrigflag; extern int nRope; extern char GetLaraOnLOS; extern int NoInput; extern int number_los_rooms; extern long rand_1; extern int framecount; extern long rand_2; extern struct ITEM_INFO* items; extern int flip_status; #if PC_VERSION extern int flipmap[255]; extern int flip_stats[255]; #else extern int flipmap[10]; extern int flip_stats[10]; #endif extern int height_type; extern int tiltxoff; extern int tiltyoff; extern unsigned long _CutSceneTriggered1; extern unsigned long _CutSceneTriggered2; extern unsigned long FmvSceneTriggered; extern unsigned char CurrentAtmosphere; extern unsigned char IsAtmospherePlaying; extern char* OutsideRoomTable; extern short* OutsideRoomOffsets; extern short IsRoomOutsideNo; extern short FXType; extern int OnObject; extern short* trigger_index; extern char cd_flags[136]; extern unsigned char InGameCnt; extern struct RAT_STRUCT* Rats; extern struct BAT_STRUCT* Bats; extern struct SPIDER_STRUCT* Spiders; extern struct TWOGUN_INFO twogun[4]; extern int SetDebounce; extern short WB_room; extern struct ITEM_INFO* WB_item; extern unsigned char HeavyTriggered; extern struct MESH_INFO* SmashedMesh[16]; extern short SmashedMeshRoom[16]; extern struct PENDULUM CurrentPendulum; extern char LaraDrawType; extern char WeatherType; extern char RoomDrawType; extern struct PHD_VECTOR ClosestCoord; extern int ClosestItem; extern int ClosestDist; extern short XSoff1; extern short YSoff1; extern short ZSoff1; extern short XSoff2; extern short YSoff2; extern short ZSoff2; extern short los_rooms[20]; extern char globoncuttrig; extern short ItemNewRooms[256][2]; extern struct CHARDEF CharDef[106]; extern struct ROPE_STRUCT Ropes[12]; extern long ControlPhase(long nframes, int demo_mode); extern long GetRandomControl(); extern void SeedRandomControl(long seed); extern long GetRandomDraw(); extern void SeedRandomDraw(long seed); extern void AddRoomFlipItems(struct room_info* r); extern void KillMoveItems(); extern void KillMoveEffects(); extern void TestTriggers(short* data, int heavy, int HeavyFlags); extern void ClearFires(); extern void ClearDynamics(); extern int is_object_in_room(int roomnumber, int objnumber); extern void NeatAndTidyTriggerCutscene(int value, int timer); extern int CheckCutPlayed(int num); extern void SetCutNotPlayed(int num); extern void SetCutPlayed(int num); extern void InitCutPlayed(); extern void ResetGuards(); extern void InterpolateAngle(short dest, short* src, short* diff, short speed); extern int CheckGuardOnTrigger(); extern int ExplodeItemNode(struct ITEM_INFO* item, int Node, int NoXZVel, long bits); extern int GetTargetOnLOS(struct GAME_VECTOR* src, struct GAME_VECTOR* dest, int DrawTarget, int firing); extern void FireCrossBowFromLaserSight(struct GAME_VECTOR* src, struct GAME_VECTOR* target); extern void TriggerNormalCDTrack(short value, short flags, short type); extern void TriggerCDTrack(short value, short flags, short type); extern void RemoveRoomFlipItems(struct room_info* r); extern void FlipMap(int FlipNumber); extern void _TestTriggers(short* data, int heavy, int HeavyFlags); extern void RefreshCamera(short type, short* data); extern long GetWaterHeight(long x, long y, long z, short room_number); extern void AlterFloorHeight(struct ITEM_INFO* item, int height); extern short GetHeight(struct FLOOR_INFO* floor, int x, int y, int z); extern struct FLOOR_INFO* GetFloor(int x, int y, int z, short* room_number); extern short GetCeiling(struct FLOOR_INFO* floor, int x, int y, int z); extern int TriggerActive(struct ITEM_INFO* item); extern void AddRoomFlipItems(struct room_info* r); extern int IsRoomOutside(long x, long y, long z); extern short GetDoor(struct FLOOR_INFO* floor); extern int LOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target); extern int xLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target); extern int zLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target); extern int CheckNoColCeilingTriangle(struct FLOOR_INFO* floor, int x, int z); extern int CheckNoColFloorTriangle(struct FLOOR_INFO* floor, int x, int z); extern int ClipTarget(struct GAME_VECTOR* start, struct GAME_VECTOR* target, struct FLOOR_INFO* floor); #ifndef PSX_VERSION || PSXPC_VERSION///@FIXME @pc extern void GetJointAbsPosition(struct ITEM_INFO* item, struct PHD_VECTOR* pos, int joint); #endif extern void AddFire(int x, int y, int z, char size, short room_num, short on); extern int ObjectOnLOS2(struct GAME_VECTOR* start, struct GAME_VECTOR* target, struct PHD_VECTOR* a3, struct MESH_INFO** a4); extern int check_xray_machine_trigger(); extern void AnimateItem(struct ITEM_INFO* item); extern void UpdateSpiders(); #endif add additional IN_ constants for debug, step shift, directional look (PSX) and unknown 31 #ifndef CONTROL_H #define CONTROL_H #include "SPECTYPES.H" // guessed, some may be wrong on PSX enum input_buttons { IN_NONE = 0, // 0x00000000 IN_FORWARD = (1 << 0), // 0x00000001 IN_BACK = (1 << 1), // 0x00000002 IN_LEFT = (1 << 2), // 0x00000004 IN_RIGHT = (1 << 3), // 0x00000008 IN_JUMP = (1 << 4), // 0x00000010 IN_DRAW = (1 << 5), // Space / Triangle // 0x00000020 IN_ACTION = (1 << 6), // Ctrl / X // 0x00000040 IN_WALK = (1 << 7), // Shift / R1 // 0x00000080 IN_OPTION = (1 << 8), // 0x00000100 IN_LOOK = (1 << 9), // 0x00000200 IN_LSTEP = (1 << 10), // 0x00000400 IN_RSTEP = (1 << 11), // 0x00000800 IN_ROLL = (1 << 12), // End / O // 0x00001000 IN_PAUSE = (1 << 13), // 0x00002000 IN_A = (1 << 14), // 0x00004000 IN_B = (1 << 15), // 0x00008000 IN_CHEAT = (1 << 16), // 0x00010000 IN_D = (1 << 17), // 0x00020000 IN_E = (1 << 18), // 0x00040000 IN_FLARE = (1 << 19), // 0x00080000 IN_SELECT = (1 << 20), // 0x00100000 IN_DESELECT = (1 << 21), // 0x00200000 IN_SAVE = (1 << 22), // F5 // 0x00400000 IN_LOAD = (1 << 23), // F6 // 0x00800000 IN_STEPSHIFT = (1 << 24), // 0x01000000 IN_LOOKLEFT = (1 << 25), // 0x02000000 IN_LOOKRIGHT = (1 << 26), // 0x04000000 IN_LOOKFORWARD = (1 << 27), // 0x08000000 IN_LOOKBACK = (1 << 28), // 0x10000000 IN_DUCK = (1 << 29), // 0x20000000 IN_SPRINT = (1 << 30), // 0x40000000 IN_UNK31 = (1 << 31), // 0x80000000 IN_ALL = ~0, // 0xFFFFFFFF (-1) }; enum flipeffects { FE_ROTATE_180 = 0, FE_FLOOR_SHAKE = 1, FE_FLOOD_FX = 2, FE_LARA_BUBBLES = 3, FE_FINISH_LEVEL = 4, FE_ACTIVATE_CAMERA = 5, FE_ACTIVATE_KEY = 6, FE_RUBBLE_FX = 7, FE_SWAP_CROWBAR = 8, FE_TIMER_FIELD_FX = 10, FE_EXPLOSION_FX = 11, FE_LARA_HANDSFREE = 12, FE_SHOOT_RIGHTGUN = 16, FE_SHOOT_LEFTGUN = 17, FE_INV_ON = 21, FE_INV_OFF = 22, FE_RESET_HAIR = 26, FE_SETFOG = 28, FE_LARALOCATION = 30, FE_RESET_TEST = 31, FE_FOOTPRINT_FX = 32, FE_CLEAR_SPIDERS_PATCH = 33, FE_LARALOCATIONPAD = 45, FE_KILLACTIVEBADDIES = 46, FE_TUT_HINT_1 = 47, FE_TUT_HINT_2 = 48, FE_TUT_HINT_3 = 49, FE_TUT_HINT_4 = 50, FE_TUT_HINT_5 = 51, FE_TUT_HINT_6 = 52, FE_TUT_HINT_7 = 53, FE_TUT_HINT_8 = 54, FE_TUT_HINT_9 = 55, FE_TUT_HINT_10 = 56, FE_TUT_HINT_11 = 57, FE_TUT_HINT_12 = 58, NUM_FLIPEFFECTS }; extern int flipeffect; extern int fliptimer; extern unsigned char ShatterSounds[18][10]; extern unsigned char WeaponDelay; extern unsigned char KeyTriggerActive; extern unsigned short GlobalCounter; extern char TriggerTimer; extern int reset_flag; extern short SlowMotion; extern short SlowMoFrameCount; extern unsigned char InItemControlLoop; extern short ItemNewRoomNo; extern short SmashedMeshCount; extern char richcutfrigflag; extern int nRope; extern char GetLaraOnLOS; extern int NoInput; extern int number_los_rooms; extern long rand_1; extern int framecount; extern long rand_2; extern struct ITEM_INFO* items; extern int flip_status; #if PC_VERSION extern int flipmap[255]; extern int flip_stats[255]; #else extern int flipmap[10]; extern int flip_stats[10]; #endif extern int height_type; extern int tiltxoff; extern int tiltyoff; extern unsigned long _CutSceneTriggered1; extern unsigned long _CutSceneTriggered2; extern unsigned long FmvSceneTriggered; extern unsigned char CurrentAtmosphere; extern unsigned char IsAtmospherePlaying; extern char* OutsideRoomTable; extern short* OutsideRoomOffsets; extern short IsRoomOutsideNo; extern short FXType; extern int OnObject; extern short* trigger_index; extern char cd_flags[136]; extern unsigned char InGameCnt; extern struct RAT_STRUCT* Rats; extern struct BAT_STRUCT* Bats; extern struct SPIDER_STRUCT* Spiders; extern struct TWOGUN_INFO twogun[4]; extern int SetDebounce; extern short WB_room; extern struct ITEM_INFO* WB_item; extern unsigned char HeavyTriggered; extern struct MESH_INFO* SmashedMesh[16]; extern short SmashedMeshRoom[16]; extern struct PENDULUM CurrentPendulum; extern char LaraDrawType; extern char WeatherType; extern char RoomDrawType; extern struct PHD_VECTOR ClosestCoord; extern int ClosestItem; extern int ClosestDist; extern short XSoff1; extern short YSoff1; extern short ZSoff1; extern short XSoff2; extern short YSoff2; extern short ZSoff2; extern short los_rooms[20]; extern char globoncuttrig; extern short ItemNewRooms[256][2]; extern struct CHARDEF CharDef[106]; extern struct ROPE_STRUCT Ropes[12]; extern long ControlPhase(long nframes, int demo_mode); extern long GetRandomControl(); extern void SeedRandomControl(long seed); extern long GetRandomDraw(); extern void SeedRandomDraw(long seed); extern void AddRoomFlipItems(struct room_info* r); extern void KillMoveItems(); extern void KillMoveEffects(); extern void TestTriggers(short* data, int heavy, int HeavyFlags); extern void ClearFires(); extern void ClearDynamics(); extern int is_object_in_room(int roomnumber, int objnumber); extern void NeatAndTidyTriggerCutscene(int value, int timer); extern int CheckCutPlayed(int num); extern void SetCutNotPlayed(int num); extern void SetCutPlayed(int num); extern void InitCutPlayed(); extern void ResetGuards(); extern void InterpolateAngle(short dest, short* src, short* diff, short speed); extern int CheckGuardOnTrigger(); extern int ExplodeItemNode(struct ITEM_INFO* item, int Node, int NoXZVel, long bits); extern int GetTargetOnLOS(struct GAME_VECTOR* src, struct GAME_VECTOR* dest, int DrawTarget, int firing); extern void FireCrossBowFromLaserSight(struct GAME_VECTOR* src, struct GAME_VECTOR* target); extern void TriggerNormalCDTrack(short value, short flags, short type); extern void TriggerCDTrack(short value, short flags, short type); extern void RemoveRoomFlipItems(struct room_info* r); extern void FlipMap(int FlipNumber); extern void _TestTriggers(short* data, int heavy, int HeavyFlags); extern void RefreshCamera(short type, short* data); extern long GetWaterHeight(long x, long y, long z, short room_number); extern void AlterFloorHeight(struct ITEM_INFO* item, int height); extern short GetHeight(struct FLOOR_INFO* floor, int x, int y, int z); extern struct FLOOR_INFO* GetFloor(int x, int y, int z, short* room_number); extern short GetCeiling(struct FLOOR_INFO* floor, int x, int y, int z); extern int TriggerActive(struct ITEM_INFO* item); extern void AddRoomFlipItems(struct room_info* r); extern int IsRoomOutside(long x, long y, long z); extern short GetDoor(struct FLOOR_INFO* floor); extern int LOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target); extern int xLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target); extern int zLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target); extern int CheckNoColCeilingTriangle(struct FLOOR_INFO* floor, int x, int z); extern int CheckNoColFloorTriangle(struct FLOOR_INFO* floor, int x, int z); extern int ClipTarget(struct GAME_VECTOR* start, struct GAME_VECTOR* target, struct FLOOR_INFO* floor); #ifndef PSX_VERSION || PSXPC_VERSION///@FIXME @pc extern void GetJointAbsPosition(struct ITEM_INFO* item, struct PHD_VECTOR* pos, int joint); #endif extern void AddFire(int x, int y, int z, char size, short room_num, short on); extern int ObjectOnLOS2(struct GAME_VECTOR* start, struct GAME_VECTOR* target, struct PHD_VECTOR* a3, struct MESH_INFO** a4); extern int check_xray_machine_trigger(); extern void AnimateItem(struct ITEM_INFO* item); extern void UpdateSpiders(); #endif
/************************************************************************* This software allows for filtering in high-dimensional observation and state spaces, as described in M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal. Probabilistic Object Tracking using a Range Camera IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013 In a publication based on this software pleace cite the above reference. Copyright (C) 2014 Manuel Wuthrich This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *************************************************************************/ #ifndef MODELS_OBSERVERS_FEATURES_RAO_BLACKWELL_observer_HPP #define MODELS_OBSERVERS_FEATURES_RAO_BLACKWELL_observer_HPP #include <vector> #include <state_filtering/distributions/distribution.hpp> namespace distributions { template<typename ScalarType_, typename StateType_, typename ObservationType_, typename IndexType_ = size_t> class RaoBlackwellObserver: public Distribution<ScalarType_, StateType_> { public: typedef typename Distribution<ScalarType_, StateType_>::ScalarType ScalarType; typedef typename Distribution<ScalarType_, StateType_>::VectorType StateType; typedef ObservationType_ ObservationType; typedef IndexType_ IndexType; public: virtual ~RaoBlackwellObserver() {} // since we can not implicitly cast a vector globally we do it here locally template<typename Type> std::vector<ScalarType> Loglikes(const std::vector<Type>& states, std::vector<IndexType>& indices, const bool& update = false) { std::vector<const StateType*> state_pointers(states.size()); for(IndexType i = 0; i < states.size(); i++) { state_pointers[i] = &(states[i]); } return Loglikes(state_pointers, indices, update); } virtual std::vector<ScalarType> Loglikes(const std::vector<const StateType*>& states, std::vector<IndexType>& indices, const bool& update = false) = 0; virtual void Observation(const ObservationType& image, const ScalarType& delta_time) = 0; // reset the latent variables virtual void Reset() = 0; }; } #endif - Uses ::sf namespace & removed distribution namespace. - Removed ScalarType_ template parameter since it's encoded in the STate type - Omitted suffix "Type" since it does not provide any further meaning. /************************************************************************* This software allows for filtering in high-dimensional observation and state spaces, as described in M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal. Probabilistic Object Tracking using a Range Camera IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013 In a publication based on this software pleace cite the above reference. Copyright (C) 2014 Manuel Wuthrich This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *************************************************************************/ #ifndef MODELS_OBSERVERS_FEATURES_RAO_BLACKWELL_observer_HPP #define MODELS_OBSERVERS_FEATURES_RAO_BLACKWELL_observer_HPP #include <vector> #include <state_filtering/utils/traits.hpp> namespace sf { template<typename State, typename Observation_, typename Index_ = size_t> class RaoBlackwellObserver { public: typedef typename internal::VectorTraits<State>::Scalar Scalar; typedef Index_ Index; typedef Observation_ Observation; public: virtual ~RaoBlackwellObserver() {} // since we can not implicitly cast a vector globally we do it here locally virtual std::vector<Scalar> Loglikes(const std::vector<State>& states, std::vector<Index>& indices, const bool& update = false) { std::vector<const State*> state_pointers(states.size()); for(Index i = 0; i < states.size(); i++) { state_pointers[i] = &(states[i]); } return Loglikes_(state_pointers, indices, update); } /* TODO fix this overloading hack */ virtual std::vector<Scalar> Loglikes_(const std::vector<const State*>& states, std::vector<Index>& indices, const bool& update = false) = 0; virtual void SetObservation(const Observation& image, const Scalar& delta_time) = 0; // reset the latent variables virtual void Reset() = 0; }; } #endif
#include "SequentialEventDispatcher.hpp" #include <memory> #include <stdexcept> #include <unordered_map> #include <utility> #include <vector> #include "Event.hpp" #include "EventStatistics.hpp" #include "SimulationObject.hpp" #include "STLLTSFQueue.hpp" namespace warped { SequentialEventDispatcher::SequentialEventDispatcher(unsigned int max_sim_time, std::unique_ptr<EventStatistics> stats) : EventDispatcher(max_sim_time), stats_(std::move(stats)) {} void SequentialEventDispatcher::startSimulation( const std::vector<std::vector<SimulationObject*>>& objects) { if (objects.size() != 1) { throw std::runtime_error(std::string("Sequential simualtion only supports 1 partition.")); } std::unordered_map<std::string, SimulationObject*> objects_by_name; STLLTSFQueue events; unsigned int current_sim_time = 0; for (auto& ob : objects[0]) { auto new_events = ob->createInitialEvents(); stats_->record(ob->name_, current_sim_time, new_events); events.push(std::move(new_events)); objects_by_name[ob->name_] = ob; } while (current_sim_time < max_sim_time_ && !events.empty()) { auto event = events.pop(); current_sim_time = event->timestamp(); auto receiver = objects_by_name[event->receiverName()]; auto new_events = receiver->receiveEvent(*event.get()); stats_->record(event->receiverName(), current_sim_time, new_events); events.push(std::move(new_events)); } stats_->writeToFile(); } } // namespace warped Fixed typo #include "SequentialEventDispatcher.hpp" #include <memory> #include <stdexcept> #include <unordered_map> #include <utility> #include <vector> #include "Event.hpp" #include "EventStatistics.hpp" #include "SimulationObject.hpp" #include "STLLTSFQueue.hpp" namespace warped { SequentialEventDispatcher::SequentialEventDispatcher(unsigned int max_sim_time, std::unique_ptr<EventStatistics> stats) : EventDispatcher(max_sim_time), stats_(std::move(stats)) {} void SequentialEventDispatcher::startSimulation( const std::vector<std::vector<SimulationObject*>>& objects) { if (objects.size() != 1) { throw std::runtime_error(std::string("Sequential simulation only supports 1 partition.")); } std::unordered_map<std::string, SimulationObject*> objects_by_name; STLLTSFQueue events; unsigned int current_sim_time = 0; for (auto& ob : objects[0]) { auto new_events = ob->createInitialEvents(); stats_->record(ob->name_, current_sim_time, new_events); events.push(std::move(new_events)); objects_by_name[ob->name_] = ob; } while (current_sim_time < max_sim_time_ && !events.empty()) { auto event = events.pop(); current_sim_time = event->timestamp(); auto receiver = objects_by_name[event->receiverName()]; auto new_events = receiver->receiveEvent(*event.get()); stats_->record(event->receiverName(), current_sim_time, new_events); events.push(std::move(new_events)); } stats_->writeToFile(); } } // namespace warped
/* Authors: Lutong Wang and Bangqi Xu */ /* * Copyright (c) 2019, The Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <chrono> #include <fstream> #include <boost/io/ios_state.hpp> #include "frProfileTask.h" #include "dr/FlexDR.h" #include "db/infra/frTime.h" #include "dr/FlexDR_graphics.h" #include <omp.h> using namespace std; using namespace fr; FlexDR::FlexDR(frDesign* designIn, Logger* loggerIn) : design_(designIn), logger_(loggerIn) { } FlexDR::~FlexDR() { } void FlexDR::setDebug(frDebugSettings* settings, odb::dbDatabase* db) { bool on = settings->debugDR; graphics_ = on && FlexDRGraphics::guiActive() ? std::make_unique<FlexDRGraphics>(settings, design_, db, logger_) : nullptr; } int FlexDRWorker::main() { using namespace std::chrono; high_resolution_clock::time_point t0 = high_resolution_clock::now(); if (VERBOSE > 1) { frBox scaledBox; stringstream ss; ss <<endl <<"start DR worker (BOX) " <<"( " << routeBox_.left() * 1.0 / getTech()->getDBUPerUU() <<" " << routeBox_.bottom() * 1.0 / getTech()->getDBUPerUU() <<" ) ( " << routeBox_.right() * 1.0 / getTech()->getDBUPerUU() <<" " << routeBox_.top() * 1.0 / getTech()->getDBUPerUU() <<" )" <<endl; cout <<ss.str() <<flush; } init(); high_resolution_clock::time_point t1 = high_resolution_clock::now(); route(); high_resolution_clock::time_point t2 = high_resolution_clock::now(); end(); high_resolution_clock::time_point t3 = high_resolution_clock::now(); duration<double> time_span0 = duration_cast<duration<double>>(t1 - t0); duration<double> time_span1 = duration_cast<duration<double>>(t2 - t1); duration<double> time_span2 = duration_cast<duration<double>>(t3 - t2); if (VERBOSE > 1) { stringstream ss; ss <<"time (INIT/ROUTE/POST) " <<time_span0.count() <<" " <<time_span1.count() <<" " <<time_span2.count() <<" " <<endl; cout <<ss.str() <<flush; } return 0; } int FlexDRWorker::main_mt() { ProfileTask profile("DR:main_mt"); using namespace std::chrono; high_resolution_clock::time_point t0 = high_resolution_clock::now(); if (VERBOSE > 1) { frBox scaledBox; stringstream ss; ss <<endl <<"start DR worker (BOX) " <<"( " << routeBox_.left() * 1.0 / getTech()->getDBUPerUU() <<" " << routeBox_.bottom() * 1.0 / getTech()->getDBUPerUU() <<" ) ( " << routeBox_.right() * 1.0 / getTech()->getDBUPerUU() <<" " << routeBox_.top() * 1.0 / getTech()->getDBUPerUU() <<" )" <<endl; cout <<ss.str() <<flush; } if (graphics_) { graphics_->startWorker(this); } init(); high_resolution_clock::time_point t1 = high_resolution_clock::now(); if (getFixMode() != 9) { route(); } else { route_queue(); } high_resolution_clock::time_point t2 = high_resolution_clock::now(); cleanup(); high_resolution_clock::time_point t3 = high_resolution_clock::now(); duration<double> time_span0 = duration_cast<duration<double>>(t1 - t0); duration<double> time_span1 = duration_cast<duration<double>>(t2 - t1); duration<double> time_span2 = duration_cast<duration<double>>(t3 - t2); if (VERBOSE > 1) { stringstream ss; ss <<"time (INIT/ROUTE/POST) " <<time_span0.count() <<" " <<time_span1.count() <<" " <<time_span2.count() <<" " <<endl; cout <<ss.str() <<flush; } return 0; } void FlexDR::initFromTA() { bool enableOutput = false; // initialize lists for (auto &net: getDesign()->getTopBlock()->getNets()) { for (auto &guide: net->getGuides()) { for (auto &connFig: guide->getRoutes()) { if (connFig->typeId() == frcPathSeg) { unique_ptr<frShape> ps = make_unique<frPathSeg>(*(static_cast<frPathSeg*>(connFig.get()))); frPoint bp, ep; static_cast<frPathSeg*>(ps.get())->getPoints(bp, ep); if (ep.x() - bp.x() + ep.y() - bp.y() == 1) { ; // skip TA dummy segment } else { net->addShape(std::move(ps)); } } else { cout <<"Error: initFromTA unsupported shape" <<endl; } } } } if (enableOutput) { for (auto &net: getDesign()->getTopBlock()->getNets()) { cout <<"net " <<net->getName() <<" has " <<net->getShapes().size() <<" shape" <<endl; } } } void FlexDR::initGCell2BoundaryPin() { bool enableOutput = false; // initiailize size frBox dieBox; getDesign()->getTopBlock()->getBoundaryBBox(dieBox); auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto &xgp = gCellPatterns.at(0); auto &ygp = gCellPatterns.at(1); auto tmpVec = vector<map<frNet*, set<pair<frPoint, frLayerNum> >, frBlockObjectComp> >((int)ygp.getCount()); gcell2BoundaryPin_ = vector<vector<map<frNet*, set<pair<frPoint, frLayerNum> >, frBlockObjectComp> > >((int)xgp.getCount(), tmpVec); for (auto &net: getDesign()->getTopBlock()->getNets()) { auto netPtr = net.get(); for (auto &guide: net->getGuides()) { for (auto &connFig: guide->getRoutes()) { if (connFig->typeId() == frcPathSeg) { auto ps = static_cast<frPathSeg*>(connFig.get()); frLayerNum layerNum; frPoint bp, ep; ps->getPoints(bp, ep); layerNum = ps->getLayerNum(); // skip TA dummy segment if (ep.x() - bp.x() + ep.y() - bp.y() == 1 || ep.x() - bp.x() + ep.y() - bp.y() == 0) { continue; } frPoint idx1, idx2; getDesign()->getTopBlock()->getGCellIdx(bp, idx1); getDesign()->getTopBlock()->getGCellIdx(ep, idx2); // update gcell2BoundaryPin // horizontal if (bp.y() == ep.y()) { int x1 = idx1.x(); int x2 = idx2.x(); int y = idx1.y(); for (auto x = x1; x <= x2; ++x) { frBox gcellBox; getDesign()->getTopBlock()->getGCellBox(frPoint(x, y), gcellBox); frCoord leftBound = gcellBox.left(); frCoord rightBound = gcellBox.right(); bool hasLeftBound = true; bool hasRightBound = true; if (bp.x() < leftBound) { hasLeftBound = true; } else { hasLeftBound = false; } if (ep.x() >= rightBound) { hasRightBound = true; } else { hasRightBound = false; } if (hasLeftBound) { frPoint boundaryPt(leftBound, bp.y()); gcell2BoundaryPin_[x][y][netPtr].insert(make_pair(boundaryPt, layerNum)); if (enableOutput) { cout << "init left boundary pin (" << boundaryPt.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ", " << boundaryPt.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ") at (" << x <<", " <<y <<") " << getTech()->getLayer(layerNum)->getName() <<" " << string((net == nullptr) ? "null" : net->getName()) <<"\n"; } } if (hasRightBound) { frPoint boundaryPt(rightBound, ep.y()); gcell2BoundaryPin_[x][y][netPtr].insert(make_pair(boundaryPt, layerNum)); if (enableOutput) { cout << "init right boundary pin (" << boundaryPt.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ", " << boundaryPt.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ") at (" << x <<", " <<y <<") " << getTech()->getLayer(layerNum)->getName() <<" " << string((net == nullptr) ? "null" : net->getName()) <<"\n"; } } } } else if (bp.x() == ep.x()) { int x = idx1.x(); int y1 = idx1.y(); int y2 = idx2.y(); for (auto y = y1; y <= y2; ++y) { frBox gcellBox; getDesign()->getTopBlock()->getGCellBox(frPoint(x, y), gcellBox); frCoord bottomBound = gcellBox.bottom(); frCoord topBound = gcellBox.top(); bool hasBottomBound = true; bool hasTopBound = true; if (bp.y() < bottomBound) { hasBottomBound = true; } else { hasBottomBound = false; } if (ep.y() >= topBound) { hasTopBound = true; } else { hasTopBound = false; } if (hasBottomBound) { frPoint boundaryPt(bp.x(), bottomBound); gcell2BoundaryPin_[x][y][netPtr].insert(make_pair(boundaryPt, layerNum)); if (enableOutput) { cout << "init bottom boundary pin (" << boundaryPt.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ", " << boundaryPt.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ") at (" << x <<", " <<y <<") " << getTech()->getLayer(layerNum)->getName() <<" " << string((net == nullptr) ? "null" : net->getName()) <<"\n"; } } if (hasTopBound) { frPoint boundaryPt(ep.x(), topBound); gcell2BoundaryPin_[x][y][netPtr].insert(make_pair(boundaryPt, layerNum)); if (enableOutput) { cout << "init top boundary pin (" << boundaryPt.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ", " << boundaryPt.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ") at (" << x <<", " <<y <<") " << getTech()->getLayer(layerNum)->getName() <<" " << string((net == nullptr) ? "null" : net->getName()) <<"\n"; } } } } else { cout << "Error: non-orthogonal pathseg in initGCell2BoundryPin\n"; } } } } } } frCoord FlexDR::init_via2viaMinLen_minimumcut1(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isH = (getDesign()->getTech()->getLayer(lNum)->getDir() == frPrefRoutingDirEnum::frcHorzPrefRoutingDir); bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); auto length1 = viaBox1.length(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); auto length2 = viaBox2.length(); for (auto &con: getDesign()->getTech()->getLayer(lNum)->getMinimumcutConstraints()) { if ((!con->hasLength() || (con->hasLength() && length1 > con->getLength())) && width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } if (isH) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.right() - 0 + 0 - viaBox1.left(), viaBox1.right() - 0 + 0 - cutBox2.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.top() - 0 + 0 - viaBox1.bottom(), viaBox1.top() - 0 + 0 - cutBox2.bottom())); } } // check via1cut to via2metal if ((!con->hasLength() || (con->hasLength() && length2 > con->getLength())) && width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } if (isH) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.right() - 0 + 0 - viaBox2.left(), viaBox2.right() - 0 + 0 - cutBox1.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.top() - 0 + 0 - viaBox2.bottom(), viaBox2.top() - 0 + 0 - cutBox1.bottom())); } } } return sol; } bool FlexDR::init_via2viaMinLen_minimumcut2(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { return true; } // skip if same-layer via if (viaDef1 == viaDef2) { return true; } bool sol = true; bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); for (auto &con: getDesign()->getTech()->getLayer(lNum)->getMinimumcutConstraints()) { if (con->hasLength()) { continue; } // check via2cut to via1metal if (width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { // has length rule if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } sol = false; break; } // check via1cut to via2metal if (width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } sol = false; break; } } return sol; } frCoord FlexDR::init_via2viaMinLen_minSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { //cout <<"hehehehehe" <<endl; return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isH = (getDesign()->getTech()->getLayer(lNum)->getDir() == frPrefRoutingDirEnum::frcHorzPrefRoutingDir); frCoord defaultWidth = getDesign()->getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef1); frBox viaBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isH ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isH ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frVia via2(viaDef2); frBox viaBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } auto width2 = viaBox2.width(); bool isVia2Fat = isH ? (viaBox2.top() - viaBox2.bottom() > defaultWidth) : (viaBox2.right() - viaBox2.left() > defaultWidth); auto prl2 = isH ? (viaBox2.top() - viaBox2.bottom()) : (viaBox2.right() - viaBox2.left()); frCoord reqDist = 0; if (isVia1Fat && isVia2Fat) { auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), min(prl1, prl2)); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, min(prl1, prl2)); } } if (isH) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += max((viaBox2.right() - 0), (0 - viaBox2.left())); } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += max((viaBox2.top() - 0), (0 - viaBox2.bottom())); } sol = max(sol, reqDist); } // check min len in layer2 if two vias are in same layer if (viaDef1 != viaDef2) { return sol; } if (viaDef1->getLayer1Num() == lNum) { via1.getLayer2BBox(viaBox1); lNum = lNum + 2; } else { via1.getLayer1BBox(viaBox1); lNum = lNum - 2; } width1 = viaBox1.width(); prl1 = isH ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); reqDist = 0; auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, prl1); } } if (isH) { reqDist += (viaBox1.right() - 0) + (0 - viaBox1.left()); } else { reqDist += (viaBox1.top() - 0) + (0 - viaBox1.bottom()); } sol = max(sol, reqDist); return sol; } void FlexDR::init_via2viaMinLen() { bool enableOutput = false; //bool enableOutput = true; auto bottomLayerNum = getDesign()->getTech()->getBottomLayerNum(); auto topLayerNum = getDesign()->getTech()->getTopLayerNum(); for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2viaMinLenTmp(4, 0); vector<bool> via2viaZeroLen(4, true); via2viaMinLen_.push_back(make_pair(via2viaMinLenTmp, via2viaZeroLen)); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } (via2viaMinLen_[i].first)[0] = max((via2viaMinLen_[i].first)[0], init_via2viaMinLen_minSpc(lNum, downVia, downVia)); (via2viaMinLen_[i].first)[1] = max((via2viaMinLen_[i].first)[1], init_via2viaMinLen_minSpc(lNum, downVia, upVia)); (via2viaMinLen_[i].first)[2] = max((via2viaMinLen_[i].first)[2], init_via2viaMinLen_minSpc(lNum, upVia, downVia)); (via2viaMinLen_[i].first)[3] = max((via2viaMinLen_[i].first)[3], init_via2viaMinLen_minSpc(lNum, upVia, upVia)); if (enableOutput) { logger_->info(DRT, 188, "initVia2ViaMinLen_minSpc {}" " (d2d, d2u, u2d, u2u) = ({}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), (via2viaMinLen_[i].first)[0], (via2viaMinLen_[i].first)[1], (via2viaMinLen_[i].first)[2], (via2viaMinLen_[i].first)[3]); } i++; } // check minimumcut i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } vector<frCoord> via2viaMinLenTmp(4, 0); (via2viaMinLen_[i].first)[0] = max((via2viaMinLen_[i].first)[0], init_via2viaMinLen_minimumcut1(lNum, downVia, downVia)); (via2viaMinLen_[i].first)[1] = max((via2viaMinLen_[i].first)[1], init_via2viaMinLen_minimumcut1(lNum, downVia, upVia)); (via2viaMinLen_[i].first)[2] = max((via2viaMinLen_[i].first)[2], init_via2viaMinLen_minimumcut1(lNum, upVia, downVia)); (via2viaMinLen_[i].first)[3] = max((via2viaMinLen_[i].first)[3], init_via2viaMinLen_minimumcut1(lNum, upVia, upVia)); (via2viaMinLen_[i].second)[0] = (via2viaMinLen_[i].second)[0] && init_via2viaMinLen_minimumcut2(lNum, downVia, downVia); (via2viaMinLen_[i].second)[1] = (via2viaMinLen_[i].second)[1] && init_via2viaMinLen_minimumcut2(lNum, downVia, upVia); (via2viaMinLen_[i].second)[2] = (via2viaMinLen_[i].second)[2] && init_via2viaMinLen_minimumcut2(lNum, upVia, downVia); (via2viaMinLen_[i].second)[3] = (via2viaMinLen_[i].second)[3] && init_via2viaMinLen_minimumcut2(lNum, upVia, upVia); if (enableOutput) { logger_->info(DRT, 189, "initVia2ViaMinLen_minimumcut {}" " (d2d, d2u, u2d, u2u) = ({}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), (via2viaMinLen_[i].first)[0], (via2viaMinLen_[i].first)[1], (via2viaMinLen_[i].first)[2], (via2viaMinLen_[i].first)[3]); logger_->info(DRT, 190, "initVia2ViaMinLen_minimumcut {}" " zerolen (b, b, b, b) = ({}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), (via2viaMinLen_[i].second)[0], (via2viaMinLen_[i].second)[1], (via2viaMinLen_[i].second)[2], (via2viaMinLen_[i].second)[3]); } i++; } } frCoord FlexDR::init_via2viaMinLenNew_minimumcut1(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); auto length1 = viaBox1.length(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); auto length2 = viaBox2.length(); for (auto &con: getDesign()->getTech()->getLayer(lNum)->getMinimumcutConstraints()) { // check via2cut to via1metal // no length OR metal1 shape satisfies --> check via2 if ((!con->hasLength() || (con->hasLength() && length1 > con->getLength())) && width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } if (isCurrDirX) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.right() - 0 + 0 - viaBox1.left(), viaBox1.right() - 0 + 0 - cutBox2.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.top() - 0 + 0 - viaBox1.bottom(), viaBox1.top() - 0 + 0 - cutBox2.bottom())); } } // check via1cut to via2metal if ((!con->hasLength() || (con->hasLength() && length2 > con->getLength())) && width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } if (isCurrDirX) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.right() - 0 + 0 - viaBox2.left(), viaBox2.right() - 0 + 0 - cutBox1.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.top() - 0 + 0 - viaBox2.bottom(), viaBox2.top() - 0 + 0 - cutBox1.bottom())); } } } return sol; } frCoord FlexDR::init_via2viaMinLenNew_minSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getDesign()->getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef1); frBox viaBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frVia via2(viaDef2); frBox viaBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } auto width2 = viaBox2.width(); bool isVia2Fat = isCurrDirX ? (viaBox2.top() - viaBox2.bottom() > defaultWidth) : (viaBox2.right() - viaBox2.left() > defaultWidth); auto prl2 = isCurrDirX ? (viaBox2.top() - viaBox2.bottom()) : (viaBox2.right() - viaBox2.left()); frCoord reqDist = 0; if (isVia1Fat && isVia2Fat) { auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), min(prl1, prl2)); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, min(prl1, prl2)); } } if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += max((viaBox2.right() - 0), (0 - viaBox2.left())); } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += max((viaBox2.top() - 0), (0 - viaBox2.bottom())); } sol = max(sol, reqDist); } // check min len in layer2 if two vias are in same layer if (viaDef1 != viaDef2) { return sol; } if (viaDef1->getLayer1Num() == lNum) { via1.getLayer2BBox(viaBox1); lNum = lNum + 2; } else { via1.getLayer1BBox(viaBox1); lNum = lNum - 2; } width1 = viaBox1.width(); prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); reqDist = 0; auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, prl1); } } if (isCurrDirX) { reqDist += (viaBox1.right() - 0) + (0 - viaBox1.left()); } else { reqDist += (viaBox1.top() - 0) + (0 - viaBox1.bottom()); } sol = max(sol, reqDist); return sol; } frCoord FlexDR::init_via2viaMinLenNew_cutSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } via1.getCutBBox(cutBox1); frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } via2.getCutBBox(cutBox2); // same layer (use samenet rule if exist, otherwise use diffnet rule) if (viaDef1->getCutLayerNum() == viaDef2->getCutLayerNum()) { auto samenetCons = getDesign()->getTech()->getLayer(viaDef1->getCutLayerNum())->getCutSpacing(true); auto diffnetCons = getDesign()->getTech()->getLayer(viaDef1->getCutLayerNum())->getCutSpacing(false); if (!samenetCons.empty()) { // check samenet spacing rule if exists for (auto con: samenetCons) { if (con == nullptr) { continue; } // filter rule, assuming default via will never trigger cutArea if (con->hasSecondLayer() || con->isAdjacentCuts() || con->isParallelOverlap() || con->isArea() || !con->hasSameNet()) { continue; } auto reqSpcVal = con->getCutSpacing(); if (!con->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } sol = max(sol, reqSpcVal); } } else { // check diffnet spacing rule // filter rule, assuming default via will never trigger cutArea for (auto con: diffnetCons) { if (con == nullptr) { continue; } if (con->hasSecondLayer() || con->isAdjacentCuts() || con->isParallelOverlap() || con->isArea() || con->hasSameNet()) { continue; } auto reqSpcVal = con->getCutSpacing(); if (!con->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } sol = max(sol, reqSpcVal); } } // TODO: diff layer } else { auto layerNum1 = viaDef1->getCutLayerNum(); auto layerNum2 = viaDef2->getCutLayerNum(); frCutSpacingConstraint* samenetCon = nullptr; if (getDesign()->getTech()->getLayer(layerNum1)->hasInterLayerCutSpacing(layerNum2, true)) { samenetCon = getDesign()->getTech()->getLayer(layerNum1)->getInterLayerCutSpacing(layerNum2, true); } if (getDesign()->getTech()->getLayer(layerNum2)->hasInterLayerCutSpacing(layerNum1, true)) { if (samenetCon) { cout <<"Warning: duplicate diff layer samenet cut spacing, skipping cut spacing from " <<layerNum2 <<" to " <<layerNum1 <<endl; } else { samenetCon = getDesign()->getTech()->getLayer(layerNum2)->getInterLayerCutSpacing(layerNum1, true); } } if (samenetCon == nullptr) { if (getDesign()->getTech()->getLayer(layerNum1)->hasInterLayerCutSpacing(layerNum2, false)) { samenetCon = getDesign()->getTech()->getLayer(layerNum1)->getInterLayerCutSpacing(layerNum2, false); } if (getDesign()->getTech()->getLayer(layerNum2)->hasInterLayerCutSpacing(layerNum1, false)) { if (samenetCon) { cout <<"Warning: duplicate diff layer diffnet cut spacing, skipping cut spacing from " <<layerNum2 <<" to " <<layerNum1 <<endl; } else { samenetCon = getDesign()->getTech()->getLayer(layerNum2)->getInterLayerCutSpacing(layerNum1, false); } } } if (samenetCon) { // filter rule, assuming default via will never trigger cutArea auto reqSpcVal = samenetCon->getCutSpacing(); if (reqSpcVal == 0) { ; } else { if (!samenetCon->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } } sol = max(sol, reqSpcVal); } } return sol; } void FlexDR::init_via2viaMinLenNew() { bool enableOutput = false; //bool enableOutput = true; auto bottomLayerNum = getDesign()->getTech()->getBottomLayerNum(); auto topLayerNum = getDesign()->getTech()->getTopLayerNum(); for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2viaMinLenTmp(8, 0); via2viaMinLenNew_.push_back(via2viaMinLenTmp); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew_[i][0] = max(via2viaMinLenNew_[i][0], init_via2viaMinLenNew_minSpc(lNum, downVia, downVia, false)); via2viaMinLenNew_[i][1] = max(via2viaMinLenNew_[i][1], init_via2viaMinLenNew_minSpc(lNum, downVia, downVia, true )); via2viaMinLenNew_[i][2] = max(via2viaMinLenNew_[i][2], init_via2viaMinLenNew_minSpc(lNum, downVia, upVia, false)); via2viaMinLenNew_[i][3] = max(via2viaMinLenNew_[i][3], init_via2viaMinLenNew_minSpc(lNum, downVia, upVia, true )); via2viaMinLenNew_[i][4] = max(via2viaMinLenNew_[i][4], init_via2viaMinLenNew_minSpc(lNum, upVia, downVia, false)); via2viaMinLenNew_[i][5] = max(via2viaMinLenNew_[i][5], init_via2viaMinLenNew_minSpc(lNum, upVia, downVia, true )); via2viaMinLenNew_[i][6] = max(via2viaMinLenNew_[i][6], init_via2viaMinLenNew_minSpc(lNum, upVia, upVia, false)); via2viaMinLenNew_[i][7] = max(via2viaMinLenNew_[i][7], init_via2viaMinLenNew_minSpc(lNum, upVia, upVia, true )); if (enableOutput) { logger_->info(DRT, 191, "initVia2ViaMinLenNew_minSpc {} " "(d2d-x, d2d-y, d2u-x, d2u-y, u2d-x, u2d-y, u2u-x, u2u-y) " "= ({}, {}, {}, {}, {}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), via2viaMinLenNew_[i][0], via2viaMinLenNew_[i][1], via2viaMinLenNew_[i][2], via2viaMinLenNew_[i][3], via2viaMinLenNew_[i][4], via2viaMinLenNew_[i][5], via2viaMinLenNew_[i][6], via2viaMinLenNew_[i][7]); } i++; } // check minimumcut i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew_[i][0] = max(via2viaMinLenNew_[i][0], init_via2viaMinLenNew_minimumcut1(lNum, downVia, downVia, false)); via2viaMinLenNew_[i][1] = max(via2viaMinLenNew_[i][1], init_via2viaMinLenNew_minimumcut1(lNum, downVia, downVia, true )); via2viaMinLenNew_[i][2] = max(via2viaMinLenNew_[i][2], init_via2viaMinLenNew_minimumcut1(lNum, downVia, upVia, false)); via2viaMinLenNew_[i][3] = max(via2viaMinLenNew_[i][3], init_via2viaMinLenNew_minimumcut1(lNum, downVia, upVia, true )); via2viaMinLenNew_[i][4] = max(via2viaMinLenNew_[i][4], init_via2viaMinLenNew_minimumcut1(lNum, upVia, downVia, false)); via2viaMinLenNew_[i][5] = max(via2viaMinLenNew_[i][5], init_via2viaMinLenNew_minimumcut1(lNum, upVia, downVia, true )); via2viaMinLenNew_[i][6] = max(via2viaMinLenNew_[i][6], init_via2viaMinLenNew_minimumcut1(lNum, upVia, upVia, false)); via2viaMinLenNew_[i][7] = max(via2viaMinLenNew_[i][7], init_via2viaMinLenNew_minimumcut1(lNum, upVia, upVia, true )); if (enableOutput) { logger_->info(DRT, 192, "initVia2ViaMinLenNew_minimumcut {}" " (d2d-x, d2d-y, d2u-x, d2u-y, u2d-x, u2d-y, u2u-x, u2u-y) " "= ({}, {}, {}, {}, {}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), via2viaMinLenNew_[i][0], via2viaMinLenNew_[i][1], via2viaMinLenNew_[i][2], via2viaMinLenNew_[i][3], via2viaMinLenNew_[i][4], via2viaMinLenNew_[i][5], via2viaMinLenNew_[i][6], via2viaMinLenNew_[i][7]); } i++; } // check cut spacing i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew_[i][0] = max(via2viaMinLenNew_[i][0], init_via2viaMinLenNew_cutSpc(lNum, downVia, downVia, false)); via2viaMinLenNew_[i][1] = max(via2viaMinLenNew_[i][1], init_via2viaMinLenNew_cutSpc(lNum, downVia, downVia, true )); via2viaMinLenNew_[i][2] = max(via2viaMinLenNew_[i][2], init_via2viaMinLenNew_cutSpc(lNum, downVia, upVia, false)); via2viaMinLenNew_[i][3] = max(via2viaMinLenNew_[i][3], init_via2viaMinLenNew_cutSpc(lNum, downVia, upVia, true )); via2viaMinLenNew_[i][4] = max(via2viaMinLenNew_[i][4], init_via2viaMinLenNew_cutSpc(lNum, upVia, downVia, false)); via2viaMinLenNew_[i][5] = max(via2viaMinLenNew_[i][5], init_via2viaMinLenNew_cutSpc(lNum, upVia, downVia, true )); via2viaMinLenNew_[i][6] = max(via2viaMinLenNew_[i][6], init_via2viaMinLenNew_cutSpc(lNum, upVia, upVia, false)); via2viaMinLenNew_[i][7] = max(via2viaMinLenNew_[i][7], init_via2viaMinLenNew_cutSpc(lNum, upVia, upVia, true )); if (enableOutput) { logger_->info(DRT, 193, "initVia2ViaMinLenNew_cutSpc {}" " (d2d-x, d2d-y, d2u-x, d2u-y, u2d-x, u2d-y, u2u-x, u2u-y) " "= ({}, {}, {}, {}, {}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), via2viaMinLenNew_[i][0], via2viaMinLenNew_[i][1], via2viaMinLenNew_[i][2], via2viaMinLenNew_[i][3], via2viaMinLenNew_[i][4], via2viaMinLenNew_[i][5], via2viaMinLenNew_[i][6], via2viaMinLenNew_[i][7]); } i++; } } void FlexDR::init_halfViaEncArea() { auto bottomLayerNum = getDesign()->getTech()->getBottomLayerNum(); auto topLayerNum = getDesign()->getTech()->getTopLayerNum(); for (int i = bottomLayerNum; i <= topLayerNum; i++) { if (getDesign()->getTech()->getLayer(i)->getType() != frLayerTypeEnum::ROUTING) { continue; } if (i + 1 <= topLayerNum && getDesign()->getTech()->getLayer(i + 1)->getType() == frLayerTypeEnum::CUT) { auto viaDef = getTech()->getLayer(i + 1)->getDefaultViaDef(); frVia via(viaDef); frBox layer1Box; frBox layer2Box; via.getLayer1BBox(layer1Box); via.getLayer2BBox(layer2Box); auto layer1HalfArea = layer1Box.width() * layer1Box.length() / 2; auto layer2HalfArea = layer2Box.width() * layer2Box.length() / 2; halfViaEncArea_.push_back(make_pair(layer1HalfArea, layer2HalfArea)); } else { halfViaEncArea_.push_back(make_pair(0,0)); } } } frCoord FlexDR::init_via2turnMinLen_minSpc(frLayerNum lNum, frViaDef* viaDef, bool isCurrDirY) { if (!viaDef) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getDesign()->getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef); frBox viaBox1; if (viaDef->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frCoord reqDist = 0; if (isVia1Fat) { auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, defaultWidth), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, defaultWidth, prl1); } } if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += defaultWidth; } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += defaultWidth; } sol = max(sol, reqDist); } return sol; } frCoord FlexDR::init_via2turnMinLen_minStp(frLayerNum lNum, frViaDef* viaDef, bool isCurrDirY) { if (!viaDef) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getDesign()->getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef); frBox viaBox1; if (viaDef->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); frCoord reqDist = 0; if (isVia1Fat) { auto con = getDesign()->getTech()->getLayer(lNum)->getMinStepConstraint(); if (con && con->hasMaxEdges()) { // currently only consider maxedge violation reqDist = con->getMinStepLength(); if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += defaultWidth; } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += defaultWidth; } sol = max(sol, reqDist); } } return sol; } void FlexDR::init_via2turnMinLen() { bool enableOutput = false; //bool enableOutput = true; auto bottomLayerNum = getDesign()->getTech()->getBottomLayerNum(); auto topLayerNum = getDesign()->getTech()->getTopLayerNum(); for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2turnMinLenTmp(4, 0); via2turnMinLen_.push_back(via2turnMinLenTmp); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2turnMinLen_[i][0] = max(via2turnMinLen_[i][0], init_via2turnMinLen_minSpc(lNum, downVia, false)); via2turnMinLen_[i][1] = max(via2turnMinLen_[i][1], init_via2turnMinLen_minSpc(lNum, downVia, true)); via2turnMinLen_[i][2] = max(via2turnMinLen_[i][2], init_via2turnMinLen_minSpc(lNum, upVia, false)); via2turnMinLen_[i][3] = max(via2turnMinLen_[i][3], init_via2turnMinLen_minSpc(lNum, upVia, true)); if (enableOutput) { cout <<"initVia2TurnMinLen_minSpc " <<getDesign()->getTech()->getLayer(lNum)->getName() <<" (down->x->y, down->y->x, up->x->y, up->y->x) = (" <<via2turnMinLen_[i][0] <<", " <<via2turnMinLen_[i][1] <<", " <<via2turnMinLen_[i][2] <<", " <<via2turnMinLen_[i][3] <<")" <<endl; } i++; } // check minstep i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } vector<frCoord> via2turnMinLenTmp(4, 0); via2turnMinLen_[i][0] = max(via2turnMinLen_[i][0], init_via2turnMinLen_minStp(lNum, downVia, false)); via2turnMinLen_[i][1] = max(via2turnMinLen_[i][1], init_via2turnMinLen_minStp(lNum, downVia, true)); via2turnMinLen_[i][2] = max(via2turnMinLen_[i][2], init_via2turnMinLen_minStp(lNum, upVia, false)); via2turnMinLen_[i][3] = max(via2turnMinLen_[i][3], init_via2turnMinLen_minStp(lNum, upVia, true)); if (enableOutput) { cout <<"initVia2TurnMinLen_minstep " <<getDesign()->getTech()->getLayer(lNum)->getName() <<" (down->x->y, down->y->x, up->x->y, up->y->x) = (" <<via2turnMinLen_[i][0] <<", " <<via2turnMinLen_[i][1] <<", " <<via2turnMinLen_[i][2] <<", " <<via2turnMinLen_[i][3] <<")" <<endl; } i++; } } void FlexDR::init() { ProfileTask profile("DR:init"); frTime t; if (VERBOSE > 0) { logger_->info(DRT, 187, "start routing data preparation"); } initGCell2BoundaryPin(); getRegionQuery()->initDRObj(getTech()->getLayers().size()); // first init in postProcess init_halfViaEncArea(); init_via2viaMinLen(); init_via2viaMinLenNew(); init_via2turnMinLen(); if (VERBOSE > 0) { t.print(logger_); } } void FlexDR::removeGCell2BoundaryPin() { gcell2BoundaryPin_.clear(); gcell2BoundaryPin_.shrink_to_fit(); } map<frNet*, set<pair<frPoint, frLayerNum> >, frBlockObjectComp> FlexDR::initDR_mergeBoundaryPin(int startX, int startY, int size, const frBox &routeBox) { map<frNet*, set<pair<frPoint, frLayerNum> >, frBlockObjectComp> bp; auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto &xgp = gCellPatterns.at(0); auto &ygp = gCellPatterns.at(1); for (int i = startX; i < (int)xgp.getCount() && i < startX + size; i++) { for (int j = startY; j < (int)ygp.getCount() && j < startY + size; j++) { auto &currBp = gcell2BoundaryPin_[i][j]; for (auto &[net, s]: currBp) { for (auto &[pt, lNum]: s) { if (pt.x() == routeBox.left() || pt.x() == routeBox.right() || pt.y() == routeBox.bottom() || pt.y() == routeBox.top()) { bp[net].insert(make_pair(pt, lNum)); } } } } } return bp; } void FlexDR::initDR(int size, bool enableDRC) { bool TEST = false; // bool TEST = true; //FlexGridGraph gg(getTech(), getDesign()); ////frBox testBBox(225000, 228100, 228000, 231100); // net1702 in ispd19_test1 //frBox testBBox(0, 0, 2000, 2000); // net1702 in ispd19_test1 ////gg.setBBox(testBBox); //gg.init(testBBox); //gg.print(); //exit(1); frTime t; if (VERBOSE > 0) { cout <<endl <<"start initial detail routing ..." <<endl; } frBox dieBox; getDesign()->getTopBlock()->getBoundaryBBox(dieBox); auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto &xgp = gCellPatterns.at(0); auto &ygp = gCellPatterns.at(1); int cnt = 0; int tot = (((int)xgp.getCount() - 1) / size + 1) * (((int)ygp.getCount() - 1) / size + 1); int prev_perc = 0; bool isExceed = false; int numQuickMarkers = 0; if (TEST) { //FlexDRWorker worker(getDesign()); FlexDRWorker worker(this, logger_); //frBox routeBox; //routeBox.set(0*2000, 0*2000, 1*2000, 1*2000); //frCoord xl = 21 * 2000; //frCoord yl = 42 * 2000; frCoord xl = 241.92 * 2000; frCoord yl = 241.92 * 2000; //frCoord xh = 129 * 2000; //frCoord yh = 94.05 * 2000; frPoint idx; getDesign()->getTopBlock()->getGCellIdx(frPoint(xl, yl), idx); if (VERBOSE > 1) { cout <<"(i,j) = (" <<idx.x() <<", " <<idx.y() <<")" <<endl; } //getDesign()->getTopBlock()->getGCellBox(idx, routeBox); frBox routeBox1; getDesign()->getTopBlock()->getGCellBox(frPoint(idx.x(), idx.y()), routeBox1); frBox routeBox2; getDesign()->getTopBlock()->getGCellBox(frPoint(min((int)xgp.getCount() - 1, idx.x() + size-1), min((int)ygp.getCount(), idx.y() + size-1)), routeBox2); frBox routeBox(routeBox1.left(), routeBox1.bottom(), routeBox2.right(), routeBox2.top()); auto bp = initDR_mergeBoundaryPin(idx.x(), idx.y(), size, routeBox); //routeBox.set(129*2000, 94.05*2000, 132*2000, 96.9*2000); worker.setRouteBox(routeBox); frBox extBox; routeBox.bloat(2000, extBox); frBox drcBox; routeBox.bloat(500, drcBox); worker.setRouteBox(routeBox); worker.setExtBox(extBox); worker.setDrcBox(drcBox); worker.setFollowGuide(false); worker.setCost(DRCCOST, 0, 0, 0); //int i = (129 * 2000 - xgp.getStartCoord()) / xgp.getSpacing(); //int j = (94.05 * 2000 - ygp.getStartCoord()) / ygp.getSpacing(); //worker.setDRIter(0, gcell2BoundaryPin[idx.x()][idx.y()]); worker.setDRIter(0, bp); worker.setEnableDRC(enableDRC); //worker.setTest(true); worker.main(); cout <<"done" <<endl <<flush; } else { vector<unique_ptr<FlexDRWorker> > uworkers; int batchStepX, batchStepY; getBatchInfo(batchStepX, batchStepY); vector<vector<vector<unique_ptr<FlexDRWorker> > > > workers(batchStepX * batchStepY); int xIdx = 0, yIdx = 0; // sequential init for (int i = 0; i < (int)xgp.getCount(); i += size) { for (int j = 0; j < (int)ygp.getCount(); j += size) { auto worker = make_unique<FlexDRWorker>(this, logger_); frBox routeBox1; getDesign()->getTopBlock()->getGCellBox(frPoint(i, j), routeBox1); frBox routeBox2; getDesign()->getTopBlock()->getGCellBox(frPoint(min((int)xgp.getCount() - 1, i + size-1), min((int)ygp.getCount(), j + size-1)), routeBox2); //frBox routeBox; frBox routeBox(routeBox1.left(), routeBox1.bottom(), routeBox2.right(), routeBox2.top()); frBox extBox; routeBox.bloat(MTSAFEDIST, extBox); frBox drcBox; routeBox.bloat(DRCSAFEDIST, drcBox); worker->setRouteBox(routeBox); worker->setExtBox(extBox); worker->setDrcBox(drcBox); auto bp = initDR_mergeBoundaryPin(i, j, size, routeBox); worker->setDRIter(0, bp); // set boundary pin worker->setEnableDRC(enableDRC); worker->setFollowGuide(false); //worker->setFollowGuide(true); worker->setCost(DRCCOST, 0, 0, 0); // int workerIdx = xIdx * batchSizeY + yIdx; int batchIdx = (xIdx % batchStepX) * batchStepY + yIdx % batchStepY; // workers[batchIdx][workerIdx] = worker; if (workers[batchIdx].empty() || (int)workers[batchIdx].back().size() >= BATCHSIZE) { workers[batchIdx].push_back(vector<unique_ptr<FlexDRWorker> >()); } workers[batchIdx].back().push_back(std::move(worker)); yIdx++; } yIdx = 0; xIdx++; } omp_set_num_threads(MAX_THREADS); // parallel execution for (auto &workerBatch: workers) { for (auto &workersInBatch: workerBatch) { // multi thread #pragma omp parallel for schedule(dynamic) for (int i = 0; i < (int)workersInBatch.size(); i++) { workersInBatch[i]->main_mt(); #pragma omp critical { cnt++; if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc < 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; //if (true) { if (isExceed) { if (enableDRC) { cout <<" completing " <<prev_perc <<"% with " <<getDesign()->getTopBlock()->getNumMarkers() <<" violations" <<endl; } else { cout <<" completing " <<prev_perc <<"% with " <<numQuickMarkers <<" quick violations" <<endl; } cout <<" " <<t <<endl <<flush; } } } } } // single thread for (int i = 0; i < (int)workersInBatch.size(); i++) { workersInBatch[i]->end(); } workersInBatch.clear(); } } checkConnectivity(); } if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc >= 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; //if (true) { if (isExceed) { if (enableDRC) { cout <<" completing " <<prev_perc <<"% with " <<getDesign()->getTopBlock()->getNumMarkers() <<" violations" <<endl; } else { cout <<" completing " <<prev_perc <<"% with " <<numQuickMarkers <<" quick violations" <<endl; } cout <<" " <<t <<endl <<flush; } } } removeGCell2BoundaryPin(); numViols_.push_back(getDesign()->getTopBlock()->getNumMarkers()); if (VERBOSE > 0) { if (enableDRC) { logger_->info(DRT, 196, " number of violations = {}", getDesign()->getTopBlock()->getNumMarkers()); } else { logger_->info(DRT, 197, " number of quick violations = {}", numQuickMarkers); } t.print(logger_); cout <<flush; } } void FlexDR::getBatchInfo(int &batchStepX, int &batchStepY) { batchStepX = 2; batchStepY = 2; } void FlexDR::searchRepair(int iter, int size, int offset, int mazeEndIter, frUInt4 workerDRCCost, frUInt4 workerMarkerCost, frUInt4 workerMarkerBloatWidth, frUInt4 workerMarkerBloatDepth, bool enableDRC, int ripupMode, bool followGuide, int fixMode, bool TEST) { std::string profile_name("DR:searchRepair"); profile_name += std::to_string(iter); ProfileTask profile(profile_name.c_str()); if (iter > END_ITERATION) { return; } if (ripupMode != 1 && getDesign()->getTopBlock()->getMarkers().size() == 0) { return; } frTime t; //bool TEST = false; //bool TEST = true; if (VERBOSE > 0) { string suffix; if (iter == 1 || (iter > 20 && iter % 10 == 1)) { suffix = "st"; } else if (iter == 2 || (iter > 20 && iter % 10 == 2)) { suffix = "nd"; } else if (iter == 3 || (iter > 20 && iter % 10 == 3)) { suffix = "rd"; } else { suffix = "th"; } logger_->info(DRT, 195, "start {}{} optimization iteration ...", iter, suffix); } if (graphics_) { graphics_->startIter(iter); } frBox dieBox; getDesign()->getTopBlock()->getBoundaryBBox(dieBox); auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto &xgp = gCellPatterns.at(0); auto &ygp = gCellPatterns.at(1); int numQuickMarkers = 0; int clipSize = size; int cnt = 0; int tot = (((int)xgp.getCount() - 1 - offset) / clipSize + 1) * (((int)ygp.getCount() - 1 - offset) / clipSize + 1); int prev_perc = 0; bool isExceed = false; if (TEST) { cout <<"search and repair test mode" <<endl <<flush; //FlexDRWorker worker(getDesign()); FlexDRWorker worker(this, logger_); frBox routeBox; //frCoord xl = 148.5 * 2000; //frCoord yl = 570 * 2000; //frPoint idx; //getDesign()->getTopBlock()->getGCellIdx(frPoint(xl, yl), idx); //if (VERBOSE > 1) { // cout <<"(i,j) = (" <<idx.x() <<", " <<idx.y() <<")" <<endl; //} //getDesign()->getTopBlock()->getGCellBox(idx, routeBox); //routeBox.set(156*2000, 108.3*2000, 177*2000, 128.25*2000); // routeBox.set(175*2000, 3.5*2000, 185*2000, 13.5*2000); // routeBox.set(0*2000, 0*2000, 200*2000, 200*2000); // routeBox.set(420*1000, 816.1*1000, 441*1000, 837.1*1000); routeBox.set(441*1000, 816.1*1000, 462*1000, 837.1*1000); worker.setRouteBox(routeBox); frBox extBox; frBox drcBox; routeBox.bloat(2000, extBox); routeBox.bloat(500, drcBox); worker.setRouteBox(routeBox); worker.setExtBox(extBox); worker.setDrcBox(drcBox); worker.setMazeEndIter(mazeEndIter); worker.setTest(true); //worker.setQuickDRCTest(true); //worker.setDRCTest(true); worker.setDRIter(iter); if (!iter) { // set boundary pin (need to manulally calculate for test mode) auto bp = initDR_mergeBoundaryPin(147, 273, size, routeBox); worker.setDRIter(0, bp); } worker.setEnableDRC(enableDRC); worker.setRipupMode(ripupMode); worker.setFollowGuide(followGuide); worker.setFixMode(fixMode); //worker.setNetOrderingMode(netOrderingMode); worker.setCost(workerDRCCost, workerMarkerCost, workerMarkerBloatWidth, workerMarkerBloatDepth); worker.main_mt(); numQuickMarkers += worker.getNumQuickMarkers(); cout <<"done" <<endl <<flush; } else { vector<unique_ptr<FlexDRWorker> > uworkers; int batchStepX, batchStepY; getBatchInfo(batchStepX, batchStepY); vector<vector<vector<unique_ptr<FlexDRWorker> > > > workers(batchStepX * batchStepY); int xIdx = 0, yIdx = 0; for (int i = offset; i < (int)xgp.getCount(); i += clipSize) { for (int j = offset; j < (int)ygp.getCount(); j += clipSize) { auto worker = make_unique<FlexDRWorker>(this, logger_); frBox routeBox1; getDesign()->getTopBlock()->getGCellBox(frPoint(i, j), routeBox1); frBox routeBox2; const int max_i = min((int)xgp.getCount() - 1, i + clipSize-1); const int max_j = min((int)ygp.getCount(), j + clipSize-1); getDesign()->getTopBlock()->getGCellBox(frPoint(max_i, max_j), routeBox2); frBox routeBox(routeBox1.left(), routeBox1.bottom(), routeBox2.right(), routeBox2.top()); frBox extBox; frBox drcBox; routeBox.bloat(MTSAFEDIST, extBox); routeBox.bloat(DRCSAFEDIST, drcBox); worker->setRouteBox(routeBox); worker->setExtBox(extBox); worker->setDrcBox(drcBox); worker->setGCellBox(frBox(i, j, max_i, max_j)); worker->setMazeEndIter(mazeEndIter); worker->setDRIter(iter); if (!iter) { // if (routeBox.left() == 441000 && routeBox.bottom() == 816100) { // cout << "@@@ debug: " << i << " " << j << endl; // } // set boundary pin auto bp = initDR_mergeBoundaryPin(i, j, size, routeBox); worker->setDRIter(0, bp); } worker->setEnableDRC(enableDRC); worker->setRipupMode(ripupMode); worker->setFollowGuide(followGuide); worker->setFixMode(fixMode); // TODO: only pass to relevant workers worker->setGraphics(graphics_.get()); worker->setCost(workerDRCCost, workerMarkerCost, workerMarkerBloatWidth, workerMarkerBloatDepth); int batchIdx = (xIdx % batchStepX) * batchStepY + yIdx % batchStepY; if (workers[batchIdx].empty() || (int)workers[batchIdx].back().size() >= BATCHSIZE) { workers[batchIdx].push_back(vector<unique_ptr<FlexDRWorker>>()); } workers[batchIdx].back().push_back(std::move(worker)); yIdx++; } yIdx = 0; xIdx++; } omp_set_num_threads(MAX_THREADS); // parallel execution for (auto &workerBatch: workers) { ProfileTask profile("DR:checkerboard"); for (auto &workersInBatch: workerBatch) { { ProfileTask profile("DR:batch"); // multi thread #pragma omp parallel for schedule(dynamic) for (int i = 0; i < (int)workersInBatch.size(); i++) { workersInBatch[i]->main_mt(); #pragma omp critical { cnt++; if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc < 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; //if (true) { if (isExceed) { if (enableDRC) { logger_->report(" completing {}% with {} violations", prev_perc, getDesign()->getTopBlock()->getNumMarkers()); } else { logger_->report(" completing {}% with {} quick violations", prev_perc, numQuickMarkers); } logger_->report(" {}", t); } } } } } } { ProfileTask profile("DR:end_batch"); // single thread for (int i = 0; i < (int)workersInBatch.size(); i++) { workersInBatch[i]->end(); } workersInBatch.clear(); } } } } if (!iter) { removeGCell2BoundaryPin(); } if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc >= 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; //if (true) { if (isExceed) { if (enableDRC) { logger_->report(" completing {}% with {} violations", prev_perc, getDesign()->getTopBlock()->getNumMarkers()); } else { logger_->report(" completing {}% with {} quick violations", prev_perc, numQuickMarkers); } logger_->report(" {}", t); } } } checkConnectivity(iter); numViols_.push_back(getDesign()->getTopBlock()->getNumMarkers()); if (VERBOSE > 0) { if (enableDRC) { logger_->info(DRT, 199, " number of violations = {}", getDesign()->getTopBlock()->getNumMarkers()); } else { logger_->info(DRT, 200, " number of quick violations = {}", numQuickMarkers); } t.print(logger_); cout <<flush; } end(); } void FlexDR::end(bool writeMetrics) { vector<unsigned long long> wlen(getTech()->getLayers().size(), 0); vector<unsigned long long> sCut(getTech()->getLayers().size(), 0); vector<unsigned long long> mCut(getTech()->getLayers().size(), 0); unsigned long long totWlen = 0; unsigned long long totSCut = 0; unsigned long long totMCut = 0; frPoint bp, ep; for (auto &net: getDesign()->getTopBlock()->getNets()) { for (auto &shape: net->getShapes()) { if (shape->typeId() == frcPathSeg) { auto obj = static_cast<frPathSeg*>(shape.get()); obj->getPoints(bp, ep); auto lNum = obj->getLayerNum(); frCoord psLen = ep.x() - bp.x() + ep.y() - bp.y(); wlen[lNum] += psLen; totWlen += psLen; } } for (auto &via: net->getVias()) { auto lNum = via->getViaDef()->getCutLayerNum(); if (via->getViaDef()->isMultiCut()) { ++mCut[lNum]; ++totMCut; } else { ++sCut[lNum]; ++totSCut; } } } if (writeMetrics) { logger_->metric(DRT, "wire length::total", totWlen / getDesign()->getTopBlock()->getDBUPerUU()); logger_->metric(DRT, "vias::total", totSCut + totMCut); } if (VERBOSE > 0) { logger_->report("total wire length = {} um", totWlen / getDesign()->getTopBlock()->getDBUPerUU()); for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::ROUTING) { logger_->report("total wire length on LAYER {} = {} um", getTech()->getLayer(i)->getName(), wlen[i] / getDesign()->getTopBlock()->getDBUPerUU()); } } logger_->report("total number of vias = {}", totSCut + totMCut); if (totMCut > 0) { logger_->report("total number of multi-cut vias = {} ({:5.1f}%)", totMCut, totMCut * 100.0 / (totSCut + totMCut)); logger_->report("total number of single-cut vias = {} ({:5.1f}%)", totSCut, totSCut * 100.0 / (totSCut + totMCut)); } logger_->report("up-via summary (total {}):", totSCut + totMCut); int nameLen = 0; for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::CUT) { nameLen = max(nameLen, (int)getTech()->getLayer(i-1)->getName().size()); } } int maxL = 1 + nameLen + 4 + (int)to_string(totSCut).length(); if (totMCut) { maxL += 9 + 4 + (int)to_string(totMCut).length() + 9 + 4 + (int)to_string(totSCut + totMCut).length(); } std::ostringstream msg; if (totMCut) { msg <<" " <<setw(nameLen + 4 + (int)to_string(totSCut).length() + 9) <<"single-cut"; msg <<setw(4 + (int)to_string(totMCut).length() + 9) <<"multi-cut" <<setw(4 + (int)to_string(totSCut + totMCut).length()) <<"total"; } msg <<endl; for (int i = 0; i < maxL; i++) { msg <<"-"; } msg <<endl; for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::CUT) { msg <<" " <<setw(nameLen) <<getTech()->getLayer(i-1)->getName() <<" " <<setw((int)to_string(totSCut).length()) <<sCut[i]; if (totMCut) { msg <<" (" <<setw(5) <<(double)((sCut[i] + mCut[i]) ? sCut[i] * 100.0 / (sCut[i] + mCut[i]) : 0.0) <<"%)"; msg <<" " <<setw((int)to_string(totMCut).length()) <<mCut[i] <<" (" <<setw(5) <<(double)((sCut[i] + mCut[i]) ? mCut[i] * 100.0 / (sCut[i] + mCut[i]) : 0.0) <<"%)" <<" " <<setw((int)to_string(totSCut + totMCut).length()) <<sCut[i] + mCut[i]; } msg <<endl; } } for (int i = 0; i < maxL; i++) { msg <<"-"; } msg <<endl; msg <<" " <<setw(nameLen) <<"" <<" " <<setw((int)to_string(totSCut).length()) <<totSCut; if (totMCut) { msg <<" (" <<setw(5) <<(double)((totSCut + totMCut) ? totSCut * 100.0 / (totSCut + totMCut) : 0.0) <<"%)"; msg <<" " <<setw((int)to_string(totMCut).length()) <<totMCut <<" (" <<setw(5) <<(double)((totSCut + totMCut) ? totMCut * 100.0 / (totSCut + totMCut) : 0.0) <<"%)" <<" " <<setw((int)to_string(totSCut + totMCut).length()) <<totSCut + totMCut; } msg <<endl <<endl; logger_->report("{}", msg.str()); } } void FlexDR::reportDRC() { double dbu = design_->getTech()->getDBUPerUU(); if (DRC_RPT_FILE == string("")) { if (VERBOSE > 0) { cout <<"Waring: no DRC report specified, skipped writing DRC report" <<endl; } return; } //cout << DRC_RPT_FILE << "\n"; ofstream drcRpt(DRC_RPT_FILE.c_str()); if (drcRpt.is_open()) { for (auto &marker: getDesign()->getTopBlock()->getMarkers()) { auto con = marker->getConstraint(); drcRpt << " violation type: "; if (con) { if (con->typeId() == frConstraintTypeEnum::frcShortConstraint) { if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::ROUTING) { drcRpt <<"Short"; } else if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::CUT) { drcRpt <<"CShort"; } } else if (con->typeId() == frConstraintTypeEnum::frcMinWidthConstraint) { drcRpt <<"MinWid"; } else if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { drcRpt <<"MetSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcSpacingEndOfLineConstraint) { drcRpt <<"EOLSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { drcRpt <<"MetSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcCutSpacingConstraint) { drcRpt <<"CutSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcMinStepConstraint) { drcRpt <<"MinStp"; } else if (con->typeId() == frConstraintTypeEnum::frcNonSufficientMetalConstraint) { drcRpt <<"NSMet"; } else if (con->typeId() == frConstraintTypeEnum::frcSpacingSamenetConstraint) { drcRpt <<"MetSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcOffGridConstraint) { drcRpt <<"OffGrid"; } else if (con->typeId() == frConstraintTypeEnum::frcMinEnclosedAreaConstraint) { drcRpt <<"MinHole"; } else if (con->typeId() == frConstraintTypeEnum::frcAreaConstraint) { drcRpt <<"MinArea"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58CornerSpacingConstraint) { drcRpt <<"CornerSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58CutSpacingConstraint) { drcRpt <<"CutSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58RectOnlyConstraint) { drcRpt <<"RectOnly"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58RightWayOnGridOnlyConstraint) { drcRpt <<"RightWayOnGridOnly"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58MinStepConstraint) { drcRpt <<"MinStp"; } else { drcRpt << "unknown"; } } else { drcRpt << "nullptr"; } drcRpt <<endl; // get source(s) of violation drcRpt << " srcs: "; for (auto src: marker->getSrcs()) { if (src) { switch (src->typeId()) { case frcNet: drcRpt << (static_cast<frNet*>(src))->getName() << " "; break; case frcInstTerm: { frInstTerm* instTerm = (static_cast<frInstTerm*>(src)); drcRpt <<instTerm->getInst()->getName() <<"/" <<instTerm->getTerm()->getName() << " "; break; } case frcTerm: { frTerm* term = (static_cast<frTerm*>(src)); drcRpt <<"PIN/" << term->getName() << " "; break; } case frcInstBlockage: { frInstBlockage* instBlockage = (static_cast<frInstBlockage*>(src)); drcRpt <<instBlockage->getInst()->getName() <<"/OBS" << " "; break; } case frcBlockage: { drcRpt << "PIN/OBS" << " "; break; } default: std::cout << "Error: unexpected src type in marker\n"; } } } drcRpt << "\n"; // get violation bbox frBox bbox; marker->getBBox(bbox); drcRpt << " bbox = ( " << bbox.left() / dbu << ", " << bbox.bottom() / dbu << " ) - ( " << bbox.right() / dbu << ", " << bbox.top() / dbu << " ) on Layer "; if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::CUT && marker->getLayerNum() - 1 >= getTech()->getBottomLayerNum()) { drcRpt << getTech()->getLayer(marker->getLayerNum() - 1)->getName() << "\n"; } else { drcRpt << getTech()->getLayer(marker->getLayerNum())->getName() << "\n"; } } } else { cout << "Error: Fail to open DRC report file\n"; } } int FlexDR::main() { ProfileTask profile("DR:main"); init(); frTime t; if (VERBOSE > 0) { logger_->info(DRT, 194, "start detail routing ..."); } // search and repair: iter, size, offset, mazeEndIter, workerDRCCost, workerMarkerCost, // markerBloatWidth, markerBloatDepth, enableDRC, ripupMode, followGuide, fixMode, TEST // fixMode: // 0 - general fix // 1 - fat via short, spc to wire fix (keep via net), no permutation, increasing DRCCOST // 2 - fat via short, spc to wire fix (ripup via net), no permutation, increasing DRCCOST // 3 - general fix, ripup everything (bloat) // 4 - general fix, ripup left/bottom net (touching), currently DISABLED // 5 - general fix, ripup right/top net (touching), currently DISABLED // 6 - two-net viol // 9 - search-and-repair queue // assume only mazeEndIter > 1 if enableDRC and ripupMode == 0 (partial ripup) //end(); //searchRepair(1, 7, -4, 1, DRCCOST, 0, 0, 0, true, 1, false, 0, true); // test mode // need three different offsets to resolve boundary corner issues int iterNum = 0; searchRepair(iterNum++/* 0 */, 7, 0, 3, DRCCOST, 0/*MAARKERCOST*/, 0, 0, true, 1, true, 9); // true search and repair searchRepair(iterNum++/* 1 */, 7, -2, 3, DRCCOST, DRCCOST/*MAARKERCOST*/, 0, 0, true, 1, true, 9); // true search and repair searchRepair(iterNum++/* 1 */, 7, -5, 3, DRCCOST, DRCCOST/*MAARKERCOST*/, 0, 0, true, 1, true, 9); // true search and repair searchRepair(iterNum++/* 3 */, 7, 0, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 4 */, 7, -1, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 5 */, 7, -2, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 6 */, 7, -3, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 7 */, 7, -4, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 8 */, 7, -5, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 9 */, 7, -6, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 10 */, 7, 0, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 11 */, 7, -1, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 12 */, 7, -2, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 13 */, 7, -3, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 14 */, 7, -4, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 15 */, 7, -5, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 16 */, 7, -6, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 7, -3, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 17 */, 7, 0, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 18 */, 7, -1, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 19 */, 7, -2, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 20 */, 7, -3, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 21 */, 7, -4, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 22 */, 7, -5, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 23 */, 7, -6, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 5, -2, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 24 */, 7, 0, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 25 */, 7, -1, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 26 */, 7, -2, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 27 */, 7, -3, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 28 */, 7, -4, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 29 */, 7, -5, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 30 */, 7, -6, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 3, -1, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 31 */, 7, 0, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 32 */, 7, -1, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 33 */, 7, -2, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 34 */, 7, -3, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 35 */, 7, -4, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 36 */, 7, -5, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 37 */, 7, -6, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 3, -2, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 38 */, 7, 0, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 39 */, 7, -1, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 40 */, 7, -2, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 41 */, 7, -3, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 42 */, 7, -4, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 43 */, 7, -5, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 44 */, 7, -6, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 3, -0, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 45 */, 7, 0, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 46 */, 7, -1, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 47 */, 7, -2, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 48 */, 7, -3, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 49 */, 7, -4, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 50 */, 7, -5, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 51 */, 7, -6, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 3, -1, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 52 */, 7, 0, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 53 */, 7, -1, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 54 */, 7, -2, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 55 */, 7, -3, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 56 */, 7, -4, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 57 */, 7, -5, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 58 */, 7, -6, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair if (DRC_RPT_FILE != string("")) { reportDRC(); } if (VERBOSE > 0) { logger_->info(DRT, 198, "complete detail routing"); end(/* writeMetrics */ true); } if (VERBOSE > 0) { t.print(logger_); cout <<endl; } return 0; } Update FlexDR.cpp /* Authors: Lutong Wang and Bangqi Xu */ /* * Copyright (c) 2019, The Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <chrono> #include <fstream> #incluse <sstream> #include <boost/io/ios_state.hpp> #include "frProfileTask.h" #include "dr/FlexDR.h" #include "db/infra/frTime.h" #include "dr/FlexDR_graphics.h" #include <omp.h> using namespace std; using namespace fr; FlexDR::FlexDR(frDesign* designIn, Logger* loggerIn) : design_(designIn), logger_(loggerIn) { } FlexDR::~FlexDR() { } void FlexDR::setDebug(frDebugSettings* settings, odb::dbDatabase* db) { bool on = settings->debugDR; graphics_ = on && FlexDRGraphics::guiActive() ? std::make_unique<FlexDRGraphics>(settings, design_, db, logger_) : nullptr; } int FlexDRWorker::main() { using namespace std::chrono; high_resolution_clock::time_point t0 = high_resolution_clock::now(); if (VERBOSE > 1) { frBox scaledBox; stringstream ss; ss <<endl <<"start DR worker (BOX) " <<"( " << routeBox_.left() * 1.0 / getTech()->getDBUPerUU() <<" " << routeBox_.bottom() * 1.0 / getTech()->getDBUPerUU() <<" ) ( " << routeBox_.right() * 1.0 / getTech()->getDBUPerUU() <<" " << routeBox_.top() * 1.0 / getTech()->getDBUPerUU() <<" )" <<endl; cout <<ss.str() <<flush; } init(); high_resolution_clock::time_point t1 = high_resolution_clock::now(); route(); high_resolution_clock::time_point t2 = high_resolution_clock::now(); end(); high_resolution_clock::time_point t3 = high_resolution_clock::now(); duration<double> time_span0 = duration_cast<duration<double>>(t1 - t0); duration<double> time_span1 = duration_cast<duration<double>>(t2 - t1); duration<double> time_span2 = duration_cast<duration<double>>(t3 - t2); if (VERBOSE > 1) { stringstream ss; ss <<"time (INIT/ROUTE/POST) " <<time_span0.count() <<" " <<time_span1.count() <<" " <<time_span2.count() <<" " <<endl; cout <<ss.str() <<flush; } return 0; } int FlexDRWorker::main_mt() { ProfileTask profile("DR:main_mt"); using namespace std::chrono; high_resolution_clock::time_point t0 = high_resolution_clock::now(); if (VERBOSE > 1) { frBox scaledBox; stringstream ss; ss <<endl <<"start DR worker (BOX) " <<"( " << routeBox_.left() * 1.0 / getTech()->getDBUPerUU() <<" " << routeBox_.bottom() * 1.0 / getTech()->getDBUPerUU() <<" ) ( " << routeBox_.right() * 1.0 / getTech()->getDBUPerUU() <<" " << routeBox_.top() * 1.0 / getTech()->getDBUPerUU() <<" )" <<endl; cout <<ss.str() <<flush; } if (graphics_) { graphics_->startWorker(this); } init(); high_resolution_clock::time_point t1 = high_resolution_clock::now(); if (getFixMode() != 9) { route(); } else { route_queue(); } high_resolution_clock::time_point t2 = high_resolution_clock::now(); cleanup(); high_resolution_clock::time_point t3 = high_resolution_clock::now(); duration<double> time_span0 = duration_cast<duration<double>>(t1 - t0); duration<double> time_span1 = duration_cast<duration<double>>(t2 - t1); duration<double> time_span2 = duration_cast<duration<double>>(t3 - t2); if (VERBOSE > 1) { stringstream ss; ss <<"time (INIT/ROUTE/POST) " <<time_span0.count() <<" " <<time_span1.count() <<" " <<time_span2.count() <<" " <<endl; cout <<ss.str() <<flush; } return 0; } void FlexDR::initFromTA() { bool enableOutput = false; // initialize lists for (auto &net: getDesign()->getTopBlock()->getNets()) { for (auto &guide: net->getGuides()) { for (auto &connFig: guide->getRoutes()) { if (connFig->typeId() == frcPathSeg) { unique_ptr<frShape> ps = make_unique<frPathSeg>(*(static_cast<frPathSeg*>(connFig.get()))); frPoint bp, ep; static_cast<frPathSeg*>(ps.get())->getPoints(bp, ep); if (ep.x() - bp.x() + ep.y() - bp.y() == 1) { ; // skip TA dummy segment } else { net->addShape(std::move(ps)); } } else { cout <<"Error: initFromTA unsupported shape" <<endl; } } } } if (enableOutput) { for (auto &net: getDesign()->getTopBlock()->getNets()) { cout <<"net " <<net->getName() <<" has " <<net->getShapes().size() <<" shape" <<endl; } } } void FlexDR::initGCell2BoundaryPin() { bool enableOutput = false; // initiailize size frBox dieBox; getDesign()->getTopBlock()->getBoundaryBBox(dieBox); auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto &xgp = gCellPatterns.at(0); auto &ygp = gCellPatterns.at(1); auto tmpVec = vector<map<frNet*, set<pair<frPoint, frLayerNum> >, frBlockObjectComp> >((int)ygp.getCount()); gcell2BoundaryPin_ = vector<vector<map<frNet*, set<pair<frPoint, frLayerNum> >, frBlockObjectComp> > >((int)xgp.getCount(), tmpVec); for (auto &net: getDesign()->getTopBlock()->getNets()) { auto netPtr = net.get(); for (auto &guide: net->getGuides()) { for (auto &connFig: guide->getRoutes()) { if (connFig->typeId() == frcPathSeg) { auto ps = static_cast<frPathSeg*>(connFig.get()); frLayerNum layerNum; frPoint bp, ep; ps->getPoints(bp, ep); layerNum = ps->getLayerNum(); // skip TA dummy segment if (ep.x() - bp.x() + ep.y() - bp.y() == 1 || ep.x() - bp.x() + ep.y() - bp.y() == 0) { continue; } frPoint idx1, idx2; getDesign()->getTopBlock()->getGCellIdx(bp, idx1); getDesign()->getTopBlock()->getGCellIdx(ep, idx2); // update gcell2BoundaryPin // horizontal if (bp.y() == ep.y()) { int x1 = idx1.x(); int x2 = idx2.x(); int y = idx1.y(); for (auto x = x1; x <= x2; ++x) { frBox gcellBox; getDesign()->getTopBlock()->getGCellBox(frPoint(x, y), gcellBox); frCoord leftBound = gcellBox.left(); frCoord rightBound = gcellBox.right(); bool hasLeftBound = true; bool hasRightBound = true; if (bp.x() < leftBound) { hasLeftBound = true; } else { hasLeftBound = false; } if (ep.x() >= rightBound) { hasRightBound = true; } else { hasRightBound = false; } if (hasLeftBound) { frPoint boundaryPt(leftBound, bp.y()); gcell2BoundaryPin_[x][y][netPtr].insert(make_pair(boundaryPt, layerNum)); if (enableOutput) { cout << "init left boundary pin (" << boundaryPt.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ", " << boundaryPt.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ") at (" << x <<", " <<y <<") " << getTech()->getLayer(layerNum)->getName() <<" " << string((net == nullptr) ? "null" : net->getName()) <<"\n"; } } if (hasRightBound) { frPoint boundaryPt(rightBound, ep.y()); gcell2BoundaryPin_[x][y][netPtr].insert(make_pair(boundaryPt, layerNum)); if (enableOutput) { cout << "init right boundary pin (" << boundaryPt.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ", " << boundaryPt.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ") at (" << x <<", " <<y <<") " << getTech()->getLayer(layerNum)->getName() <<" " << string((net == nullptr) ? "null" : net->getName()) <<"\n"; } } } } else if (bp.x() == ep.x()) { int x = idx1.x(); int y1 = idx1.y(); int y2 = idx2.y(); for (auto y = y1; y <= y2; ++y) { frBox gcellBox; getDesign()->getTopBlock()->getGCellBox(frPoint(x, y), gcellBox); frCoord bottomBound = gcellBox.bottom(); frCoord topBound = gcellBox.top(); bool hasBottomBound = true; bool hasTopBound = true; if (bp.y() < bottomBound) { hasBottomBound = true; } else { hasBottomBound = false; } if (ep.y() >= topBound) { hasTopBound = true; } else { hasTopBound = false; } if (hasBottomBound) { frPoint boundaryPt(bp.x(), bottomBound); gcell2BoundaryPin_[x][y][netPtr].insert(make_pair(boundaryPt, layerNum)); if (enableOutput) { cout << "init bottom boundary pin (" << boundaryPt.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ", " << boundaryPt.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ") at (" << x <<", " <<y <<") " << getTech()->getLayer(layerNum)->getName() <<" " << string((net == nullptr) ? "null" : net->getName()) <<"\n"; } } if (hasTopBound) { frPoint boundaryPt(ep.x(), topBound); gcell2BoundaryPin_[x][y][netPtr].insert(make_pair(boundaryPt, layerNum)); if (enableOutput) { cout << "init top boundary pin (" << boundaryPt.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ", " << boundaryPt.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() << ") at (" << x <<", " <<y <<") " << getTech()->getLayer(layerNum)->getName() <<" " << string((net == nullptr) ? "null" : net->getName()) <<"\n"; } } } } else { cout << "Error: non-orthogonal pathseg in initGCell2BoundryPin\n"; } } } } } } frCoord FlexDR::init_via2viaMinLen_minimumcut1(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isH = (getDesign()->getTech()->getLayer(lNum)->getDir() == frPrefRoutingDirEnum::frcHorzPrefRoutingDir); bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); auto length1 = viaBox1.length(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); auto length2 = viaBox2.length(); for (auto &con: getDesign()->getTech()->getLayer(lNum)->getMinimumcutConstraints()) { if ((!con->hasLength() || (con->hasLength() && length1 > con->getLength())) && width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } if (isH) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.right() - 0 + 0 - viaBox1.left(), viaBox1.right() - 0 + 0 - cutBox2.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.top() - 0 + 0 - viaBox1.bottom(), viaBox1.top() - 0 + 0 - cutBox2.bottom())); } } // check via1cut to via2metal if ((!con->hasLength() || (con->hasLength() && length2 > con->getLength())) && width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } if (isH) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.right() - 0 + 0 - viaBox2.left(), viaBox2.right() - 0 + 0 - cutBox1.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.top() - 0 + 0 - viaBox2.bottom(), viaBox2.top() - 0 + 0 - cutBox1.bottom())); } } } return sol; } bool FlexDR::init_via2viaMinLen_minimumcut2(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { return true; } // skip if same-layer via if (viaDef1 == viaDef2) { return true; } bool sol = true; bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); for (auto &con: getDesign()->getTech()->getLayer(lNum)->getMinimumcutConstraints()) { if (con->hasLength()) { continue; } // check via2cut to via1metal if (width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { // has length rule if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } sol = false; break; } // check via1cut to via2metal if (width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } sol = false; break; } } return sol; } frCoord FlexDR::init_via2viaMinLen_minSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { //cout <<"hehehehehe" <<endl; return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isH = (getDesign()->getTech()->getLayer(lNum)->getDir() == frPrefRoutingDirEnum::frcHorzPrefRoutingDir); frCoord defaultWidth = getDesign()->getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef1); frBox viaBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isH ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isH ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frVia via2(viaDef2); frBox viaBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } auto width2 = viaBox2.width(); bool isVia2Fat = isH ? (viaBox2.top() - viaBox2.bottom() > defaultWidth) : (viaBox2.right() - viaBox2.left() > defaultWidth); auto prl2 = isH ? (viaBox2.top() - viaBox2.bottom()) : (viaBox2.right() - viaBox2.left()); frCoord reqDist = 0; if (isVia1Fat && isVia2Fat) { auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), min(prl1, prl2)); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, min(prl1, prl2)); } } if (isH) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += max((viaBox2.right() - 0), (0 - viaBox2.left())); } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += max((viaBox2.top() - 0), (0 - viaBox2.bottom())); } sol = max(sol, reqDist); } // check min len in layer2 if two vias are in same layer if (viaDef1 != viaDef2) { return sol; } if (viaDef1->getLayer1Num() == lNum) { via1.getLayer2BBox(viaBox1); lNum = lNum + 2; } else { via1.getLayer1BBox(viaBox1); lNum = lNum - 2; } width1 = viaBox1.width(); prl1 = isH ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); reqDist = 0; auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, prl1); } } if (isH) { reqDist += (viaBox1.right() - 0) + (0 - viaBox1.left()); } else { reqDist += (viaBox1.top() - 0) + (0 - viaBox1.bottom()); } sol = max(sol, reqDist); return sol; } void FlexDR::init_via2viaMinLen() { bool enableOutput = false; //bool enableOutput = true; auto bottomLayerNum = getDesign()->getTech()->getBottomLayerNum(); auto topLayerNum = getDesign()->getTech()->getTopLayerNum(); for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2viaMinLenTmp(4, 0); vector<bool> via2viaZeroLen(4, true); via2viaMinLen_.push_back(make_pair(via2viaMinLenTmp, via2viaZeroLen)); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } (via2viaMinLen_[i].first)[0] = max((via2viaMinLen_[i].first)[0], init_via2viaMinLen_minSpc(lNum, downVia, downVia)); (via2viaMinLen_[i].first)[1] = max((via2viaMinLen_[i].first)[1], init_via2viaMinLen_minSpc(lNum, downVia, upVia)); (via2viaMinLen_[i].first)[2] = max((via2viaMinLen_[i].first)[2], init_via2viaMinLen_minSpc(lNum, upVia, downVia)); (via2viaMinLen_[i].first)[3] = max((via2viaMinLen_[i].first)[3], init_via2viaMinLen_minSpc(lNum, upVia, upVia)); if (enableOutput) { logger_->info(DRT, 188, "initVia2ViaMinLen_minSpc {}" " (d2d, d2u, u2d, u2u) = ({}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), (via2viaMinLen_[i].first)[0], (via2viaMinLen_[i].first)[1], (via2viaMinLen_[i].first)[2], (via2viaMinLen_[i].first)[3]); } i++; } // check minimumcut i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } vector<frCoord> via2viaMinLenTmp(4, 0); (via2viaMinLen_[i].first)[0] = max((via2viaMinLen_[i].first)[0], init_via2viaMinLen_minimumcut1(lNum, downVia, downVia)); (via2viaMinLen_[i].first)[1] = max((via2viaMinLen_[i].first)[1], init_via2viaMinLen_minimumcut1(lNum, downVia, upVia)); (via2viaMinLen_[i].first)[2] = max((via2viaMinLen_[i].first)[2], init_via2viaMinLen_minimumcut1(lNum, upVia, downVia)); (via2viaMinLen_[i].first)[3] = max((via2viaMinLen_[i].first)[3], init_via2viaMinLen_minimumcut1(lNum, upVia, upVia)); (via2viaMinLen_[i].second)[0] = (via2viaMinLen_[i].second)[0] && init_via2viaMinLen_minimumcut2(lNum, downVia, downVia); (via2viaMinLen_[i].second)[1] = (via2viaMinLen_[i].second)[1] && init_via2viaMinLen_minimumcut2(lNum, downVia, upVia); (via2viaMinLen_[i].second)[2] = (via2viaMinLen_[i].second)[2] && init_via2viaMinLen_minimumcut2(lNum, upVia, downVia); (via2viaMinLen_[i].second)[3] = (via2viaMinLen_[i].second)[3] && init_via2viaMinLen_minimumcut2(lNum, upVia, upVia); if (enableOutput) { logger_->info(DRT, 189, "initVia2ViaMinLen_minimumcut {}" " (d2d, d2u, u2d, u2u) = ({}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), (via2viaMinLen_[i].first)[0], (via2viaMinLen_[i].first)[1], (via2viaMinLen_[i].first)[2], (via2viaMinLen_[i].first)[3]); logger_->info(DRT, 190, "initVia2ViaMinLen_minimumcut {}" " zerolen (b, b, b, b) = ({}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), (via2viaMinLen_[i].second)[0], (via2viaMinLen_[i].second)[1], (via2viaMinLen_[i].second)[2], (via2viaMinLen_[i].second)[3]); } i++; } } frCoord FlexDR::init_via2viaMinLenNew_minimumcut1(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); auto length1 = viaBox1.length(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); auto length2 = viaBox2.length(); for (auto &con: getDesign()->getTech()->getLayer(lNum)->getMinimumcutConstraints()) { // check via2cut to via1metal // no length OR metal1 shape satisfies --> check via2 if ((!con->hasLength() || (con->hasLength() && length1 > con->getLength())) && width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } if (isCurrDirX) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.right() - 0 + 0 - viaBox1.left(), viaBox1.right() - 0 + 0 - cutBox2.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.top() - 0 + 0 - viaBox1.bottom(), viaBox1.top() - 0 + 0 - cutBox2.bottom())); } } // check via1cut to via2metal if ((!con->hasLength() || (con->hasLength() && length2 > con->getLength())) && width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } if (isCurrDirX) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.right() - 0 + 0 - viaBox2.left(), viaBox2.right() - 0 + 0 - cutBox1.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.top() - 0 + 0 - viaBox2.bottom(), viaBox2.top() - 0 + 0 - cutBox1.bottom())); } } } return sol; } frCoord FlexDR::init_via2viaMinLenNew_minSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getDesign()->getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef1); frBox viaBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frVia via2(viaDef2); frBox viaBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } auto width2 = viaBox2.width(); bool isVia2Fat = isCurrDirX ? (viaBox2.top() - viaBox2.bottom() > defaultWidth) : (viaBox2.right() - viaBox2.left() > defaultWidth); auto prl2 = isCurrDirX ? (viaBox2.top() - viaBox2.bottom()) : (viaBox2.right() - viaBox2.left()); frCoord reqDist = 0; if (isVia1Fat && isVia2Fat) { auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), min(prl1, prl2)); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, min(prl1, prl2)); } } if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += max((viaBox2.right() - 0), (0 - viaBox2.left())); } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += max((viaBox2.top() - 0), (0 - viaBox2.bottom())); } sol = max(sol, reqDist); } // check min len in layer2 if two vias are in same layer if (viaDef1 != viaDef2) { return sol; } if (viaDef1->getLayer1Num() == lNum) { via1.getLayer2BBox(viaBox1); lNum = lNum + 2; } else { via1.getLayer1BBox(viaBox1); lNum = lNum - 2; } width1 = viaBox1.width(); prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); reqDist = 0; auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, prl1); } } if (isCurrDirX) { reqDist += (viaBox1.right() - 0) + (0 - viaBox1.left()); } else { reqDist += (viaBox1.top() - 0) + (0 - viaBox1.bottom()); } sol = max(sol, reqDist); return sol; } frCoord FlexDR::init_via2viaMinLenNew_cutSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } via1.getCutBBox(cutBox1); frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } via2.getCutBBox(cutBox2); // same layer (use samenet rule if exist, otherwise use diffnet rule) if (viaDef1->getCutLayerNum() == viaDef2->getCutLayerNum()) { auto samenetCons = getDesign()->getTech()->getLayer(viaDef1->getCutLayerNum())->getCutSpacing(true); auto diffnetCons = getDesign()->getTech()->getLayer(viaDef1->getCutLayerNum())->getCutSpacing(false); if (!samenetCons.empty()) { // check samenet spacing rule if exists for (auto con: samenetCons) { if (con == nullptr) { continue; } // filter rule, assuming default via will never trigger cutArea if (con->hasSecondLayer() || con->isAdjacentCuts() || con->isParallelOverlap() || con->isArea() || !con->hasSameNet()) { continue; } auto reqSpcVal = con->getCutSpacing(); if (!con->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } sol = max(sol, reqSpcVal); } } else { // check diffnet spacing rule // filter rule, assuming default via will never trigger cutArea for (auto con: diffnetCons) { if (con == nullptr) { continue; } if (con->hasSecondLayer() || con->isAdjacentCuts() || con->isParallelOverlap() || con->isArea() || con->hasSameNet()) { continue; } auto reqSpcVal = con->getCutSpacing(); if (!con->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } sol = max(sol, reqSpcVal); } } // TODO: diff layer } else { auto layerNum1 = viaDef1->getCutLayerNum(); auto layerNum2 = viaDef2->getCutLayerNum(); frCutSpacingConstraint* samenetCon = nullptr; if (getDesign()->getTech()->getLayer(layerNum1)->hasInterLayerCutSpacing(layerNum2, true)) { samenetCon = getDesign()->getTech()->getLayer(layerNum1)->getInterLayerCutSpacing(layerNum2, true); } if (getDesign()->getTech()->getLayer(layerNum2)->hasInterLayerCutSpacing(layerNum1, true)) { if (samenetCon) { cout <<"Warning: duplicate diff layer samenet cut spacing, skipping cut spacing from " <<layerNum2 <<" to " <<layerNum1 <<endl; } else { samenetCon = getDesign()->getTech()->getLayer(layerNum2)->getInterLayerCutSpacing(layerNum1, true); } } if (samenetCon == nullptr) { if (getDesign()->getTech()->getLayer(layerNum1)->hasInterLayerCutSpacing(layerNum2, false)) { samenetCon = getDesign()->getTech()->getLayer(layerNum1)->getInterLayerCutSpacing(layerNum2, false); } if (getDesign()->getTech()->getLayer(layerNum2)->hasInterLayerCutSpacing(layerNum1, false)) { if (samenetCon) { cout <<"Warning: duplicate diff layer diffnet cut spacing, skipping cut spacing from " <<layerNum2 <<" to " <<layerNum1 <<endl; } else { samenetCon = getDesign()->getTech()->getLayer(layerNum2)->getInterLayerCutSpacing(layerNum1, false); } } } if (samenetCon) { // filter rule, assuming default via will never trigger cutArea auto reqSpcVal = samenetCon->getCutSpacing(); if (reqSpcVal == 0) { ; } else { if (!samenetCon->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } } sol = max(sol, reqSpcVal); } } return sol; } void FlexDR::init_via2viaMinLenNew() { bool enableOutput = false; //bool enableOutput = true; auto bottomLayerNum = getDesign()->getTech()->getBottomLayerNum(); auto topLayerNum = getDesign()->getTech()->getTopLayerNum(); for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2viaMinLenTmp(8, 0); via2viaMinLenNew_.push_back(via2viaMinLenTmp); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew_[i][0] = max(via2viaMinLenNew_[i][0], init_via2viaMinLenNew_minSpc(lNum, downVia, downVia, false)); via2viaMinLenNew_[i][1] = max(via2viaMinLenNew_[i][1], init_via2viaMinLenNew_minSpc(lNum, downVia, downVia, true )); via2viaMinLenNew_[i][2] = max(via2viaMinLenNew_[i][2], init_via2viaMinLenNew_minSpc(lNum, downVia, upVia, false)); via2viaMinLenNew_[i][3] = max(via2viaMinLenNew_[i][3], init_via2viaMinLenNew_minSpc(lNum, downVia, upVia, true )); via2viaMinLenNew_[i][4] = max(via2viaMinLenNew_[i][4], init_via2viaMinLenNew_minSpc(lNum, upVia, downVia, false)); via2viaMinLenNew_[i][5] = max(via2viaMinLenNew_[i][5], init_via2viaMinLenNew_minSpc(lNum, upVia, downVia, true )); via2viaMinLenNew_[i][6] = max(via2viaMinLenNew_[i][6], init_via2viaMinLenNew_minSpc(lNum, upVia, upVia, false)); via2viaMinLenNew_[i][7] = max(via2viaMinLenNew_[i][7], init_via2viaMinLenNew_minSpc(lNum, upVia, upVia, true )); if (enableOutput) { logger_->info(DRT, 191, "initVia2ViaMinLenNew_minSpc {} " "(d2d-x, d2d-y, d2u-x, d2u-y, u2d-x, u2d-y, u2u-x, u2u-y) " "= ({}, {}, {}, {}, {}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), via2viaMinLenNew_[i][0], via2viaMinLenNew_[i][1], via2viaMinLenNew_[i][2], via2viaMinLenNew_[i][3], via2viaMinLenNew_[i][4], via2viaMinLenNew_[i][5], via2viaMinLenNew_[i][6], via2viaMinLenNew_[i][7]); } i++; } // check minimumcut i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew_[i][0] = max(via2viaMinLenNew_[i][0], init_via2viaMinLenNew_minimumcut1(lNum, downVia, downVia, false)); via2viaMinLenNew_[i][1] = max(via2viaMinLenNew_[i][1], init_via2viaMinLenNew_minimumcut1(lNum, downVia, downVia, true )); via2viaMinLenNew_[i][2] = max(via2viaMinLenNew_[i][2], init_via2viaMinLenNew_minimumcut1(lNum, downVia, upVia, false)); via2viaMinLenNew_[i][3] = max(via2viaMinLenNew_[i][3], init_via2viaMinLenNew_minimumcut1(lNum, downVia, upVia, true )); via2viaMinLenNew_[i][4] = max(via2viaMinLenNew_[i][4], init_via2viaMinLenNew_minimumcut1(lNum, upVia, downVia, false)); via2viaMinLenNew_[i][5] = max(via2viaMinLenNew_[i][5], init_via2viaMinLenNew_minimumcut1(lNum, upVia, downVia, true )); via2viaMinLenNew_[i][6] = max(via2viaMinLenNew_[i][6], init_via2viaMinLenNew_minimumcut1(lNum, upVia, upVia, false)); via2viaMinLenNew_[i][7] = max(via2viaMinLenNew_[i][7], init_via2viaMinLenNew_minimumcut1(lNum, upVia, upVia, true )); if (enableOutput) { logger_->info(DRT, 192, "initVia2ViaMinLenNew_minimumcut {}" " (d2d-x, d2d-y, d2u-x, d2u-y, u2d-x, u2d-y, u2u-x, u2u-y) " "= ({}, {}, {}, {}, {}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), via2viaMinLenNew_[i][0], via2viaMinLenNew_[i][1], via2viaMinLenNew_[i][2], via2viaMinLenNew_[i][3], via2viaMinLenNew_[i][4], via2viaMinLenNew_[i][5], via2viaMinLenNew_[i][6], via2viaMinLenNew_[i][7]); } i++; } // check cut spacing i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew_[i][0] = max(via2viaMinLenNew_[i][0], init_via2viaMinLenNew_cutSpc(lNum, downVia, downVia, false)); via2viaMinLenNew_[i][1] = max(via2viaMinLenNew_[i][1], init_via2viaMinLenNew_cutSpc(lNum, downVia, downVia, true )); via2viaMinLenNew_[i][2] = max(via2viaMinLenNew_[i][2], init_via2viaMinLenNew_cutSpc(lNum, downVia, upVia, false)); via2viaMinLenNew_[i][3] = max(via2viaMinLenNew_[i][3], init_via2viaMinLenNew_cutSpc(lNum, downVia, upVia, true )); via2viaMinLenNew_[i][4] = max(via2viaMinLenNew_[i][4], init_via2viaMinLenNew_cutSpc(lNum, upVia, downVia, false)); via2viaMinLenNew_[i][5] = max(via2viaMinLenNew_[i][5], init_via2viaMinLenNew_cutSpc(lNum, upVia, downVia, true )); via2viaMinLenNew_[i][6] = max(via2viaMinLenNew_[i][6], init_via2viaMinLenNew_cutSpc(lNum, upVia, upVia, false)); via2viaMinLenNew_[i][7] = max(via2viaMinLenNew_[i][7], init_via2viaMinLenNew_cutSpc(lNum, upVia, upVia, true )); if (enableOutput) { logger_->info(DRT, 193, "initVia2ViaMinLenNew_cutSpc {}" " (d2d-x, d2d-y, d2u-x, d2u-y, u2d-x, u2d-y, u2u-x, u2u-y) " "= ({}, {}, {}, {}, {}, {}, {}, {})", getDesign()->getTech()->getLayer(lNum)->getName(), via2viaMinLenNew_[i][0], via2viaMinLenNew_[i][1], via2viaMinLenNew_[i][2], via2viaMinLenNew_[i][3], via2viaMinLenNew_[i][4], via2viaMinLenNew_[i][5], via2viaMinLenNew_[i][6], via2viaMinLenNew_[i][7]); } i++; } } void FlexDR::init_halfViaEncArea() { auto bottomLayerNum = getDesign()->getTech()->getBottomLayerNum(); auto topLayerNum = getDesign()->getTech()->getTopLayerNum(); for (int i = bottomLayerNum; i <= topLayerNum; i++) { if (getDesign()->getTech()->getLayer(i)->getType() != frLayerTypeEnum::ROUTING) { continue; } if (i + 1 <= topLayerNum && getDesign()->getTech()->getLayer(i + 1)->getType() == frLayerTypeEnum::CUT) { auto viaDef = getTech()->getLayer(i + 1)->getDefaultViaDef(); frVia via(viaDef); frBox layer1Box; frBox layer2Box; via.getLayer1BBox(layer1Box); via.getLayer2BBox(layer2Box); auto layer1HalfArea = layer1Box.width() * layer1Box.length() / 2; auto layer2HalfArea = layer2Box.width() * layer2Box.length() / 2; halfViaEncArea_.push_back(make_pair(layer1HalfArea, layer2HalfArea)); } else { halfViaEncArea_.push_back(make_pair(0,0)); } } } frCoord FlexDR::init_via2turnMinLen_minSpc(frLayerNum lNum, frViaDef* viaDef, bool isCurrDirY) { if (!viaDef) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getDesign()->getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef); frBox viaBox1; if (viaDef->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frCoord reqDist = 0; if (isVia1Fat) { auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, defaultWidth), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, defaultWidth, prl1); } } if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += defaultWidth; } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += defaultWidth; } sol = max(sol, reqDist); } return sol; } frCoord FlexDR::init_via2turnMinLen_minStp(frLayerNum lNum, frViaDef* viaDef, bool isCurrDirY) { if (!viaDef) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getDesign()->getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef); frBox viaBox1; if (viaDef->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); frCoord reqDist = 0; if (isVia1Fat) { auto con = getDesign()->getTech()->getLayer(lNum)->getMinStepConstraint(); if (con && con->hasMaxEdges()) { // currently only consider maxedge violation reqDist = con->getMinStepLength(); if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += defaultWidth; } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += defaultWidth; } sol = max(sol, reqDist); } } return sol; } void FlexDR::init_via2turnMinLen() { bool enableOutput = false; //bool enableOutput = true; auto bottomLayerNum = getDesign()->getTech()->getBottomLayerNum(); auto topLayerNum = getDesign()->getTech()->getTopLayerNum(); for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2turnMinLenTmp(4, 0); via2turnMinLen_.push_back(via2turnMinLenTmp); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2turnMinLen_[i][0] = max(via2turnMinLen_[i][0], init_via2turnMinLen_minSpc(lNum, downVia, false)); via2turnMinLen_[i][1] = max(via2turnMinLen_[i][1], init_via2turnMinLen_minSpc(lNum, downVia, true)); via2turnMinLen_[i][2] = max(via2turnMinLen_[i][2], init_via2turnMinLen_minSpc(lNum, upVia, false)); via2turnMinLen_[i][3] = max(via2turnMinLen_[i][3], init_via2turnMinLen_minSpc(lNum, upVia, true)); if (enableOutput) { cout <<"initVia2TurnMinLen_minSpc " <<getDesign()->getTech()->getLayer(lNum)->getName() <<" (down->x->y, down->y->x, up->x->y, up->y->x) = (" <<via2turnMinLen_[i][0] <<", " <<via2turnMinLen_[i][1] <<", " <<via2turnMinLen_[i][2] <<", " <<via2turnMinLen_[i][3] <<")" <<endl; } i++; } // check minstep i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getDesign()->getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getDesign()->getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getDesign()->getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getDesign()->getTech()->getTopLayerNum() >= lNum + 1) { upVia = getDesign()->getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } vector<frCoord> via2turnMinLenTmp(4, 0); via2turnMinLen_[i][0] = max(via2turnMinLen_[i][0], init_via2turnMinLen_minStp(lNum, downVia, false)); via2turnMinLen_[i][1] = max(via2turnMinLen_[i][1], init_via2turnMinLen_minStp(lNum, downVia, true)); via2turnMinLen_[i][2] = max(via2turnMinLen_[i][2], init_via2turnMinLen_minStp(lNum, upVia, false)); via2turnMinLen_[i][3] = max(via2turnMinLen_[i][3], init_via2turnMinLen_minStp(lNum, upVia, true)); if (enableOutput) { cout <<"initVia2TurnMinLen_minstep " <<getDesign()->getTech()->getLayer(lNum)->getName() <<" (down->x->y, down->y->x, up->x->y, up->y->x) = (" <<via2turnMinLen_[i][0] <<", " <<via2turnMinLen_[i][1] <<", " <<via2turnMinLen_[i][2] <<", " <<via2turnMinLen_[i][3] <<")" <<endl; } i++; } } void FlexDR::init() { ProfileTask profile("DR:init"); frTime t; if (VERBOSE > 0) { logger_->info(DRT, 187, "start routing data preparation"); } initGCell2BoundaryPin(); getRegionQuery()->initDRObj(getTech()->getLayers().size()); // first init in postProcess init_halfViaEncArea(); init_via2viaMinLen(); init_via2viaMinLenNew(); init_via2turnMinLen(); if (VERBOSE > 0) { t.print(logger_); } } void FlexDR::removeGCell2BoundaryPin() { gcell2BoundaryPin_.clear(); gcell2BoundaryPin_.shrink_to_fit(); } map<frNet*, set<pair<frPoint, frLayerNum> >, frBlockObjectComp> FlexDR::initDR_mergeBoundaryPin(int startX, int startY, int size, const frBox &routeBox) { map<frNet*, set<pair<frPoint, frLayerNum> >, frBlockObjectComp> bp; auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto &xgp = gCellPatterns.at(0); auto &ygp = gCellPatterns.at(1); for (int i = startX; i < (int)xgp.getCount() && i < startX + size; i++) { for (int j = startY; j < (int)ygp.getCount() && j < startY + size; j++) { auto &currBp = gcell2BoundaryPin_[i][j]; for (auto &[net, s]: currBp) { for (auto &[pt, lNum]: s) { if (pt.x() == routeBox.left() || pt.x() == routeBox.right() || pt.y() == routeBox.bottom() || pt.y() == routeBox.top()) { bp[net].insert(make_pair(pt, lNum)); } } } } } return bp; } void FlexDR::initDR(int size, bool enableDRC) { bool TEST = false; // bool TEST = true; //FlexGridGraph gg(getTech(), getDesign()); ////frBox testBBox(225000, 228100, 228000, 231100); // net1702 in ispd19_test1 //frBox testBBox(0, 0, 2000, 2000); // net1702 in ispd19_test1 ////gg.setBBox(testBBox); //gg.init(testBBox); //gg.print(); //exit(1); frTime t; if (VERBOSE > 0) { cout <<endl <<"start initial detail routing ..." <<endl; } frBox dieBox; getDesign()->getTopBlock()->getBoundaryBBox(dieBox); auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto &xgp = gCellPatterns.at(0); auto &ygp = gCellPatterns.at(1); int cnt = 0; int tot = (((int)xgp.getCount() - 1) / size + 1) * (((int)ygp.getCount() - 1) / size + 1); int prev_perc = 0; bool isExceed = false; int numQuickMarkers = 0; if (TEST) { //FlexDRWorker worker(getDesign()); FlexDRWorker worker(this, logger_); //frBox routeBox; //routeBox.set(0*2000, 0*2000, 1*2000, 1*2000); //frCoord xl = 21 * 2000; //frCoord yl = 42 * 2000; frCoord xl = 241.92 * 2000; frCoord yl = 241.92 * 2000; //frCoord xh = 129 * 2000; //frCoord yh = 94.05 * 2000; frPoint idx; getDesign()->getTopBlock()->getGCellIdx(frPoint(xl, yl), idx); if (VERBOSE > 1) { cout <<"(i,j) = (" <<idx.x() <<", " <<idx.y() <<")" <<endl; } //getDesign()->getTopBlock()->getGCellBox(idx, routeBox); frBox routeBox1; getDesign()->getTopBlock()->getGCellBox(frPoint(idx.x(), idx.y()), routeBox1); frBox routeBox2; getDesign()->getTopBlock()->getGCellBox(frPoint(min((int)xgp.getCount() - 1, idx.x() + size-1), min((int)ygp.getCount(), idx.y() + size-1)), routeBox2); frBox routeBox(routeBox1.left(), routeBox1.bottom(), routeBox2.right(), routeBox2.top()); auto bp = initDR_mergeBoundaryPin(idx.x(), idx.y(), size, routeBox); //routeBox.set(129*2000, 94.05*2000, 132*2000, 96.9*2000); worker.setRouteBox(routeBox); frBox extBox; routeBox.bloat(2000, extBox); frBox drcBox; routeBox.bloat(500, drcBox); worker.setRouteBox(routeBox); worker.setExtBox(extBox); worker.setDrcBox(drcBox); worker.setFollowGuide(false); worker.setCost(DRCCOST, 0, 0, 0); //int i = (129 * 2000 - xgp.getStartCoord()) / xgp.getSpacing(); //int j = (94.05 * 2000 - ygp.getStartCoord()) / ygp.getSpacing(); //worker.setDRIter(0, gcell2BoundaryPin[idx.x()][idx.y()]); worker.setDRIter(0, bp); worker.setEnableDRC(enableDRC); //worker.setTest(true); worker.main(); cout <<"done" <<endl <<flush; } else { vector<unique_ptr<FlexDRWorker> > uworkers; int batchStepX, batchStepY; getBatchInfo(batchStepX, batchStepY); vector<vector<vector<unique_ptr<FlexDRWorker> > > > workers(batchStepX * batchStepY); int xIdx = 0, yIdx = 0; // sequential init for (int i = 0; i < (int)xgp.getCount(); i += size) { for (int j = 0; j < (int)ygp.getCount(); j += size) { auto worker = make_unique<FlexDRWorker>(this, logger_); frBox routeBox1; getDesign()->getTopBlock()->getGCellBox(frPoint(i, j), routeBox1); frBox routeBox2; getDesign()->getTopBlock()->getGCellBox(frPoint(min((int)xgp.getCount() - 1, i + size-1), min((int)ygp.getCount(), j + size-1)), routeBox2); //frBox routeBox; frBox routeBox(routeBox1.left(), routeBox1.bottom(), routeBox2.right(), routeBox2.top()); frBox extBox; routeBox.bloat(MTSAFEDIST, extBox); frBox drcBox; routeBox.bloat(DRCSAFEDIST, drcBox); worker->setRouteBox(routeBox); worker->setExtBox(extBox); worker->setDrcBox(drcBox); auto bp = initDR_mergeBoundaryPin(i, j, size, routeBox); worker->setDRIter(0, bp); // set boundary pin worker->setEnableDRC(enableDRC); worker->setFollowGuide(false); //worker->setFollowGuide(true); worker->setCost(DRCCOST, 0, 0, 0); // int workerIdx = xIdx * batchSizeY + yIdx; int batchIdx = (xIdx % batchStepX) * batchStepY + yIdx % batchStepY; // workers[batchIdx][workerIdx] = worker; if (workers[batchIdx].empty() || (int)workers[batchIdx].back().size() >= BATCHSIZE) { workers[batchIdx].push_back(vector<unique_ptr<FlexDRWorker> >()); } workers[batchIdx].back().push_back(std::move(worker)); yIdx++; } yIdx = 0; xIdx++; } omp_set_num_threads(MAX_THREADS); // parallel execution for (auto &workerBatch: workers) { for (auto &workersInBatch: workerBatch) { // multi thread #pragma omp parallel for schedule(dynamic) for (int i = 0; i < (int)workersInBatch.size(); i++) { workersInBatch[i]->main_mt(); #pragma omp critical { cnt++; if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc < 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; //if (true) { if (isExceed) { if (enableDRC) { cout <<" completing " <<prev_perc <<"% with " <<getDesign()->getTopBlock()->getNumMarkers() <<" violations" <<endl; } else { cout <<" completing " <<prev_perc <<"% with " <<numQuickMarkers <<" quick violations" <<endl; } cout <<" " <<t <<endl <<flush; } } } } } // single thread for (int i = 0; i < (int)workersInBatch.size(); i++) { workersInBatch[i]->end(); } workersInBatch.clear(); } } checkConnectivity(); } if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc >= 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; //if (true) { if (isExceed) { if (enableDRC) { cout <<" completing " <<prev_perc <<"% with " <<getDesign()->getTopBlock()->getNumMarkers() <<" violations" <<endl; } else { cout <<" completing " <<prev_perc <<"% with " <<numQuickMarkers <<" quick violations" <<endl; } cout <<" " <<t <<endl <<flush; } } } removeGCell2BoundaryPin(); numViols_.push_back(getDesign()->getTopBlock()->getNumMarkers()); if (VERBOSE > 0) { if (enableDRC) { logger_->info(DRT, 196, " number of violations = {}", getDesign()->getTopBlock()->getNumMarkers()); } else { logger_->info(DRT, 197, " number of quick violations = {}", numQuickMarkers); } t.print(logger_); cout <<flush; } } void FlexDR::getBatchInfo(int &batchStepX, int &batchStepY) { batchStepX = 2; batchStepY = 2; } void FlexDR::searchRepair(int iter, int size, int offset, int mazeEndIter, frUInt4 workerDRCCost, frUInt4 workerMarkerCost, frUInt4 workerMarkerBloatWidth, frUInt4 workerMarkerBloatDepth, bool enableDRC, int ripupMode, bool followGuide, int fixMode, bool TEST) { std::string profile_name("DR:searchRepair"); profile_name += std::to_string(iter); ProfileTask profile(profile_name.c_str()); if (iter > END_ITERATION) { return; } if (ripupMode != 1 && getDesign()->getTopBlock()->getMarkers().size() == 0) { return; } frTime t; //bool TEST = false; //bool TEST = true; if (VERBOSE > 0) { string suffix; if (iter == 1 || (iter > 20 && iter % 10 == 1)) { suffix = "st"; } else if (iter == 2 || (iter > 20 && iter % 10 == 2)) { suffix = "nd"; } else if (iter == 3 || (iter > 20 && iter % 10 == 3)) { suffix = "rd"; } else { suffix = "th"; } logger_->info(DRT, 195, "start {}{} optimization iteration ...", iter, suffix); } if (graphics_) { graphics_->startIter(iter); } frBox dieBox; getDesign()->getTopBlock()->getBoundaryBBox(dieBox); auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto &xgp = gCellPatterns.at(0); auto &ygp = gCellPatterns.at(1); int numQuickMarkers = 0; int clipSize = size; int cnt = 0; int tot = (((int)xgp.getCount() - 1 - offset) / clipSize + 1) * (((int)ygp.getCount() - 1 - offset) / clipSize + 1); int prev_perc = 0; bool isExceed = false; if (TEST) { cout <<"search and repair test mode" <<endl <<flush; //FlexDRWorker worker(getDesign()); FlexDRWorker worker(this, logger_); frBox routeBox; //frCoord xl = 148.5 * 2000; //frCoord yl = 570 * 2000; //frPoint idx; //getDesign()->getTopBlock()->getGCellIdx(frPoint(xl, yl), idx); //if (VERBOSE > 1) { // cout <<"(i,j) = (" <<idx.x() <<", " <<idx.y() <<")" <<endl; //} //getDesign()->getTopBlock()->getGCellBox(idx, routeBox); //routeBox.set(156*2000, 108.3*2000, 177*2000, 128.25*2000); // routeBox.set(175*2000, 3.5*2000, 185*2000, 13.5*2000); // routeBox.set(0*2000, 0*2000, 200*2000, 200*2000); // routeBox.set(420*1000, 816.1*1000, 441*1000, 837.1*1000); routeBox.set(441*1000, 816.1*1000, 462*1000, 837.1*1000); worker.setRouteBox(routeBox); frBox extBox; frBox drcBox; routeBox.bloat(2000, extBox); routeBox.bloat(500, drcBox); worker.setRouteBox(routeBox); worker.setExtBox(extBox); worker.setDrcBox(drcBox); worker.setMazeEndIter(mazeEndIter); worker.setTest(true); //worker.setQuickDRCTest(true); //worker.setDRCTest(true); worker.setDRIter(iter); if (!iter) { // set boundary pin (need to manulally calculate for test mode) auto bp = initDR_mergeBoundaryPin(147, 273, size, routeBox); worker.setDRIter(0, bp); } worker.setEnableDRC(enableDRC); worker.setRipupMode(ripupMode); worker.setFollowGuide(followGuide); worker.setFixMode(fixMode); //worker.setNetOrderingMode(netOrderingMode); worker.setCost(workerDRCCost, workerMarkerCost, workerMarkerBloatWidth, workerMarkerBloatDepth); worker.main_mt(); numQuickMarkers += worker.getNumQuickMarkers(); cout <<"done" <<endl <<flush; } else { vector<unique_ptr<FlexDRWorker> > uworkers; int batchStepX, batchStepY; getBatchInfo(batchStepX, batchStepY); vector<vector<vector<unique_ptr<FlexDRWorker> > > > workers(batchStepX * batchStepY); int xIdx = 0, yIdx = 0; for (int i = offset; i < (int)xgp.getCount(); i += clipSize) { for (int j = offset; j < (int)ygp.getCount(); j += clipSize) { auto worker = make_unique<FlexDRWorker>(this, logger_); frBox routeBox1; getDesign()->getTopBlock()->getGCellBox(frPoint(i, j), routeBox1); frBox routeBox2; const int max_i = min((int)xgp.getCount() - 1, i + clipSize-1); const int max_j = min((int)ygp.getCount(), j + clipSize-1); getDesign()->getTopBlock()->getGCellBox(frPoint(max_i, max_j), routeBox2); frBox routeBox(routeBox1.left(), routeBox1.bottom(), routeBox2.right(), routeBox2.top()); frBox extBox; frBox drcBox; routeBox.bloat(MTSAFEDIST, extBox); routeBox.bloat(DRCSAFEDIST, drcBox); worker->setRouteBox(routeBox); worker->setExtBox(extBox); worker->setDrcBox(drcBox); worker->setGCellBox(frBox(i, j, max_i, max_j)); worker->setMazeEndIter(mazeEndIter); worker->setDRIter(iter); if (!iter) { // if (routeBox.left() == 441000 && routeBox.bottom() == 816100) { // cout << "@@@ debug: " << i << " " << j << endl; // } // set boundary pin auto bp = initDR_mergeBoundaryPin(i, j, size, routeBox); worker->setDRIter(0, bp); } worker->setEnableDRC(enableDRC); worker->setRipupMode(ripupMode); worker->setFollowGuide(followGuide); worker->setFixMode(fixMode); // TODO: only pass to relevant workers worker->setGraphics(graphics_.get()); worker->setCost(workerDRCCost, workerMarkerCost, workerMarkerBloatWidth, workerMarkerBloatDepth); int batchIdx = (xIdx % batchStepX) * batchStepY + yIdx % batchStepY; if (workers[batchIdx].empty() || (int)workers[batchIdx].back().size() >= BATCHSIZE) { workers[batchIdx].push_back(vector<unique_ptr<FlexDRWorker>>()); } workers[batchIdx].back().push_back(std::move(worker)); yIdx++; } yIdx = 0; xIdx++; } omp_set_num_threads(MAX_THREADS); // parallel execution for (auto &workerBatch: workers) { ProfileTask profile("DR:checkerboard"); for (auto &workersInBatch: workerBatch) { { ProfileTask profile("DR:batch"); // multi thread #pragma omp parallel for schedule(dynamic) for (int i = 0; i < (int)workersInBatch.size(); i++) { workersInBatch[i]->main_mt(); #pragma omp critical { cnt++; if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc < 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; //if (true) { if (isExceed) { if (enableDRC) { logger_->report(" completing {}% with {} violations", prev_perc, getDesign()->getTopBlock()->getNumMarkers()); } else { logger_->report(" completing {}% with {} quick violations", prev_perc, numQuickMarkers); } logger_->report(" {}", t); } } } } } } { ProfileTask profile("DR:end_batch"); // single thread for (int i = 0; i < (int)workersInBatch.size(); i++) { workersInBatch[i]->end(); } workersInBatch.clear(); } } } } if (!iter) { removeGCell2BoundaryPin(); } if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc >= 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; //if (true) { if (isExceed) { if (enableDRC) { logger_->report(" completing {}% with {} violations", prev_perc, getDesign()->getTopBlock()->getNumMarkers()); } else { logger_->report(" completing {}% with {} quick violations", prev_perc, numQuickMarkers); } logger_->report(" {}", t); } } } checkConnectivity(iter); numViols_.push_back(getDesign()->getTopBlock()->getNumMarkers()); if (VERBOSE > 0) { if (enableDRC) { logger_->info(DRT, 199, " number of violations = {}", getDesign()->getTopBlock()->getNumMarkers()); } else { logger_->info(DRT, 200, " number of quick violations = {}", numQuickMarkers); } t.print(logger_); cout <<flush; } end(); } void FlexDR::end(bool writeMetrics) { vector<unsigned long long> wlen(getTech()->getLayers().size(), 0); vector<unsigned long long> sCut(getTech()->getLayers().size(), 0); vector<unsigned long long> mCut(getTech()->getLayers().size(), 0); unsigned long long totWlen = 0; unsigned long long totSCut = 0; unsigned long long totMCut = 0; frPoint bp, ep; for (auto &net: getDesign()->getTopBlock()->getNets()) { for (auto &shape: net->getShapes()) { if (shape->typeId() == frcPathSeg) { auto obj = static_cast<frPathSeg*>(shape.get()); obj->getPoints(bp, ep); auto lNum = obj->getLayerNum(); frCoord psLen = ep.x() - bp.x() + ep.y() - bp.y(); wlen[lNum] += psLen; totWlen += psLen; } } for (auto &via: net->getVias()) { auto lNum = via->getViaDef()->getCutLayerNum(); if (via->getViaDef()->isMultiCut()) { ++mCut[lNum]; ++totMCut; } else { ++sCut[lNum]; ++totSCut; } } } if (writeMetrics) { logger_->metric(DRT, "wire length::total", totWlen / getDesign()->getTopBlock()->getDBUPerUU()); logger_->metric(DRT, "vias::total", totSCut + totMCut); } if (VERBOSE > 0) { logger_->report("total wire length = {} um", totWlen / getDesign()->getTopBlock()->getDBUPerUU()); for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::ROUTING) { logger_->report("total wire length on LAYER {} = {} um", getTech()->getLayer(i)->getName(), wlen[i] / getDesign()->getTopBlock()->getDBUPerUU()); } } logger_->report("total number of vias = {}", totSCut + totMCut); if (totMCut > 0) { logger_->report("total number of multi-cut vias = {} ({:5.1f}%)", totMCut, totMCut * 100.0 / (totSCut + totMCut)); logger_->report("total number of single-cut vias = {} ({:5.1f}%)", totSCut, totSCut * 100.0 / (totSCut + totMCut)); } logger_->report("up-via summary (total {}):", totSCut + totMCut); int nameLen = 0; for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::CUT) { nameLen = max(nameLen, (int)getTech()->getLayer(i-1)->getName().size()); } } int maxL = 1 + nameLen + 4 + (int)to_string(totSCut).length(); if (totMCut) { maxL += 9 + 4 + (int)to_string(totMCut).length() + 9 + 4 + (int)to_string(totSCut + totMCut).length(); } std::ostringstream msg; if (totMCut) { msg <<" " <<setw(nameLen + 4 + (int)to_string(totSCut).length() + 9) <<"single-cut"; msg <<setw(4 + (int)to_string(totMCut).length() + 9) <<"multi-cut" <<setw(4 + (int)to_string(totSCut + totMCut).length()) <<"total"; } msg <<endl; for (int i = 0; i < maxL; i++) { msg <<"-"; } msg <<endl; for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::CUT) { msg <<" " <<setw(nameLen) <<getTech()->getLayer(i-1)->getName() <<" " <<setw((int)to_string(totSCut).length()) <<sCut[i]; if (totMCut) { msg <<" (" <<setw(5) <<(double)((sCut[i] + mCut[i]) ? sCut[i] * 100.0 / (sCut[i] + mCut[i]) : 0.0) <<"%)"; msg <<" " <<setw((int)to_string(totMCut).length()) <<mCut[i] <<" (" <<setw(5) <<(double)((sCut[i] + mCut[i]) ? mCut[i] * 100.0 / (sCut[i] + mCut[i]) : 0.0) <<"%)" <<" " <<setw((int)to_string(totSCut + totMCut).length()) <<sCut[i] + mCut[i]; } msg <<endl; } } for (int i = 0; i < maxL; i++) { msg <<"-"; } msg <<endl; msg <<" " <<setw(nameLen) <<"" <<" " <<setw((int)to_string(totSCut).length()) <<totSCut; if (totMCut) { msg <<" (" <<setw(5) <<(double)((totSCut + totMCut) ? totSCut * 100.0 / (totSCut + totMCut) : 0.0) <<"%)"; msg <<" " <<setw((int)to_string(totMCut).length()) <<totMCut <<" (" <<setw(5) <<(double)((totSCut + totMCut) ? totMCut * 100.0 / (totSCut + totMCut) : 0.0) <<"%)" <<" " <<setw((int)to_string(totSCut + totMCut).length()) <<totSCut + totMCut; } msg <<endl <<endl; logger_->report("{}", msg.str()); } } void FlexDR::reportDRC() { double dbu = design_->getTech()->getDBUPerUU(); if (DRC_RPT_FILE == string("")) { if (VERBOSE > 0) { cout <<"Waring: no DRC report specified, skipped writing DRC report" <<endl; } return; } //cout << DRC_RPT_FILE << "\n"; ofstream drcRpt(DRC_RPT_FILE.c_str()); if (drcRpt.is_open()) { for (auto &marker: getDesign()->getTopBlock()->getMarkers()) { auto con = marker->getConstraint(); drcRpt << " violation type: "; if (con) { if (con->typeId() == frConstraintTypeEnum::frcShortConstraint) { if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::ROUTING) { drcRpt <<"Short"; } else if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::CUT) { drcRpt <<"CShort"; } } else if (con->typeId() == frConstraintTypeEnum::frcMinWidthConstraint) { drcRpt <<"MinWid"; } else if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { drcRpt <<"MetSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcSpacingEndOfLineConstraint) { drcRpt <<"EOLSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { drcRpt <<"MetSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcCutSpacingConstraint) { drcRpt <<"CutSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcMinStepConstraint) { drcRpt <<"MinStp"; } else if (con->typeId() == frConstraintTypeEnum::frcNonSufficientMetalConstraint) { drcRpt <<"NSMet"; } else if (con->typeId() == frConstraintTypeEnum::frcSpacingSamenetConstraint) { drcRpt <<"MetSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcOffGridConstraint) { drcRpt <<"OffGrid"; } else if (con->typeId() == frConstraintTypeEnum::frcMinEnclosedAreaConstraint) { drcRpt <<"MinHole"; } else if (con->typeId() == frConstraintTypeEnum::frcAreaConstraint) { drcRpt <<"MinArea"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58CornerSpacingConstraint) { drcRpt <<"CornerSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58CutSpacingConstraint) { drcRpt <<"CutSpc"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58RectOnlyConstraint) { drcRpt <<"RectOnly"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58RightWayOnGridOnlyConstraint) { drcRpt <<"RightWayOnGridOnly"; } else if (con->typeId() == frConstraintTypeEnum::frcLef58MinStepConstraint) { drcRpt <<"MinStp"; } else { drcRpt << "unknown"; } } else { drcRpt << "nullptr"; } drcRpt <<endl; // get source(s) of violation drcRpt << " srcs: "; for (auto src: marker->getSrcs()) { if (src) { switch (src->typeId()) { case frcNet: drcRpt << (static_cast<frNet*>(src))->getName() << " "; break; case frcInstTerm: { frInstTerm* instTerm = (static_cast<frInstTerm*>(src)); drcRpt <<instTerm->getInst()->getName() <<"/" <<instTerm->getTerm()->getName() << " "; break; } case frcTerm: { frTerm* term = (static_cast<frTerm*>(src)); drcRpt <<"PIN/" << term->getName() << " "; break; } case frcInstBlockage: { frInstBlockage* instBlockage = (static_cast<frInstBlockage*>(src)); drcRpt <<instBlockage->getInst()->getName() <<"/OBS" << " "; break; } case frcBlockage: { drcRpt << "PIN/OBS" << " "; break; } default: std::cout << "Error: unexpected src type in marker\n"; } } } drcRpt << "\n"; // get violation bbox frBox bbox; marker->getBBox(bbox); drcRpt << " bbox = ( " << bbox.left() / dbu << ", " << bbox.bottom() / dbu << " ) - ( " << bbox.right() / dbu << ", " << bbox.top() / dbu << " ) on Layer "; if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::CUT && marker->getLayerNum() - 1 >= getTech()->getBottomLayerNum()) { drcRpt << getTech()->getLayer(marker->getLayerNum() - 1)->getName() << "\n"; } else { drcRpt << getTech()->getLayer(marker->getLayerNum())->getName() << "\n"; } } } else { cout << "Error: Fail to open DRC report file\n"; } } int FlexDR::main() { ProfileTask profile("DR:main"); init(); frTime t; if (VERBOSE > 0) { logger_->info(DRT, 194, "start detail routing ..."); } // search and repair: iter, size, offset, mazeEndIter, workerDRCCost, workerMarkerCost, // markerBloatWidth, markerBloatDepth, enableDRC, ripupMode, followGuide, fixMode, TEST // fixMode: // 0 - general fix // 1 - fat via short, spc to wire fix (keep via net), no permutation, increasing DRCCOST // 2 - fat via short, spc to wire fix (ripup via net), no permutation, increasing DRCCOST // 3 - general fix, ripup everything (bloat) // 4 - general fix, ripup left/bottom net (touching), currently DISABLED // 5 - general fix, ripup right/top net (touching), currently DISABLED // 6 - two-net viol // 9 - search-and-repair queue // assume only mazeEndIter > 1 if enableDRC and ripupMode == 0 (partial ripup) //end(); //searchRepair(1, 7, -4, 1, DRCCOST, 0, 0, 0, true, 1, false, 0, true); // test mode // need three different offsets to resolve boundary corner issues int iterNum = 0; searchRepair(iterNum++/* 0 */, 7, 0, 3, DRCCOST, 0/*MAARKERCOST*/, 0, 0, true, 1, true, 9); // true search and repair searchRepair(iterNum++/* 1 */, 7, -2, 3, DRCCOST, DRCCOST/*MAARKERCOST*/, 0, 0, true, 1, true, 9); // true search and repair searchRepair(iterNum++/* 1 */, 7, -5, 3, DRCCOST, DRCCOST/*MAARKERCOST*/, 0, 0, true, 1, true, 9); // true search and repair searchRepair(iterNum++/* 3 */, 7, 0, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 4 */, 7, -1, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 5 */, 7, -2, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 6 */, 7, -3, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 7 */, 7, -4, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 8 */, 7, -5, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 9 */, 7, -6, 8, DRCCOST, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 10 */, 7, 0, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 11 */, 7, -1, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 12 */, 7, -2, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 13 */, 7, -3, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 14 */, 7, -4, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 15 */, 7, -5, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 16 */, 7, -6, 8, DRCCOST*2, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 7, -3, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 17 */, 7, 0, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 18 */, 7, -1, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 19 */, 7, -2, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 20 */, 7, -3, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 21 */, 7, -4, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 22 */, 7, -5, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 23 */, 7, -6, 8, DRCCOST*4, MARKERCOST, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 5, -2, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 24 */, 7, 0, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 25 */, 7, -1, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 26 */, 7, -2, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 27 */, 7, -3, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 28 */, 7, -4, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 29 */, 7, -5, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 30 */, 7, -6, 8, DRCCOST*8, MARKERCOST*2, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 3, -1, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 31 */, 7, 0, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 32 */, 7, -1, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 33 */, 7, -2, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 34 */, 7, -3, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 35 */, 7, -4, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 36 */, 7, -5, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 37 */, 7, -6, 8, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 3, -2, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 38 */, 7, 0, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 39 */, 7, -1, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 40 */, 7, -2, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 41 */, 7, -3, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 42 */, 7, -4, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 43 */, 7, -5, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 44 */, 7, -6, 16, DRCCOST*16, MARKERCOST*4, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 3, -0, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 45 */, 7, 0, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 46 */, 7, -1, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 47 */, 7, -2, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 48 */, 7, -3, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 49 */, 7, -4, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 50 */, 7, -5, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 51 */, 7, -6, 32, DRCCOST*32, MARKERCOST*8, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* ra'*/, 3, -1, 8, DRCCOST, MARKERCOST, 0, 0, true, 1, false, 9); // true search and repair searchRepair(iterNum++/* 52 */, 7, 0, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 53 */, 7, -1, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 54 */, 7, -2, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 55 */, 7, -3, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 56 */, 7, -4, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 57 */, 7, -5, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair searchRepair(iterNum++/* 58 */, 7, -6, 64, DRCCOST*64, MARKERCOST*16, 0, 0, true, 0, false, 9); // true search and repair if (DRC_RPT_FILE != string("")) { reportDRC(); } if (VERBOSE > 0) { logger_->info(DRT, 198, "complete detail routing"); end(/* writeMetrics */ true); } if (VERBOSE > 0) { t.print(logger_); cout <<endl; } return 0; }
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkVersorTransformOptimizer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkVersorTransformOptimizer_txx #define _itkVersorTransformOptimizer_txx #include "itkVersorTransformOptimizer.h" #include "vnl/vnl_quaternion.h" #include "itkEventObject.h" namespace itk { /** * Advance one Step following the gradient direction * This method will be overrided in non-vector spaces */ void VersorTransformOptimizer ::StepAlongGradient( double factor, const DerivativeType & transformedGradient ) { const ParametersType & currentPosition = GetCurrentPosition(); // The parameters are assumed to be the right part of the versor // VectorType rightPart; for(unsigned int i=0; i<SpaceDimension; i++) { rightPart[i] = currentPosition[i]; } VersorType currentRotation; currentRotation.Set( rightPart ); // The gradient indicate the contribution of each one // of the axis to the direction of highest change in // the function VectorType axis; axis[0] = transformedGradient[0]; axis[1] = transformedGradient[1]; axis[2] = transformedGradient[2]; // gradientRotation is a rotation along the // versor direction which maximize the // variation of the cost function in question. // An additional Exponentiation produce a jump // of a particular length along the versor gradient // direction. VersorType gradientRotation; gradientRotation.Set( axis, factor * axis.GetNorm() ); // // Composing the currentRotation with the gradientRotation // produces the new Rotation versor // VersorType newRotation = currentRotation * gradientRotation; ParametersType newParameters(SpaceDimension); newParameters[0] = newRotation.GetX(); newParameters[1] = newRotation.GetY(); newParameters[2] = newRotation.GetZ(); this->SetCurrentPosition( newParameters ); } } // end namespace itk #endif STY: use of "this->" for invoking member functions. /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkVersorTransformOptimizer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkVersorTransformOptimizer_txx #define _itkVersorTransformOptimizer_txx #include "itkVersorTransformOptimizer.h" #include "vnl/vnl_quaternion.h" #include "itkEventObject.h" namespace itk { /** * Advance one Step following the gradient direction * This method will be overrided in non-vector spaces */ void VersorTransformOptimizer ::StepAlongGradient( double factor, const DerivativeType & transformedGradient ) { const ParametersType & currentPosition = this->GetCurrentPosition(); // The parameters are assumed to be the right part of the versor // VectorType rightPart; for(unsigned int i=0; i<SpaceDimension; i++) { rightPart[i] = currentPosition[i]; } VersorType currentRotation; currentRotation.Set( rightPart ); // The gradient indicate the contribution of each one // of the axis to the direction of highest change in // the function VectorType axis; axis[0] = transformedGradient[0]; axis[1] = transformedGradient[1]; axis[2] = transformedGradient[2]; // gradientRotation is a rotation along the // versor direction which maximize the // variation of the cost function in question. // An additional Exponentiation produce a jump // of a particular length along the versor gradient // direction. VersorType gradientRotation; gradientRotation.Set( axis, factor * axis.GetNorm() ); // // Composing the currentRotation with the gradientRotation // produces the new Rotation versor // VersorType newRotation = currentRotation * gradientRotation; ParametersType newParameters(SpaceDimension); newParameters[0] = newRotation.GetX(); newParameters[1] = newRotation.GetY(); newParameters[2] = newRotation.GetZ(); this->SetCurrentPosition( newParameters ); } } // end namespace itk #endif
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreOverlayElement.h" #include "OgreMaterialManager.h" #include "OgreOverlay.h" #include "OgreOverlayContainer.h" #include "OgreOverlayManager.h" #include "OgreException.h" #include "OgreRenderQueue.h" namespace Ogre { //--------------------------------------------------------------------- // Define static members OverlayElementCommands::CmdLeft OverlayElement::msLeftCmd; OverlayElementCommands::CmdTop OverlayElement::msTopCmd; OverlayElementCommands::CmdWidth OverlayElement::msWidthCmd; OverlayElementCommands::CmdHeight OverlayElement::msHeightCmd; OverlayElementCommands::CmdMaterial OverlayElement::msMaterialCmd; OverlayElementCommands::CmdCaption OverlayElement::msCaptionCmd; OverlayElementCommands::CmdMetricsMode OverlayElement::msMetricsModeCmd; OverlayElementCommands::CmdHorizontalAlign OverlayElement::msHorizontalAlignCmd; OverlayElementCommands::CmdVerticalAlign OverlayElement::msVerticalAlignCmd; OverlayElementCommands::CmdVisible OverlayElement::msVisibleCmd; //--------------------------------------------------------------------- OverlayElement::OverlayElement(const String& name) : mName(name) , mVisible(true) , mCloneable(true) , mLeft(0.0f) , mTop(0.0f) , mWidth(1.0f) , mHeight(1.0f) , mMetricsMode(GMM_RELATIVE) , mHorzAlign(GHA_LEFT) , mVertAlign(GVA_TOP) , mPixelTop(0.0) , mPixelLeft(0.0) , mPixelWidth(1.0) , mPixelHeight(1.0) , mPixelScaleX(1.0) , mPixelScaleY(1.0) , mParent(0) , mOverlay(0) , mDerivedOutOfDate(true) , mGeomPositionsOutOfDate(true) , mGeomUVsOutOfDate(true) , mZOrder(0) , mEnabled(true) , mInitialised(false) , mSourceTemplate(0) { // default overlays to preserve their own detail level mPolygonModeOverrideable = false; // use identity projection and view matrices mUseIdentityProjection = true; mUseIdentityView = true; } //--------------------------------------------------------------------- OverlayElement::~OverlayElement() { if (mParent) { mParent->removeChild(mName); mParent = 0; } } //--------------------------------------------------------------------- const String& OverlayElement::getName(void) const { return mName; } //--------------------------------------------------------------------- void OverlayElement::show(void) { mVisible = true; } //--------------------------------------------------------------------- void OverlayElement::hide(void) { mVisible = false; } //--------------------------------------------------------------------- bool OverlayElement::isVisible(void) const { return mVisible; } //--------------------------------------------------------------------- void OverlayElement::setDimensions(Real width, Real height) { if (mMetricsMode != GMM_RELATIVE) { mPixelWidth = width; mPixelHeight = height; } else { mWidth = width; mHeight = height; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::setPosition(Real left, Real top) { if (mMetricsMode != GMM_RELATIVE) { mPixelLeft = left; mPixelTop = top; } else { mLeft = left; mTop = top; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::setWidth(Real width) { if (mMetricsMode != GMM_RELATIVE) { mPixelWidth = width; } else { mWidth = width; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- Real OverlayElement::getWidth(void) const { if (mMetricsMode != GMM_RELATIVE) { return mPixelWidth; } else { return mWidth; } } //--------------------------------------------------------------------- void OverlayElement::setHeight(Real height) { if (mMetricsMode != GMM_RELATIVE) { mPixelHeight = height; } else { mHeight = height; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- Real OverlayElement::getHeight(void) const { if (mMetricsMode != GMM_RELATIVE) { return mPixelHeight; } else { return mHeight; } } //--------------------------------------------------------------------- void OverlayElement::setLeft(Real left) { if (mMetricsMode != GMM_RELATIVE) { mPixelLeft = left; } else { mLeft = left; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- Real OverlayElement::getLeft(void) const { if (mMetricsMode != GMM_RELATIVE) { return mPixelLeft; } else { return mLeft; } } //--------------------------------------------------------------------- void OverlayElement::setTop(Real top) { if (mMetricsMode != GMM_RELATIVE) { mPixelTop = top; } else { mTop = top; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- Real OverlayElement::getTop(void) const { if (mMetricsMode != GMM_RELATIVE) { return mPixelTop; } else { return mTop; } } //--------------------------------------------------------------------- void OverlayElement::_setLeft(Real left) { mLeft = left; mPixelLeft = left / mPixelScaleX; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setTop(Real top) { mTop = top; mPixelTop = top / mPixelScaleY; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setWidth(Real width) { mWidth = width; mPixelWidth = width / mPixelScaleX; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setHeight(Real height) { mHeight = height; mPixelHeight = height / mPixelScaleY; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setPosition(Real left, Real top) { mLeft = left; mTop = top; mPixelLeft = left / mPixelScaleX; mPixelTop = top / mPixelScaleY; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setDimensions(Real width, Real height) { mWidth = width; mHeight = height; mPixelWidth = width / mPixelScaleX; mPixelHeight = height / mPixelScaleY; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- const String& OverlayElement::getMaterialName(void) const { return mMaterialName; } //--------------------------------------------------------------------- void OverlayElement::setMaterialName(const String& matName) { mMaterialName = matName; if (matName != StringUtil::BLANK) { mMaterial = MaterialManager::getSingleton().getByName(matName); if (mMaterial.isNull()) OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find material " + matName, "OverlayElement::setMaterialName" ); mMaterial->load(); // Set some prerequisites to be sure mMaterial->setLightingEnabled(false); mMaterial->setDepthCheckEnabled(false); } else { mMaterial.setNull(); } } //--------------------------------------------------------------------- const MaterialPtr& OverlayElement::getMaterial(void) const { return mMaterial; } //--------------------------------------------------------------------- void OverlayElement::getWorldTransforms(Matrix4* xform) const { mOverlay->_getWorldTransforms(xform); } //--------------------------------------------------------------------- void OverlayElement::_positionsOutOfDate(void) { mGeomPositionsOutOfDate = true; } //--------------------------------------------------------------------- void OverlayElement::_update(void) { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); // Check size if pixel-based or relative-aspect-adjusted switch (mMetricsMode) { case GMM_PIXELS : if (OverlayManager::getSingleton().hasViewportChanged() || mGeomPositionsOutOfDate) { mPixelScaleX = 1.0f / vpWidth; mPixelScaleY = 1.0f / vpHeight; } break; case GMM_RELATIVE_ASPECT_ADJUSTED : if (OverlayManager::getSingleton().hasViewportChanged() || mGeomPositionsOutOfDate) { mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); mPixelScaleY = 1.0f / 10000.0f; } break; default: break; } mLeft = mPixelLeft * mPixelScaleX; mTop = mPixelTop * mPixelScaleY; mWidth = mPixelWidth * mPixelScaleX; mHeight = mPixelHeight * mPixelScaleY; Real tmpPixelWidth = mPixelWidth; _updateFromParent(); // NB container subclasses will update children too // Tell self to update own position geometry if (mGeomPositionsOutOfDate && mInitialised) { updatePositionGeometry(); // Within updatePositionGeometry() of TextOverlayElements, // the needed pixel width is calculated and as a result a new // second update call is needed, so leave the dirty flag on 'true' // so that that in a second call in the next frame, the element // width can be correctly set and the text gets displayed. if(mMetricsMode == GMM_PIXELS && tmpPixelWidth != mPixelWidth) mGeomPositionsOutOfDate = true; else mGeomPositionsOutOfDate = false; } // Tell self to update own texture geometry if (mGeomUVsOutOfDate && mInitialised) { updateTextureGeometry(); mGeomUVsOutOfDate = false; } } //--------------------------------------------------------------------- void OverlayElement::_updateFromParent(void) { Real parentLeft = 0, parentTop = 0, parentBottom = 0, parentRight = 0; if (mParent) { parentLeft = mParent->_getDerivedLeft(); parentTop = mParent->_getDerivedTop(); if (mHorzAlign == GHA_CENTER || mHorzAlign == GHA_RIGHT) { parentRight = parentLeft + mParent->_getRelativeWidth(); } if (mVertAlign == GVA_CENTER || mVertAlign == GVA_BOTTOM) { parentBottom = parentTop + mParent->_getRelativeHeight(); } } else { RenderSystem* rSys = Root::getSingleton().getRenderSystem(); OverlayManager& oMgr = OverlayManager::getSingleton(); // Calculate offsets required for mapping texel origins to pixel origins in the // current rendersystem Real hOffset = rSys->getHorizontalTexelOffset() / oMgr.getViewportWidth(); Real vOffset = rSys->getVerticalTexelOffset() / oMgr.getViewportHeight(); parentLeft = 0.0f + hOffset; parentTop = 0.0f + vOffset; parentRight = 1.0f + hOffset; parentBottom = 1.0f + vOffset; } // Sort out position based on alignment // NB all we do is derived the origin, we don't automatically sort out the position // This is more flexible than forcing absolute right & middle switch(mHorzAlign) { case GHA_CENTER: mDerivedLeft = ((parentLeft + parentRight) * 0.5f) + mLeft; break; case GHA_LEFT: mDerivedLeft = parentLeft + mLeft; break; case GHA_RIGHT: mDerivedLeft = parentRight + mLeft; break; }; switch(mVertAlign) { case GVA_CENTER: mDerivedTop = ((parentTop + parentBottom) * 0.5f) + mTop; break; case GVA_TOP: mDerivedTop = parentTop + mTop; break; case GVA_BOTTOM: mDerivedTop = parentBottom + mTop; break; }; mDerivedOutOfDate = false; if (mParent != 0) { RealRect parent; RealRect child; mParent->_getClippingRegion(parent); child.left = mDerivedLeft; child.top = mDerivedTop; child.right = mDerivedLeft + mWidth; child.bottom = mDerivedTop + mHeight; mClippingRegion = parent.intersect(child); } else { mClippingRegion.left = mDerivedLeft; mClippingRegion.top = mDerivedTop; mClippingRegion.right = mDerivedLeft + mWidth; mClippingRegion.bottom = mDerivedTop + mHeight; } } //--------------------------------------------------------------------- void OverlayElement::_notifyParent(OverlayContainer* parent, Overlay* overlay) { mParent = parent; mOverlay = overlay; if (mOverlay && mOverlay->isInitialised() && !mInitialised) { initialise(); } mDerivedOutOfDate = true; } //--------------------------------------------------------------------- Real OverlayElement::_getDerivedLeft(void) { if (mDerivedOutOfDate) { _updateFromParent(); } return mDerivedLeft; } //--------------------------------------------------------------------- Real OverlayElement::_getDerivedTop(void) { if (mDerivedOutOfDate) { _updateFromParent(); } return mDerivedTop; } //--------------------------------------------------------------------- Real OverlayElement::_getRelativeWidth(void) { return mWidth; } //--------------------------------------------------------------------- Real OverlayElement::_getRelativeHeight(void) { return mHeight; } //--------------------------------------------------------------------- void OverlayElement::_getClippingRegion(RealRect &clippingRegion) { if (mDerivedOutOfDate) { _updateFromParent(); } clippingRegion = mClippingRegion; } //--------------------------------------------------------------------- ushort OverlayElement::_notifyZOrder(ushort newZOrder) { mZOrder = newZOrder; return mZOrder + 1; } //--------------------------------------------------------------------- void OverlayElement::_notifyWorldTransforms(const Matrix4& xform) { mXForm = xform; } //--------------------------------------------------------------------- void OverlayElement::_notifyViewport() { switch (mMetricsMode) { case GMM_PIXELS : { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); mPixelScaleX = 1.0f / vpWidth; mPixelScaleY = 1.0f / vpHeight; } break; case GMM_RELATIVE_ASPECT_ADJUSTED : { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); mPixelScaleY = 1.0f / 10000.0f; } break; case GMM_RELATIVE : mPixelScaleX = 1.0; mPixelScaleY = 1.0; mPixelLeft = mLeft; mPixelTop = mTop; mPixelWidth = mWidth; mPixelHeight = mHeight; break; } mLeft = mPixelLeft * mPixelScaleX; mTop = mPixelTop * mPixelScaleY; mWidth = mPixelWidth * mPixelScaleX; mHeight = mPixelHeight * mPixelScaleY; mGeomPositionsOutOfDate = true; } //--------------------------------------------------------------------- void OverlayElement::_updateRenderQueue(RenderQueue* queue) { if (mVisible) { queue->addRenderable(this, RENDER_QUEUE_OVERLAY, mZOrder); } } //--------------------------------------------------------------------- void OverlayElement::visitRenderables(Renderable::Visitor* visitor, bool debugRenderables) { visitor->visit(this, 0, false); } //----------------------------------------------------------------------- void OverlayElement::addBaseParameters(void) { ParamDictionary* dict = getParamDictionary(); dict->addParameter(ParameterDef("left", "The position of the left border of the gui element." , PT_REAL), &msLeftCmd); dict->addParameter(ParameterDef("top", "The position of the top border of the gui element." , PT_REAL), &msTopCmd); dict->addParameter(ParameterDef("width", "The width of the element." , PT_REAL), &msWidthCmd); dict->addParameter(ParameterDef("height", "The height of the element." , PT_REAL), &msHeightCmd); dict->addParameter(ParameterDef("material", "The name of the material to use." , PT_STRING), &msMaterialCmd); dict->addParameter(ParameterDef("caption", "The element caption, if supported." , PT_STRING), &msCaptionCmd); dict->addParameter(ParameterDef("metrics_mode", "The type of metrics to use, either 'relative' to the screen, 'pixels' or 'relative_aspect_adjusted'." , PT_STRING), &msMetricsModeCmd); dict->addParameter(ParameterDef("horz_align", "The horizontal alignment, 'left', 'right' or 'center'." , PT_STRING), &msHorizontalAlignCmd); dict->addParameter(ParameterDef("vert_align", "The vertical alignment, 'top', 'bottom' or 'center'." , PT_STRING), &msVerticalAlignCmd); dict->addParameter(ParameterDef("visible", "Initial visibility of element, either 'true' or 'false' (default true)." , PT_STRING), &msVisibleCmd); } //----------------------------------------------------------------------- void OverlayElement::setCaption( const DisplayString& caption ) { mCaption = caption; _positionsOutOfDate(); } //----------------------------------------------------------------------- const DisplayString& OverlayElement::getCaption() const { return mCaption; } //----------------------------------------------------------------------- void OverlayElement::setColour(const ColourValue& col) { mColour = col; } //----------------------------------------------------------------------- const ColourValue& OverlayElement::getColour(void) const { return mColour; } //----------------------------------------------------------------------- void OverlayElement::setMetricsMode(GuiMetricsMode gmm) { switch (gmm) { case GMM_PIXELS : { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); // cope with temporarily zero dimensions, avoid divide by zero vpWidth = vpWidth == 0.0f? 1.0f : vpWidth; vpHeight = vpHeight == 0.0f? 1.0f : vpHeight; mPixelScaleX = 1.0f / vpWidth; mPixelScaleY = 1.0f / vpHeight; if (mMetricsMode == GMM_RELATIVE) { mPixelLeft = mLeft; mPixelTop = mTop; mPixelWidth = mWidth; mPixelHeight = mHeight; } } break; case GMM_RELATIVE_ASPECT_ADJUSTED : { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); mPixelScaleY = 1.0f / 10000.0f; if (mMetricsMode == GMM_RELATIVE) { mPixelLeft = mLeft; mPixelTop = mTop; mPixelWidth = mWidth; mPixelHeight = mHeight; } } break; case GMM_RELATIVE : mPixelScaleX = 1.0; mPixelScaleY = 1.0; mPixelLeft = mLeft; mPixelTop = mTop; mPixelWidth = mWidth; mPixelHeight = mHeight; break; } mLeft = mPixelLeft * mPixelScaleX; mTop = mPixelTop * mPixelScaleY; mWidth = mPixelWidth * mPixelScaleX; mHeight = mPixelHeight * mPixelScaleY; mMetricsMode = gmm; mDerivedOutOfDate = true; _positionsOutOfDate(); } //----------------------------------------------------------------------- GuiMetricsMode OverlayElement::getMetricsMode(void) const { return mMetricsMode; } //----------------------------------------------------------------------- void OverlayElement::setHorizontalAlignment(GuiHorizontalAlignment gha) { mHorzAlign = gha; _positionsOutOfDate(); } //----------------------------------------------------------------------- GuiHorizontalAlignment OverlayElement::getHorizontalAlignment(void) const { return mHorzAlign; } //----------------------------------------------------------------------- void OverlayElement::setVerticalAlignment(GuiVerticalAlignment gva) { mVertAlign = gva; _positionsOutOfDate(); } //----------------------------------------------------------------------- GuiVerticalAlignment OverlayElement::getVerticalAlignment(void) const { return mVertAlign; } //----------------------------------------------------------------------- bool OverlayElement::contains(Real x, Real y) const { return x >= mClippingRegion.left && x <= mClippingRegion.right && y >= mClippingRegion.top && y <= mClippingRegion.bottom; } //----------------------------------------------------------------------- OverlayElement* OverlayElement::findElementAt(Real x, Real y) // relative to parent { OverlayElement* ret = NULL; if (contains(x , y )) { ret = this; } return ret; } //----------------------------------------------------------------------- OverlayContainer* OverlayElement::getParent() { return mParent; } //--------------------------------------------------------------------- void OverlayElement::copyFromTemplate(OverlayElement* templateOverlay) { templateOverlay->copyParametersTo(this); mSourceTemplate = templateOverlay ; return; } //--------------------------------------------------------------------- OverlayElement* OverlayElement::clone(const String& instanceName) { OverlayElement* newElement; newElement = OverlayManager::getSingleton().createOverlayElement( getTypeName(), instanceName + "/" + mName); copyParametersTo(newElement); return newElement; } //----------------------------------------------------------------------- bool OverlayElement::isEnabled() const { return mEnabled; } //----------------------------------------------------------------------- void OverlayElement::setEnabled(bool b) { mEnabled = b; } //--------------------------------------------------------------------- } Backed out changeset: 8659fe712bc9 /* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreOverlayElement.h" #include "OgreMaterialManager.h" #include "OgreOverlay.h" #include "OgreOverlayContainer.h" #include "OgreOverlayManager.h" #include "OgreException.h" #include "OgreRenderQueue.h" namespace Ogre { //--------------------------------------------------------------------- // Define static members OverlayElementCommands::CmdLeft OverlayElement::msLeftCmd; OverlayElementCommands::CmdTop OverlayElement::msTopCmd; OverlayElementCommands::CmdWidth OverlayElement::msWidthCmd; OverlayElementCommands::CmdHeight OverlayElement::msHeightCmd; OverlayElementCommands::CmdMaterial OverlayElement::msMaterialCmd; OverlayElementCommands::CmdCaption OverlayElement::msCaptionCmd; OverlayElementCommands::CmdMetricsMode OverlayElement::msMetricsModeCmd; OverlayElementCommands::CmdHorizontalAlign OverlayElement::msHorizontalAlignCmd; OverlayElementCommands::CmdVerticalAlign OverlayElement::msVerticalAlignCmd; OverlayElementCommands::CmdVisible OverlayElement::msVisibleCmd; //--------------------------------------------------------------------- OverlayElement::OverlayElement(const String& name) : mName(name) , mVisible(true) , mCloneable(true) , mLeft(0.0f) , mTop(0.0f) , mWidth(1.0f) , mHeight(1.0f) , mMetricsMode(GMM_RELATIVE) , mHorzAlign(GHA_LEFT) , mVertAlign(GVA_TOP) , mPixelTop(0.0) , mPixelLeft(0.0) , mPixelWidth(1.0) , mPixelHeight(1.0) , mPixelScaleX(1.0) , mPixelScaleY(1.0) , mParent(0) , mOverlay(0) , mDerivedOutOfDate(true) , mGeomPositionsOutOfDate(true) , mGeomUVsOutOfDate(true) , mZOrder(0) , mEnabled(true) , mInitialised(false) , mSourceTemplate(0) { // default overlays to preserve their own detail level mPolygonModeOverrideable = false; // use identity projection and view matrices mUseIdentityProjection = true; mUseIdentityView = true; } //--------------------------------------------------------------------- OverlayElement::~OverlayElement() { if (mParent) { mParent->removeChild(mName); mParent = 0; } } //--------------------------------------------------------------------- const String& OverlayElement::getName(void) const { return mName; } //--------------------------------------------------------------------- void OverlayElement::show(void) { mVisible = true; } //--------------------------------------------------------------------- void OverlayElement::hide(void) { mVisible = false; } //--------------------------------------------------------------------- bool OverlayElement::isVisible(void) const { return mVisible; } //--------------------------------------------------------------------- void OverlayElement::setDimensions(Real width, Real height) { if (mMetricsMode != GMM_RELATIVE) { mPixelWidth = width; mPixelHeight = height; } else { mWidth = width; mHeight = height; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::setPosition(Real left, Real top) { if (mMetricsMode != GMM_RELATIVE) { mPixelLeft = left; mPixelTop = top; } else { mLeft = left; mTop = top; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::setWidth(Real width) { if (mMetricsMode != GMM_RELATIVE) { mPixelWidth = width; } else { mWidth = width; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- Real OverlayElement::getWidth(void) const { if (mMetricsMode != GMM_RELATIVE) { return mPixelWidth; } else { return mWidth; } } //--------------------------------------------------------------------- void OverlayElement::setHeight(Real height) { if (mMetricsMode != GMM_RELATIVE) { mPixelHeight = height; } else { mHeight = height; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- Real OverlayElement::getHeight(void) const { if (mMetricsMode != GMM_RELATIVE) { return mPixelHeight; } else { return mHeight; } } //--------------------------------------------------------------------- void OverlayElement::setLeft(Real left) { if (mMetricsMode != GMM_RELATIVE) { mPixelLeft = left; } else { mLeft = left; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- Real OverlayElement::getLeft(void) const { if (mMetricsMode != GMM_RELATIVE) { return mPixelLeft; } else { return mLeft; } } //--------------------------------------------------------------------- void OverlayElement::setTop(Real top) { if (mMetricsMode != GMM_RELATIVE) { mPixelTop = top; } else { mTop = top; } mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- Real OverlayElement::getTop(void) const { if (mMetricsMode != GMM_RELATIVE) { return mPixelTop; } else { return mTop; } } //--------------------------------------------------------------------- void OverlayElement::_setLeft(Real left) { mLeft = left; mPixelLeft = left / mPixelScaleX; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setTop(Real top) { mTop = top; mPixelTop = top / mPixelScaleY; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setWidth(Real width) { mWidth = width; mPixelWidth = width / mPixelScaleX; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setHeight(Real height) { mHeight = height; mPixelHeight = height / mPixelScaleY; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setPosition(Real left, Real top) { mLeft = left; mTop = top; mPixelLeft = left / mPixelScaleX; mPixelTop = top / mPixelScaleY; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- void OverlayElement::_setDimensions(Real width, Real height) { mWidth = width; mHeight = height; mPixelWidth = width / mPixelScaleX; mPixelHeight = height / mPixelScaleY; mDerivedOutOfDate = true; _positionsOutOfDate(); } //--------------------------------------------------------------------- const String& OverlayElement::getMaterialName(void) const { return mMaterialName; } //--------------------------------------------------------------------- void OverlayElement::setMaterialName(const String& matName) { mMaterialName = matName; if (matName != StringUtil::BLANK) { mMaterial = MaterialManager::getSingleton().getByName(matName); if (mMaterial.isNull()) OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find material " + matName, "OverlayElement::setMaterialName" ); mMaterial->load(); // Set some prerequisites to be sure mMaterial->setLightingEnabled(false); mMaterial->setDepthCheckEnabled(false); } else { mMaterial.setNull(); } } //--------------------------------------------------------------------- const MaterialPtr& OverlayElement::getMaterial(void) const { return mMaterial; } //--------------------------------------------------------------------- void OverlayElement::getWorldTransforms(Matrix4* xform) const { mOverlay->_getWorldTransforms(xform); } //--------------------------------------------------------------------- void OverlayElement::_positionsOutOfDate(void) { mGeomPositionsOutOfDate = true; } //--------------------------------------------------------------------- void OverlayElement::_update(void) { // Check size if pixel-based switch (mMetricsMode) { case GMM_PIXELS : if (OverlayManager::getSingleton().hasViewportChanged() || mGeomPositionsOutOfDate) { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); mPixelScaleX = 1.0f / vpWidth; mPixelScaleY = 1.0f / vpHeight; mLeft = mPixelLeft * mPixelScaleX; mTop = mPixelTop * mPixelScaleY; mWidth = mPixelWidth * mPixelScaleX; mHeight = mPixelHeight * mPixelScaleY; } break; case GMM_RELATIVE_ASPECT_ADJUSTED : if (OverlayManager::getSingleton().hasViewportChanged() || mGeomPositionsOutOfDate) { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); mPixelScaleY = 1.0f / 10000.0f; mLeft = mPixelLeft * mPixelScaleX; mTop = mPixelTop * mPixelScaleY; mWidth = mPixelWidth * mPixelScaleX; mHeight = mPixelHeight * mPixelScaleY; } break; default: break; } _updateFromParent(); // NB container subclasses will update children too // Tell self to update own position geometry if (mGeomPositionsOutOfDate && mInitialised) { updatePositionGeometry(); mGeomPositionsOutOfDate = false; } // Tell self to update own texture geometry if (mGeomUVsOutOfDate && mInitialised) { updateTextureGeometry(); mGeomUVsOutOfDate = false; } } //--------------------------------------------------------------------- void OverlayElement::_updateFromParent(void) { Real parentLeft = 0, parentTop = 0, parentBottom = 0, parentRight = 0; if (mParent) { parentLeft = mParent->_getDerivedLeft(); parentTop = mParent->_getDerivedTop(); if (mHorzAlign == GHA_CENTER || mHorzAlign == GHA_RIGHT) { parentRight = parentLeft + mParent->_getRelativeWidth(); } if (mVertAlign == GVA_CENTER || mVertAlign == GVA_BOTTOM) { parentBottom = parentTop + mParent->_getRelativeHeight(); } } else { RenderSystem* rSys = Root::getSingleton().getRenderSystem(); OverlayManager& oMgr = OverlayManager::getSingleton(); // Calculate offsets required for mapping texel origins to pixel origins in the // current rendersystem Real hOffset = rSys->getHorizontalTexelOffset() / oMgr.getViewportWidth(); Real vOffset = rSys->getVerticalTexelOffset() / oMgr.getViewportHeight(); parentLeft = 0.0f + hOffset; parentTop = 0.0f + vOffset; parentRight = 1.0f + hOffset; parentBottom = 1.0f + vOffset; } // Sort out position based on alignment // NB all we do is derived the origin, we don't automatically sort out the position // This is more flexible than forcing absolute right & middle switch(mHorzAlign) { case GHA_CENTER: mDerivedLeft = ((parentLeft + parentRight) * 0.5f) + mLeft; break; case GHA_LEFT: mDerivedLeft = parentLeft + mLeft; break; case GHA_RIGHT: mDerivedLeft = parentRight + mLeft; break; }; switch(mVertAlign) { case GVA_CENTER: mDerivedTop = ((parentTop + parentBottom) * 0.5f) + mTop; break; case GVA_TOP: mDerivedTop = parentTop + mTop; break; case GVA_BOTTOM: mDerivedTop = parentBottom + mTop; break; }; mDerivedOutOfDate = false; if (mParent != 0) { RealRect parent; RealRect child; mParent->_getClippingRegion(parent); child.left = mDerivedLeft; child.top = mDerivedTop; child.right = mDerivedLeft + mWidth; child.bottom = mDerivedTop + mHeight; mClippingRegion = parent.intersect(child); } else { mClippingRegion.left = mDerivedLeft; mClippingRegion.top = mDerivedTop; mClippingRegion.right = mDerivedLeft + mWidth; mClippingRegion.bottom = mDerivedTop + mHeight; } } //--------------------------------------------------------------------- void OverlayElement::_notifyParent(OverlayContainer* parent, Overlay* overlay) { mParent = parent; mOverlay = overlay; if (mOverlay && mOverlay->isInitialised() && !mInitialised) { initialise(); } mDerivedOutOfDate = true; } //--------------------------------------------------------------------- Real OverlayElement::_getDerivedLeft(void) { if (mDerivedOutOfDate) { _updateFromParent(); } return mDerivedLeft; } //--------------------------------------------------------------------- Real OverlayElement::_getDerivedTop(void) { if (mDerivedOutOfDate) { _updateFromParent(); } return mDerivedTop; } //--------------------------------------------------------------------- Real OverlayElement::_getRelativeWidth(void) { return mWidth; } //--------------------------------------------------------------------- Real OverlayElement::_getRelativeHeight(void) { return mHeight; } //--------------------------------------------------------------------- void OverlayElement::_getClippingRegion(RealRect &clippingRegion) { if (mDerivedOutOfDate) { _updateFromParent(); } clippingRegion = mClippingRegion; } //--------------------------------------------------------------------- ushort OverlayElement::_notifyZOrder(ushort newZOrder) { mZOrder = newZOrder; return mZOrder + 1; } //--------------------------------------------------------------------- void OverlayElement::_notifyWorldTransforms(const Matrix4& xform) { mXForm = xform; } //--------------------------------------------------------------------- void OverlayElement::_notifyViewport() { switch (mMetricsMode) { case GMM_PIXELS : { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); mPixelScaleX = 1.0f / vpWidth; mPixelScaleY = 1.0f / vpHeight; } break; case GMM_RELATIVE_ASPECT_ADJUSTED : { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); mPixelScaleY = 1.0f / 10000.0f; } break; case GMM_RELATIVE : mPixelScaleX = 1.0; mPixelScaleY = 1.0; mPixelLeft = mLeft; mPixelTop = mTop; mPixelWidth = mWidth; mPixelHeight = mHeight; break; } mLeft = mPixelLeft * mPixelScaleX; mTop = mPixelTop * mPixelScaleY; mWidth = mPixelWidth * mPixelScaleX; mHeight = mPixelHeight * mPixelScaleY; mGeomPositionsOutOfDate = true; } //--------------------------------------------------------------------- void OverlayElement::_updateRenderQueue(RenderQueue* queue) { if (mVisible) { queue->addRenderable(this, RENDER_QUEUE_OVERLAY, mZOrder); } } //--------------------------------------------------------------------- void OverlayElement::visitRenderables(Renderable::Visitor* visitor, bool debugRenderables) { visitor->visit(this, 0, false); } //----------------------------------------------------------------------- void OverlayElement::addBaseParameters(void) { ParamDictionary* dict = getParamDictionary(); dict->addParameter(ParameterDef("left", "The position of the left border of the gui element." , PT_REAL), &msLeftCmd); dict->addParameter(ParameterDef("top", "The position of the top border of the gui element." , PT_REAL), &msTopCmd); dict->addParameter(ParameterDef("width", "The width of the element." , PT_REAL), &msWidthCmd); dict->addParameter(ParameterDef("height", "The height of the element." , PT_REAL), &msHeightCmd); dict->addParameter(ParameterDef("material", "The name of the material to use." , PT_STRING), &msMaterialCmd); dict->addParameter(ParameterDef("caption", "The element caption, if supported." , PT_STRING), &msCaptionCmd); dict->addParameter(ParameterDef("metrics_mode", "The type of metrics to use, either 'relative' to the screen, 'pixels' or 'relative_aspect_adjusted'." , PT_STRING), &msMetricsModeCmd); dict->addParameter(ParameterDef("horz_align", "The horizontal alignment, 'left', 'right' or 'center'." , PT_STRING), &msHorizontalAlignCmd); dict->addParameter(ParameterDef("vert_align", "The vertical alignment, 'top', 'bottom' or 'center'." , PT_STRING), &msVerticalAlignCmd); dict->addParameter(ParameterDef("visible", "Initial visibility of element, either 'true' or 'false' (default true)." , PT_STRING), &msVisibleCmd); } //----------------------------------------------------------------------- void OverlayElement::setCaption( const DisplayString& caption ) { mCaption = caption; _positionsOutOfDate(); } //----------------------------------------------------------------------- const DisplayString& OverlayElement::getCaption() const { return mCaption; } //----------------------------------------------------------------------- void OverlayElement::setColour(const ColourValue& col) { mColour = col; } //----------------------------------------------------------------------- const ColourValue& OverlayElement::getColour(void) const { return mColour; } //----------------------------------------------------------------------- void OverlayElement::setMetricsMode(GuiMetricsMode gmm) { switch (gmm) { case GMM_PIXELS : { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); // cope with temporarily zero dimensions, avoid divide by zero vpWidth = vpWidth == 0.0f? 1.0f : vpWidth; vpHeight = vpHeight == 0.0f? 1.0f : vpHeight; mPixelScaleX = 1.0f / vpWidth; mPixelScaleY = 1.0f / vpHeight; if (mMetricsMode == GMM_RELATIVE) { mPixelLeft = mLeft; mPixelTop = mTop; mPixelWidth = mWidth; mPixelHeight = mHeight; } } break; case GMM_RELATIVE_ASPECT_ADJUSTED : { Real vpWidth, vpHeight; OverlayManager& oMgr = OverlayManager::getSingleton(); vpWidth = (Real) (oMgr.getViewportWidth()); vpHeight = (Real) (oMgr.getViewportHeight()); mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); mPixelScaleY = 1.0f / 10000.0f; if (mMetricsMode == GMM_RELATIVE) { mPixelLeft = mLeft; mPixelTop = mTop; mPixelWidth = mWidth; mPixelHeight = mHeight; } } break; case GMM_RELATIVE : mPixelScaleX = 1.0; mPixelScaleY = 1.0; mPixelLeft = mLeft; mPixelTop = mTop; mPixelWidth = mWidth; mPixelHeight = mHeight; break; } mLeft = mPixelLeft * mPixelScaleX; mTop = mPixelTop * mPixelScaleY; mWidth = mPixelWidth * mPixelScaleX; mHeight = mPixelHeight * mPixelScaleY; mMetricsMode = gmm; mDerivedOutOfDate = true; _positionsOutOfDate(); } //----------------------------------------------------------------------- GuiMetricsMode OverlayElement::getMetricsMode(void) const { return mMetricsMode; } //----------------------------------------------------------------------- void OverlayElement::setHorizontalAlignment(GuiHorizontalAlignment gha) { mHorzAlign = gha; _positionsOutOfDate(); } //----------------------------------------------------------------------- GuiHorizontalAlignment OverlayElement::getHorizontalAlignment(void) const { return mHorzAlign; } //----------------------------------------------------------------------- void OverlayElement::setVerticalAlignment(GuiVerticalAlignment gva) { mVertAlign = gva; _positionsOutOfDate(); } //----------------------------------------------------------------------- GuiVerticalAlignment OverlayElement::getVerticalAlignment(void) const { return mVertAlign; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- bool OverlayElement::contains(Real x, Real y) const { return x >= mClippingRegion.left && x <= mClippingRegion.right && y >= mClippingRegion.top && y <= mClippingRegion.bottom; } //----------------------------------------------------------------------- OverlayElement* OverlayElement::findElementAt(Real x, Real y) // relative to parent { OverlayElement* ret = NULL; if (contains(x , y )) { ret = this; } return ret; } //----------------------------------------------------------------------- OverlayContainer* OverlayElement::getParent() { return mParent; } void OverlayElement::copyFromTemplate(OverlayElement* templateOverlay) { templateOverlay->copyParametersTo(this); mSourceTemplate = templateOverlay ; return; } OverlayElement* OverlayElement::clone(const String& instanceName) { OverlayElement* newElement; newElement = OverlayManager::getSingleton().createOverlayElement( getTypeName(), instanceName + "/" + mName); copyParametersTo(newElement); return newElement; } //----------------------------------------------------------------------- bool OverlayElement::isEnabled() const { return mEnabled; } //----------------------------------------------------------------------- void OverlayElement::setEnabled(bool b) { mEnabled = b; } }
/* Copyright (C) 2011 by Ivan Safrin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef _WINDOWS #include <windows.h> #endif #include "PolyGLHeaders.h" #include "PolyGLSLShaderModule.h" #include "PolyCoreServices.h" #include "PolyCore.h" #include "PolyResourceManager.h" #include "PolyRenderer.h" #include "PolyGLSLProgram.h" #include "PolyGLSLShader.h" #include "PolyGLCubemap.h" #include "PolyMaterial.h" #include "PolyGLTexture.h" #include "tinyxml.h" using std::vector; using namespace Polycode; #if defined(_WINDOWS) && !defined(_MINGW) PFNGLUSEPROGRAMPROC glUseProgram; PFNGLUNIFORM1IPROC glUniform1i; PFNGLUNIFORM1FPROC glUniform1f; PFNGLUNIFORM2FPROC glUniform2f; PFNGLUNIFORM3FPROC glUniform3f; PFNGLUNIFORM4FPROC glUniform4f; extern PFNGLACTIVETEXTUREPROC glActiveTexture; PFNGLCREATESHADERPROC glCreateShader; PFNGLSHADERSOURCEPROC glShaderSource; PFNGLCOMPILESHADERPROC glCompileShader; PFNGLCREATEPROGRAMPROC glCreateProgram; PFNGLATTACHSHADERPROC glAttachShader; PFNGLLINKPROGRAMPROC glLinkProgram; PFNGLDETACHSHADERPROC glDetachShader; PFNGLDELETESHADERPROC glDeleteShader; PFNGLDELETEPROGRAMPROC glDeleteProgram; PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; PFNGLGETSHADERIVPROC glGetShaderiv; PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation; #endif GLSLShaderModule::GLSLShaderModule() : PolycodeShaderModule() { #ifdef _WINDOWS glUseProgram = (PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"); glUniform1i = (PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"); glUniform1f = (PFNGLUNIFORM1FPROC)wglGetProcAddress("glUniform1f"); glUniform2f = (PFNGLUNIFORM2FPROC)wglGetProcAddress("glUniform2f"); glUniform3f = (PFNGLUNIFORM3FPROC)wglGetProcAddress("glUniform3f"); glCreateShader = (PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader"); glShaderSource = (PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource"); glCompileShader = (PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"); glCreateProgram = (PFNGLCREATEPROGRAMPROC)wglGetProcAddress("glCreateProgram"); glAttachShader = (PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader"); glLinkProgram = (PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram"); glDetachShader = (PFNGLDETACHSHADERPROC)wglGetProcAddress("glDetachShader"); glDeleteShader = (PFNGLDELETESHADERPROC)wglGetProcAddress("glDeleteShader"); glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wglGetProcAddress("glDeleteProgram"); glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wglGetProcAddress("glUniformMatrix4fv"); glGetShaderiv = (PFNGLGETSHADERIVPROC)wglGetProcAddress("glGetShaderiv"); glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wglGetProcAddress("glGetShaderInfoLog"); #ifndef _MINGW glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONARBPROC)wglGetProcAddress("glGetUniformLocation"); glUniform4f = (PFNGLUNIFORM4FPROC)wglGetProcAddress("glUniform4f"); #endif #endif } GLSLShaderModule::~GLSLShaderModule() { } bool GLSLShaderModule::acceptsExtension(const String& extension) { if(extension == "vert" || extension == "frag") { return true; } else { return false; } } String GLSLShaderModule::getShaderType() { return "glsl"; } Shader *GLSLShaderModule::createShader(ResourcePool *resourcePool, String name, String vpName, String fpName) { GLSLShader *retShader = NULL; GLSLProgram *vp = NULL; GLSLProgram *fp = NULL; vp = (GLSLProgram*)resourcePool->getResourceByPath(vpName); fp = (GLSLProgram*)resourcePool->getResourceByPath(fpName); if(vp != NULL && fp != NULL) { GLSLShader *shader = new GLSLShader(vp,fp); shader->setName(name); retShader = shader; shaders.push_back((Shader*)shader); } return retShader; } Shader *GLSLShaderModule::createShader(ResourcePool *resourcePool, TiXmlNode *node) { TiXmlNode* pChild; GLSLProgram *vp = NULL; GLSLProgram *fp = NULL; GLSLShader *retShader = NULL; TiXmlElement *nodeElement = node->ToElement(); if (!nodeElement) return NULL; // Skip comment nodes for (pChild = node->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { TiXmlElement *pChildElement = pChild->ToElement(); if (!pChildElement) continue; // Skip comment nodes if(strcmp(pChild->Value(), "vp") == 0) { String vpFileName = String(pChildElement->Attribute("source")); vp = (GLSLProgram*)resourcePool->getResourceByPath(vpFileName); if(!vp) { vp = (GLSLProgram*)CoreServices::getInstance()->getMaterialManager()->createProgramFromFile(vpFileName); if(vp) { vp->setResourcePath(vpFileName); OSFileEntry entry = OSFileEntry(vpFileName, OSFileEntry::TYPE_FILE); vp->setResourceName(entry.name); resourcePool->addResource(vp); } } } if(strcmp(pChild->Value(), "fp") == 0) { String fpFileName = String(pChildElement->Attribute("source")); fp = (GLSLProgram*)resourcePool->getResourceByPath(fpFileName); if(!fp) { fp = (GLSLProgram*)CoreServices::getInstance()->getMaterialManager()->createProgramFromFile(fpFileName); if(fp) { fp->setResourcePath(fpFileName); OSFileEntry entry = OSFileEntry(fpFileName, OSFileEntry::TYPE_FILE); fp->setResourceName(entry.name); resourcePool->addResource(fp); } } } } if(vp != NULL && fp != NULL) { GLSLShader *cgShader = new GLSLShader(vp,fp); cgShader->setName(String(nodeElement->Attribute("name"))); retShader = cgShader; shaders.push_back((Shader*)cgShader); } return retShader; } void GLSLShaderModule::clearShader() { glUseProgram(0); } #ifdef POLYCODE_NUMBER_IS_SINGLE #define polycodeUniformMatrix4v glUniformMatrix4fv #else #define polycodeUniformMatrix4v glUniformMatrix4dv #endif void GLSLShaderModule::updateGLSLParam(Renderer *renderer, GLSLShader *glslShader, ProgramParam &param, ShaderBinding *materialOptions, ShaderBinding *localOptions) { LocalShaderParam *localParam = NULL; localParam = materialOptions->getLocalParamByName(param.name); // local options override material options. LocalShaderParam *localOptionsParam = localOptions->getLocalParamByName(param.name); if(localOptionsParam) { localParam = localOptionsParam; } int paramLocation = glGetUniformLocation(glslShader->shader_id, param.name.c_str()); switch(param.type) { case ProgramParam::PARAM_NUMBER: if(localParam) { glUniform1f(paramLocation, localParam->getNumber()); } else { glUniform1f(paramLocation, 0.0f); } break; case ProgramParam::PARAM_VECTOR2: if(localParam) { Vector2 vec2 = localParam->getVector2(); glUniform2f(paramLocation, vec2.x, vec2.y); } else { glUniform2f(paramLocation, 0.0f, 0.0f); } break; case ProgramParam::PARAM_VECTOR3: if(localParam) { Vector3 vec3 = localParam->getVector3(); glUniform3f(paramLocation, vec3.x, vec3.y, vec3.z); } else { glUniform3f(paramLocation, 0.0f, 0.0f, 0.0f); } break; case ProgramParam::PARAM_COLOR: if(localParam) { Color color = localParam->getColor(); glUniform4f(paramLocation, color.r, color.g, color.b, color.a); } else { glUniform4f(paramLocation, 0.0f, 0.0f, 0.0f, 0.0f); } break; case ProgramParam::PARAM_MATRIX: if(localParam) { polycodeUniformMatrix4v(paramLocation, 1, false, localParam->getMatrix4().ml); } else { Matrix4 defaultMatrix; polycodeUniformMatrix4v(paramLocation, 1, false, defaultMatrix.ml); } break; } } bool GLSLShaderModule::applyShaderMaterial(Renderer *renderer, Material *material, ShaderBinding *localOptions, unsigned int shaderIndex) { GLSLShader *glslShader = (GLSLShader*)material->getShader(shaderIndex); glPushMatrix(); glLoadIdentity(); int numRendererPointLights = renderer->getNumPointLights(); int numRendererSpotLights = renderer->getNumSpotLights(); int numTotalLights = glslShader->numPointLights + glslShader->numSpotLights; for(int i=0 ; i < numTotalLights; i++) { GLfloat resetData[] = {0.0, 0.0, 0.0, 0.0}; glLightfv (GL_LIGHT0+i, GL_DIFFUSE, resetData); glLightfv (GL_LIGHT0+i, GL_SPECULAR, resetData); glLightfv (GL_LIGHT0+i, GL_AMBIENT, resetData); glLightfv (GL_LIGHT0+i, GL_POSITION, resetData); glLightf (GL_LIGHT0+i, GL_SPOT_CUTOFF, 180); glLightf (GL_LIGHT0+i, GL_CONSTANT_ATTENUATION,1.0); glLightf (GL_LIGHT0+i, GL_LINEAR_ATTENUATION,0.0); glLightf (GL_LIGHT0+i, GL_QUADRATIC_ATTENUATION, 0.0); } int lightIndex = 0; vector<LightInfo> pointLights = renderer->getPointLights(); GLfloat ambientVal[] = {1, 1, 1, 1.0}; for(int i=0; i < glslShader->numPointLights; i++) { LightInfo light; if(i < numRendererPointLights) { light = pointLights[i]; light.position = renderer->getCameraMatrix().Inverse() * light.position; ambientVal[0] = renderer->ambientColor.r; ambientVal[1] = renderer->ambientColor.g; ambientVal[2] = renderer->ambientColor.b; ambientVal[3] = 1; GLfloat data4[] = {light.color.x * light.intensity, light.color.y * light.intensity, light.color.z * light.intensity, 1.0}; glLightfv (GL_LIGHT0+lightIndex, GL_DIFFUSE, data4); data4[0] = light.specularColor.r* light.intensity; data4[1] = light.specularColor.g* light.intensity; data4[2] = light.specularColor.b* light.intensity; data4[3] = light.specularColor.a* light.intensity; glLightfv (GL_LIGHT0+lightIndex, GL_SPECULAR, data4); data4[3] = 1.0; glLightfv (GL_LIGHT0+lightIndex, GL_AMBIENT, ambientVal); glLightf (GL_LIGHT0+lightIndex, GL_SPOT_CUTOFF, 180); data4[0] = light.position.x; data4[1] = light.position.y; data4[2] = light.position.z; glLightfv (GL_LIGHT0+lightIndex, GL_POSITION, data4); glLightf (GL_LIGHT0+lightIndex, GL_CONSTANT_ATTENUATION, light.constantAttenuation); glLightf (GL_LIGHT0+lightIndex, GL_LINEAR_ATTENUATION, light.linearAttenuation); glLightf (GL_LIGHT0+lightIndex, GL_QUADRATIC_ATTENUATION, light.quadraticAttenuation); } lightIndex++; } vector<LightInfo> spotLights = renderer->getSpotLights(); // vector<Texture*> shadowMapTextures = renderer->getShadowMapTextures(); char texName[32]; char matName[32]; int shadowMapTextureIndex = 0; glUseProgram(glslShader->shader_id); int textureIndex = 0; for(int i=0; i < glslShader->numSpotLights; i++) { LightInfo light; Vector3 pos; Vector3 dir; if(i < numRendererSpotLights) { light = spotLights[i]; pos = light.position; dir = light.dir; pos = renderer->getCameraMatrix().Inverse() * pos; dir = renderer->getCameraMatrix().Inverse().rotateVector(dir); ambientVal[0] = renderer->ambientColor.r; ambientVal[1] = renderer->ambientColor.g; ambientVal[2] = renderer->ambientColor.b; ambientVal[3] = 1; GLfloat data4[] = {light.color.x * light.intensity, light.color.y * light.intensity, light.color.z * light.intensity, 1.0}; glLightfv (GL_LIGHT0+lightIndex, GL_DIFFUSE, data4); data4[0] = light.specularColor.r* light.intensity; data4[1] = light.specularColor.g* light.intensity; data4[2] = light.specularColor.b* light.intensity; data4[3] = light.specularColor.a* light.intensity; glLightfv (GL_LIGHT0+lightIndex, GL_SPECULAR, data4); data4[3] = 1.0; glLightfv (GL_LIGHT0+lightIndex, GL_AMBIENT, ambientVal); glLightf (GL_LIGHT0+lightIndex, GL_SPOT_CUTOFF, light.spotlightCutoff); glLightf (GL_LIGHT0+lightIndex, GL_SPOT_EXPONENT, light.spotlightExponent); data4[0] = dir.x; data4[1] = dir.y; data4[2] = dir.z; glLightfv (GL_LIGHT0+lightIndex, GL_SPOT_DIRECTION, data4); data4[0] = pos.x; data4[1] = pos.y; data4[2] = pos.z; glLightfv (GL_LIGHT0+lightIndex, GL_POSITION, data4); glLightf (GL_LIGHT0+lightIndex, GL_CONSTANT_ATTENUATION, light.constantAttenuation); glLightf (GL_LIGHT0+lightIndex, GL_LINEAR_ATTENUATION, light.linearAttenuation); glLightf (GL_LIGHT0+lightIndex, GL_QUADRATIC_ATTENUATION, light.quadraticAttenuation); if(light.shadowsEnabled) { if(shadowMapTextureIndex < 4) { switch(shadowMapTextureIndex) { case 0: strcpy(texName, "shadowMap0"); strcpy(matName, "shadowMatrix0"); break; case 1: strcpy(texName, "shadowMap1"); strcpy(matName, "shadowMatrix1"); break; case 2: strcpy(texName, "shadowMap2"); strcpy(matName, "shadowMatrix2"); break; case 3: strcpy(texName, "shadowMap3"); strcpy(matName, "shadowMatrix3"); break; } int texture_location = glGetUniformLocation(glslShader->shader_id, texName); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_2D, ((OpenGLTexture*)light.shadowMapTexture)->getTextureID()); textureIndex++; int mloc = glGetUniformLocation(glslShader->shader_id, matName); light.textureMatrix = light.textureMatrix; GLfloat mat[16]; for(int z=0; z < 16; z++) { mat[z] = light.textureMatrix.ml[z]; } glUniformMatrix4fv(mloc, 1, false, mat); } shadowMapTextureIndex++; } else { light.shadowsEnabled = false; } } lightIndex++; } glPopMatrix(); glEnable(GL_TEXTURE_2D); Matrix4 modelMatrix = renderer->getModelviewMatrix() * renderer->getCameraMatrix(); int mloc = glGetUniformLocation(glslShader->shader_id, "modelMatrix"); GLfloat mat[16]; for(int z=0; z < 16; z++) { mat[z] = modelMatrix.ml[z]; } glUniformMatrix4fv(mloc, 1, false, mat); ShaderBinding *cgBinding = material->getShaderBinding(shaderIndex); for(int i=0; i < glslShader->expectedParams.size(); i++) { ProgramParam param = glslShader->expectedParams[i]; updateGLSLParam(renderer, glslShader, param, material->getShaderBinding(shaderIndex), localOptions); } for(int i=0; i < cgBinding->textures.size(); i++) { if(!localOptions->getTexture(cgBinding->textures[i].name)) { OpenGLTexture *glTexture = (OpenGLTexture*)cgBinding->textures[i].texture; if(glTexture) { int texture_location = glGetUniformLocation(glslShader->shader_id, cgBinding->textures[i].name.c_str()); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_2D, glTexture->getTextureID()); textureIndex++; } } } for(int i=0; i < cgBinding->cubemaps.size(); i++) { if(!localOptions->getCubemap(cgBinding->cubemaps[i].name)) { OpenGLCubemap *glCubemap = (OpenGLCubemap*)cgBinding->cubemaps[i].cubemap; if(glCubemap) { int texture_location = glGetUniformLocation(glslShader->shader_id, cgBinding->cubemaps[i].name.c_str()); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_CUBE_MAP, glCubemap->getTextureID()); textureIndex++; } } } for(int i=0; i < localOptions->textures.size(); i++) { OpenGLTexture *glTexture = (OpenGLTexture*)localOptions->textures[i].texture; if(glTexture) { int texture_location = glGetUniformLocation(glslShader->shader_id, localOptions->textures[i].name.c_str()); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_2D, glTexture->getTextureID()); textureIndex++; } } for(int i=0; i < localOptions->cubemaps.size(); i++) { OpenGLCubemap *glCubemap = (OpenGLCubemap*)localOptions->cubemaps[i].cubemap; if(glCubemap) { int texture_location = glGetUniformLocation(glslShader->shader_id, localOptions->cubemaps[i].name.c_str()); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_CUBE_MAP, glCubemap->getTextureID()); textureIndex++; } } return true; } void GLSLShaderModule::reloadPrograms() { for(int i=0; i < programs.size(); i++) { GLSLProgram *program = programs[i]; program->reloadProgram(); } } GLSLProgram *GLSLShaderModule::createGLSLProgram(const String& fileName, int type) { GLSLProgram *prog = new GLSLProgram(fileName, type); programs.push_back(prog); return prog; } ShaderProgram* GLSLShaderModule::createProgramFromFile(const String& extension, const String& fullPath) { if(extension == "vert") { Logger::log("Adding GLSL vertex program %s\n", fullPath.c_str()); return createGLSLProgram(fullPath, GLSLProgram::TYPE_VERT); } if(extension == "frag") { Logger::log("Adding GLSL fragment program %s\n", fullPath.c_str()); return createGLSLProgram(fullPath, GLSLProgram::TYPE_FRAG); } return NULL; } glUniformMatrix4dv doesn't exist on some systems, fixed for now with a matrix copy to float array /* Copyright (C) 2011 by Ivan Safrin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef _WINDOWS #include <windows.h> #endif #include "PolyGLHeaders.h" #include "PolyGLSLShaderModule.h" #include "PolyCoreServices.h" #include "PolyCore.h" #include "PolyResourceManager.h" #include "PolyRenderer.h" #include "PolyGLSLProgram.h" #include "PolyGLSLShader.h" #include "PolyGLCubemap.h" #include "PolyMaterial.h" #include "PolyGLTexture.h" #include "tinyxml.h" using std::vector; using namespace Polycode; #if defined(_WINDOWS) && !defined(_MINGW) PFNGLUSEPROGRAMPROC glUseProgram; PFNGLUNIFORM1IPROC glUniform1i; PFNGLUNIFORM1FPROC glUniform1f; PFNGLUNIFORM2FPROC glUniform2f; PFNGLUNIFORM3FPROC glUniform3f; PFNGLUNIFORM4FPROC glUniform4f; extern PFNGLACTIVETEXTUREPROC glActiveTexture; PFNGLCREATESHADERPROC glCreateShader; PFNGLSHADERSOURCEPROC glShaderSource; PFNGLCOMPILESHADERPROC glCompileShader; PFNGLCREATEPROGRAMPROC glCreateProgram; PFNGLATTACHSHADERPROC glAttachShader; PFNGLLINKPROGRAMPROC glLinkProgram; PFNGLDETACHSHADERPROC glDetachShader; PFNGLDELETESHADERPROC glDeleteShader; PFNGLDELETEPROGRAMPROC glDeleteProgram; PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; PFNGLGETSHADERIVPROC glGetShaderiv; PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation; #endif GLSLShaderModule::GLSLShaderModule() : PolycodeShaderModule() { #ifdef _WINDOWS glUseProgram = (PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"); glUniform1i = (PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"); glUniform1f = (PFNGLUNIFORM1FPROC)wglGetProcAddress("glUniform1f"); glUniform2f = (PFNGLUNIFORM2FPROC)wglGetProcAddress("glUniform2f"); glUniform3f = (PFNGLUNIFORM3FPROC)wglGetProcAddress("glUniform3f"); glCreateShader = (PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader"); glShaderSource = (PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource"); glCompileShader = (PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"); glCreateProgram = (PFNGLCREATEPROGRAMPROC)wglGetProcAddress("glCreateProgram"); glAttachShader = (PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader"); glLinkProgram = (PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram"); glDetachShader = (PFNGLDETACHSHADERPROC)wglGetProcAddress("glDetachShader"); glDeleteShader = (PFNGLDELETESHADERPROC)wglGetProcAddress("glDeleteShader"); glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wglGetProcAddress("glDeleteProgram"); glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wglGetProcAddress("glUniformMatrix4fv"); glGetShaderiv = (PFNGLGETSHADERIVPROC)wglGetProcAddress("glGetShaderiv"); glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wglGetProcAddress("glGetShaderInfoLog"); #ifndef _MINGW glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONARBPROC)wglGetProcAddress("glGetUniformLocation"); glUniform4f = (PFNGLUNIFORM4FPROC)wglGetProcAddress("glUniform4f"); #endif #endif } GLSLShaderModule::~GLSLShaderModule() { } bool GLSLShaderModule::acceptsExtension(const String& extension) { if(extension == "vert" || extension == "frag") { return true; } else { return false; } } String GLSLShaderModule::getShaderType() { return "glsl"; } Shader *GLSLShaderModule::createShader(ResourcePool *resourcePool, String name, String vpName, String fpName) { GLSLShader *retShader = NULL; GLSLProgram *vp = NULL; GLSLProgram *fp = NULL; vp = (GLSLProgram*)resourcePool->getResourceByPath(vpName); fp = (GLSLProgram*)resourcePool->getResourceByPath(fpName); if(vp != NULL && fp != NULL) { GLSLShader *shader = new GLSLShader(vp,fp); shader->setName(name); retShader = shader; shaders.push_back((Shader*)shader); } return retShader; } Shader *GLSLShaderModule::createShader(ResourcePool *resourcePool, TiXmlNode *node) { TiXmlNode* pChild; GLSLProgram *vp = NULL; GLSLProgram *fp = NULL; GLSLShader *retShader = NULL; TiXmlElement *nodeElement = node->ToElement(); if (!nodeElement) return NULL; // Skip comment nodes for (pChild = node->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { TiXmlElement *pChildElement = pChild->ToElement(); if (!pChildElement) continue; // Skip comment nodes if(strcmp(pChild->Value(), "vp") == 0) { String vpFileName = String(pChildElement->Attribute("source")); vp = (GLSLProgram*)resourcePool->getResourceByPath(vpFileName); if(!vp) { vp = (GLSLProgram*)CoreServices::getInstance()->getMaterialManager()->createProgramFromFile(vpFileName); if(vp) { vp->setResourcePath(vpFileName); OSFileEntry entry = OSFileEntry(vpFileName, OSFileEntry::TYPE_FILE); vp->setResourceName(entry.name); resourcePool->addResource(vp); } } } if(strcmp(pChild->Value(), "fp") == 0) { String fpFileName = String(pChildElement->Attribute("source")); fp = (GLSLProgram*)resourcePool->getResourceByPath(fpFileName); if(!fp) { fp = (GLSLProgram*)CoreServices::getInstance()->getMaterialManager()->createProgramFromFile(fpFileName); if(fp) { fp->setResourcePath(fpFileName); OSFileEntry entry = OSFileEntry(fpFileName, OSFileEntry::TYPE_FILE); fp->setResourceName(entry.name); resourcePool->addResource(fp); } } } } if(vp != NULL && fp != NULL) { GLSLShader *cgShader = new GLSLShader(vp,fp); cgShader->setName(String(nodeElement->Attribute("name"))); retShader = cgShader; shaders.push_back((Shader*)cgShader); } return retShader; } void GLSLShaderModule::clearShader() { glUseProgram(0); } void GLSLShaderModule::updateGLSLParam(Renderer *renderer, GLSLShader *glslShader, ProgramParam &param, ShaderBinding *materialOptions, ShaderBinding *localOptions) { LocalShaderParam *localParam = NULL; localParam = materialOptions->getLocalParamByName(param.name); // local options override material options. LocalShaderParam *localOptionsParam = localOptions->getLocalParamByName(param.name); if(localOptionsParam) { localParam = localOptionsParam; } int paramLocation = glGetUniformLocation(glslShader->shader_id, param.name.c_str()); switch(param.type) { case ProgramParam::PARAM_NUMBER: if(localParam) { glUniform1f(paramLocation, localParam->getNumber()); } else { glUniform1f(paramLocation, 0.0f); } break; case ProgramParam::PARAM_VECTOR2: if(localParam) { Vector2 vec2 = localParam->getVector2(); glUniform2f(paramLocation, vec2.x, vec2.y); } else { glUniform2f(paramLocation, 0.0f, 0.0f); } break; case ProgramParam::PARAM_VECTOR3: if(localParam) { Vector3 vec3 = localParam->getVector3(); glUniform3f(paramLocation, vec3.x, vec3.y, vec3.z); } else { glUniform3f(paramLocation, 0.0f, 0.0f, 0.0f); } break; case ProgramParam::PARAM_COLOR: if(localParam) { Color color = localParam->getColor(); glUniform4f(paramLocation, color.r, color.g, color.b, color.a); } else { glUniform4f(paramLocation, 0.0f, 0.0f, 0.0f, 0.0f); } break; case ProgramParam::PARAM_MATRIX: if(localParam) { #ifdef POLYCODE_NUMBER_IS_SINGLE glUniformMatrix4fv(paramLocation, 1, false, localParam->getMatrix4().ml); #else // no glUniformMatrix4dv on some systems float copyMatrix[16]; Matrix4 m = localParam->getMatrix4(); for(int i=0; i < 16; i++) { copyMatrix[i] = m.ml[i]; } glUniformMatrix4fv(paramLocation, 1, false, copyMatrix); #endif } else { Matrix4 defaultMatrix; #ifdef POLYCODE_NUMBER_IS_SINGLE getMatrix4(paramLocation, 1, false, defaultMatrix.ml); #else // no glUniformMatrix4dv on some systems float copyMatrix[16]; for(int i=0; i < 16; i++) { copyMatrix[i] = defaultMatrix.ml[i]; } glUniformMatrix4fv(paramLocation, 1, false, copyMatrix); #endif } break; } } bool GLSLShaderModule::applyShaderMaterial(Renderer *renderer, Material *material, ShaderBinding *localOptions, unsigned int shaderIndex) { GLSLShader *glslShader = (GLSLShader*)material->getShader(shaderIndex); glPushMatrix(); glLoadIdentity(); int numRendererPointLights = renderer->getNumPointLights(); int numRendererSpotLights = renderer->getNumSpotLights(); int numTotalLights = glslShader->numPointLights + glslShader->numSpotLights; for(int i=0 ; i < numTotalLights; i++) { GLfloat resetData[] = {0.0, 0.0, 0.0, 0.0}; glLightfv (GL_LIGHT0+i, GL_DIFFUSE, resetData); glLightfv (GL_LIGHT0+i, GL_SPECULAR, resetData); glLightfv (GL_LIGHT0+i, GL_AMBIENT, resetData); glLightfv (GL_LIGHT0+i, GL_POSITION, resetData); glLightf (GL_LIGHT0+i, GL_SPOT_CUTOFF, 180); glLightf (GL_LIGHT0+i, GL_CONSTANT_ATTENUATION,1.0); glLightf (GL_LIGHT0+i, GL_LINEAR_ATTENUATION,0.0); glLightf (GL_LIGHT0+i, GL_QUADRATIC_ATTENUATION, 0.0); } int lightIndex = 0; vector<LightInfo> pointLights = renderer->getPointLights(); GLfloat ambientVal[] = {1, 1, 1, 1.0}; for(int i=0; i < glslShader->numPointLights; i++) { LightInfo light; if(i < numRendererPointLights) { light = pointLights[i]; light.position = renderer->getCameraMatrix().Inverse() * light.position; ambientVal[0] = renderer->ambientColor.r; ambientVal[1] = renderer->ambientColor.g; ambientVal[2] = renderer->ambientColor.b; ambientVal[3] = 1; GLfloat data4[] = {light.color.x * light.intensity, light.color.y * light.intensity, light.color.z * light.intensity, 1.0}; glLightfv (GL_LIGHT0+lightIndex, GL_DIFFUSE, data4); data4[0] = light.specularColor.r* light.intensity; data4[1] = light.specularColor.g* light.intensity; data4[2] = light.specularColor.b* light.intensity; data4[3] = light.specularColor.a* light.intensity; glLightfv (GL_LIGHT0+lightIndex, GL_SPECULAR, data4); data4[3] = 1.0; glLightfv (GL_LIGHT0+lightIndex, GL_AMBIENT, ambientVal); glLightf (GL_LIGHT0+lightIndex, GL_SPOT_CUTOFF, 180); data4[0] = light.position.x; data4[1] = light.position.y; data4[2] = light.position.z; glLightfv (GL_LIGHT0+lightIndex, GL_POSITION, data4); glLightf (GL_LIGHT0+lightIndex, GL_CONSTANT_ATTENUATION, light.constantAttenuation); glLightf (GL_LIGHT0+lightIndex, GL_LINEAR_ATTENUATION, light.linearAttenuation); glLightf (GL_LIGHT0+lightIndex, GL_QUADRATIC_ATTENUATION, light.quadraticAttenuation); } lightIndex++; } vector<LightInfo> spotLights = renderer->getSpotLights(); // vector<Texture*> shadowMapTextures = renderer->getShadowMapTextures(); char texName[32]; char matName[32]; int shadowMapTextureIndex = 0; glUseProgram(glslShader->shader_id); int textureIndex = 0; for(int i=0; i < glslShader->numSpotLights; i++) { LightInfo light; Vector3 pos; Vector3 dir; if(i < numRendererSpotLights) { light = spotLights[i]; pos = light.position; dir = light.dir; pos = renderer->getCameraMatrix().Inverse() * pos; dir = renderer->getCameraMatrix().Inverse().rotateVector(dir); ambientVal[0] = renderer->ambientColor.r; ambientVal[1] = renderer->ambientColor.g; ambientVal[2] = renderer->ambientColor.b; ambientVal[3] = 1; GLfloat data4[] = {light.color.x * light.intensity, light.color.y * light.intensity, light.color.z * light.intensity, 1.0}; glLightfv (GL_LIGHT0+lightIndex, GL_DIFFUSE, data4); data4[0] = light.specularColor.r* light.intensity; data4[1] = light.specularColor.g* light.intensity; data4[2] = light.specularColor.b* light.intensity; data4[3] = light.specularColor.a* light.intensity; glLightfv (GL_LIGHT0+lightIndex, GL_SPECULAR, data4); data4[3] = 1.0; glLightfv (GL_LIGHT0+lightIndex, GL_AMBIENT, ambientVal); glLightf (GL_LIGHT0+lightIndex, GL_SPOT_CUTOFF, light.spotlightCutoff); glLightf (GL_LIGHT0+lightIndex, GL_SPOT_EXPONENT, light.spotlightExponent); data4[0] = dir.x; data4[1] = dir.y; data4[2] = dir.z; glLightfv (GL_LIGHT0+lightIndex, GL_SPOT_DIRECTION, data4); data4[0] = pos.x; data4[1] = pos.y; data4[2] = pos.z; glLightfv (GL_LIGHT0+lightIndex, GL_POSITION, data4); glLightf (GL_LIGHT0+lightIndex, GL_CONSTANT_ATTENUATION, light.constantAttenuation); glLightf (GL_LIGHT0+lightIndex, GL_LINEAR_ATTENUATION, light.linearAttenuation); glLightf (GL_LIGHT0+lightIndex, GL_QUADRATIC_ATTENUATION, light.quadraticAttenuation); if(light.shadowsEnabled) { if(shadowMapTextureIndex < 4) { switch(shadowMapTextureIndex) { case 0: strcpy(texName, "shadowMap0"); strcpy(matName, "shadowMatrix0"); break; case 1: strcpy(texName, "shadowMap1"); strcpy(matName, "shadowMatrix1"); break; case 2: strcpy(texName, "shadowMap2"); strcpy(matName, "shadowMatrix2"); break; case 3: strcpy(texName, "shadowMap3"); strcpy(matName, "shadowMatrix3"); break; } int texture_location = glGetUniformLocation(glslShader->shader_id, texName); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_2D, ((OpenGLTexture*)light.shadowMapTexture)->getTextureID()); textureIndex++; int mloc = glGetUniformLocation(glslShader->shader_id, matName); light.textureMatrix = light.textureMatrix; GLfloat mat[16]; for(int z=0; z < 16; z++) { mat[z] = light.textureMatrix.ml[z]; } glUniformMatrix4fv(mloc, 1, false, mat); } shadowMapTextureIndex++; } else { light.shadowsEnabled = false; } } lightIndex++; } glPopMatrix(); glEnable(GL_TEXTURE_2D); Matrix4 modelMatrix = renderer->getModelviewMatrix() * renderer->getCameraMatrix(); int mloc = glGetUniformLocation(glslShader->shader_id, "modelMatrix"); GLfloat mat[16]; for(int z=0; z < 16; z++) { mat[z] = modelMatrix.ml[z]; } glUniformMatrix4fv(mloc, 1, false, mat); ShaderBinding *cgBinding = material->getShaderBinding(shaderIndex); for(int i=0; i < glslShader->expectedParams.size(); i++) { ProgramParam param = glslShader->expectedParams[i]; updateGLSLParam(renderer, glslShader, param, material->getShaderBinding(shaderIndex), localOptions); } for(int i=0; i < cgBinding->textures.size(); i++) { if(!localOptions->getTexture(cgBinding->textures[i].name)) { OpenGLTexture *glTexture = (OpenGLTexture*)cgBinding->textures[i].texture; if(glTexture) { int texture_location = glGetUniformLocation(glslShader->shader_id, cgBinding->textures[i].name.c_str()); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_2D, glTexture->getTextureID()); textureIndex++; } } } for(int i=0; i < cgBinding->cubemaps.size(); i++) { if(!localOptions->getCubemap(cgBinding->cubemaps[i].name)) { OpenGLCubemap *glCubemap = (OpenGLCubemap*)cgBinding->cubemaps[i].cubemap; if(glCubemap) { int texture_location = glGetUniformLocation(glslShader->shader_id, cgBinding->cubemaps[i].name.c_str()); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_CUBE_MAP, glCubemap->getTextureID()); textureIndex++; } } } for(int i=0; i < localOptions->textures.size(); i++) { OpenGLTexture *glTexture = (OpenGLTexture*)localOptions->textures[i].texture; if(glTexture) { int texture_location = glGetUniformLocation(glslShader->shader_id, localOptions->textures[i].name.c_str()); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_2D, glTexture->getTextureID()); textureIndex++; } } for(int i=0; i < localOptions->cubemaps.size(); i++) { OpenGLCubemap *glCubemap = (OpenGLCubemap*)localOptions->cubemaps[i].cubemap; if(glCubemap) { int texture_location = glGetUniformLocation(glslShader->shader_id, localOptions->cubemaps[i].name.c_str()); glUniform1i(texture_location, textureIndex); glActiveTexture(GL_TEXTURE0 + textureIndex); glBindTexture(GL_TEXTURE_CUBE_MAP, glCubemap->getTextureID()); textureIndex++; } } return true; } void GLSLShaderModule::reloadPrograms() { for(int i=0; i < programs.size(); i++) { GLSLProgram *program = programs[i]; program->reloadProgram(); } } GLSLProgram *GLSLShaderModule::createGLSLProgram(const String& fileName, int type) { GLSLProgram *prog = new GLSLProgram(fileName, type); programs.push_back(prog); return prog; } ShaderProgram* GLSLShaderModule::createProgramFromFile(const String& extension, const String& fullPath) { if(extension == "vert") { Logger::log("Adding GLSL vertex program %s\n", fullPath.c_str()); return createGLSLProgram(fullPath, GLSLProgram::TYPE_VERT); } if(extension == "frag") { Logger::log("Adding GLSL fragment program %s\n", fullPath.c_str()); return createGLSLProgram(fullPath, GLSLProgram::TYPE_FRAG); } return NULL; }
// ConsoleDemo initial modification due to Damian Lyons // Code originally retrieved from SoftKinetic forum // http://www.softkinetic.com/Support/Forum/tabid/110/forumid/32/threadid/1450/scope/posts/language/en-US/Default.aspx // DepthSense 325 parameters and conversion fix - Tu-Hoa Pham (thp@pham.in) //////////////////////////////////////////////////////////////////////////////// // SoftKinetic DepthSense SDK // // COPYRIGHT AND CONFIDENTIALITY NOTICE - SOFTKINETIC CONFIDENTIAL // INFORMATION // // All rights reserved to SOFTKINETIC SENSORS NV (a // company incorporated and existing under the laws of Belgium, with // its principal place of business at Boulevard de la Plainelaan 15, // 1050 Brussels (Belgium), registered with the Crossroads bank for // enterprises under company number 0811 341 454 - "Softkinetic // Sensors"). // // The source code of the SoftKinetic DepthSense Camera Drivers is // proprietary and confidential information of Softkinetic Sensors NV. // // For any question about terms and conditions, please contact: // info@softkinetic.com Copyright (c) 2002-2012 Softkinetic Sensors NV //////////////////////////////////////////////////////////////////////////////// // Some OpenCV mods added below for viewing and saving - Damian Lyons, dlyons@fordham.edu #ifdef _MSC_VER #include <windows.h> #endif #include <stdio.h> #include <time.h> #include <vector> #include <exception> #include <DepthSense.hxx> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include "DepthSenseGrabberPCL.hxx" #include "../shared/ConversionTools.hxx" using namespace DepthSense; using namespace std; int waitSecondsBeforeGrab = 0; bool interpolateDepthFlag = 1; bool dispColorAcqFlag = 0; bool dispDepthAcqFlag = 0; bool dispColorSyncFlag = 0; bool dispDepthSyncFlag = 0; bool saveColorAcqFlag = 0; bool saveDepthAcqFlag = 1; bool saveColorSyncFlag = 1; bool saveDepthSyncFlag = 0; //int widthQVGA,heightQVGA,widthColor,heightColor; int frameRateDepth = 30; int frameRateColor = 30; int fovDepthHorizontalDeg = 74; int fovDepthVerticalDeg = 58; const int widthQVGA = 320, heightQVGA = 240; const int widthVGA = 640, heightVGA = 480; const int widthWXGA = 1280, heightWXGA = 720; const int widthNHD = 640, heightNHD = 360; const int nPixelsQVGA = widthQVGA*heightQVGA; const int nPixelsVGA = widthVGA*heightVGA; const int nPixelsWXGA = widthWXGA*heightWXGA; const int nPixelsNHD = widthNHD*heightNHD; // Acquired data uint16_t pixelsDepthAcqQVGA[nPixelsQVGA]; uint8_t pixelsColorAcqVGA[3*nPixelsVGA]; uint8_t pixelsColorAcqWXGA[3*nPixelsWXGA]; uint8_t pixelsColorAcqNHD[3*nPixelsNHD]; // UVmap-processed frames uint8_t pixelsColorSyncQVGA[3*nPixelsQVGA]; uint16_t pixelsDepthSyncQVGA[nPixelsQVGA]; uint16_t pixelsDepthSyncVGA[nPixelsVGA]; uint16_t pixelsDepthSyncWXGA[nPixelsWXGA]; uint16_t pixelsDepthSyncNHD[nPixelsNHD]; // Interpolated frames uint8_t pixelsColorSyncVGA[3*nPixelsVGA]; uint16_t pixelsDepthAcqVGA[nPixelsVGA]; FrameFormat frameFormatDepth = FRAME_FORMAT_QVGA; // Depth QVGA const int nPixelsDepthAcq = nPixelsQVGA; uint16_t* pixelsDepthAcq = pixelsDepthAcqQVGA; float depthToPosMatXQVGA[nPixelsQVGA]; float depthToPosMatYQVGA[nPixelsQVGA]; float depthToPosMatXVGA[nPixelsVGA]; float depthToPosMatYVGA[nPixelsVGA]; // Color VGA FrameFormat frameFormatColor = FRAME_FORMAT_VGA; const int widthColor = widthVGA, heightColor = heightVGA, nPixelsColorAcq = nPixelsVGA; uint8_t* pixelsColorAcq = pixelsColorAcqVGA; uint16_t* pixelsDepthSync = pixelsDepthSyncVGA; /* // Color WXGA FrameFormat frameFormatColor = FRAME_FORMAT_WXGA_H; const int widthColor = widthWXGA, heightColor = heightWXGA, nPixelsColorAcq = nPixelsWXGA; uint8_t* pixelsColorAcq = pixelsColorAcqWXGA; uint16_t* pixelsDepthSync = pixelsDepthSyncWXGA; */ /* // Color NHD FrameFormat frameFormatColor = FRAME_FORMAT_NHD; const int widthColor = widthNHD, heightColor = heightNHD, nPixelsColorAcq = nPixelsNHD; uint8_t* pixelsColorAcq = pixelsColorAcqNHD; uint16_t* pixelsDepthSync = pixelsDepthSyncNHD; */ const uint16_t noDepthDefault = 65535; const uint16_t noDepthThreshold = 2000; uint8_t noDepthBGR[3] = {255,255,255}; int colorPixelInd, colorPixelRow, colorPixelCol; int debugInt; UV uvMapAcq[nPixelsQVGA]; UV uvMapVGA[nPixelsVGA]; int timeStamp; clock_t clockStartGrab; unsigned int frameCount; Context g_context; DepthNode g_dnode; ColorNode g_cnode; AudioNode g_anode; uint32_t g_aFrames = 0; uint32_t g_cFrames = 0; uint32_t g_dFrames = 0; bool g_bDeviceFound = false; ProjectionHelper* g_pProjHelper = NULL; StereoCameraParameters g_scp; char fileNamePCL[50]; char fileNameColorAcq[50]; char fileNameDepthAcq[50]; char fileNameColorSync[50]; char fileNameDepthSync[50]; char baseNamePCL[20] = "pclFrame_0_"; char baseNameColorAcq[20] = "colorAcqFrame_0_"; char baseNameDepthAcq[20] = "depthFrame_0_"; char baseNameColorSync[20] = "colorFrame_0_"; char baseNameDepthSync[20] = "depthSyncFrame_0_"; /*----------------------------------------------------------------------------*/ // New audio sample event handler void onNewAudioSample(AudioNode node, AudioNode::NewSampleReceivedData data) { g_aFrames++; } /*----------------------------------------------------------------------------*/ // New color sample event handler /* Comments from SoftKinetic From data you can get ::DepthSense::Pointer< uint8_t > colorMap The color map. If captureConfiguration::compression is DepthSense::COMPRESSION_TYPE_MJPEG, the output format is BGR, otherwise the output format is YUY2. */ void onNewColorSample(ColorNode node, ColorNode::NewSampleReceivedData data) { for (int currentPixelInd = 0; currentPixelInd < nPixelsColorAcq; currentPixelInd++) { // Reinitialize synchronized depth pixelsDepthSync[currentPixelInd] = noDepthDefault; pixelsColorAcq[3*currentPixelInd] = data.colorMap[3*currentPixelInd+2]; pixelsColorAcq[3*currentPixelInd+1] = data.colorMap[3*currentPixelInd+1]; pixelsColorAcq[3*currentPixelInd+2] = data.colorMap[3*currentPixelInd]; } g_cFrames++; } /*----------------------------------------------------------------------------*/ // New depth sample event handler /* From SoftKinetic ::DepthSense::Pointer< int16_t > depthMap The depth map in fixed point format. This map represents the cartesian depth of each pixel, expressed in millimeters. Valid values lies in the range [0 - 31999]. Saturated pixels are given the special value 32002. • ::DepthSense::Pointer< float > depthMapFloatingPoint The depth map in floating point format. This map represents the cartesian depth of each pixel, expressed in meters. Saturated pixels are given the special value -2.0. */ void onNewDepthSample(DepthNode node, DepthNode::NewSampleReceivedData data) { timeStamp = (int) (((float)(1000*(clock()-clockStartGrab)))/CLOCKS_PER_SEC); /* for (int currentPixelInd = 0; currentPixelInd < nPixelsDepthVGA; currentPixelInd++) { pixelsDepthSyncWXGA[currentPixelInd] = noDepthDefault; } */ // Initialize raw depth and UV maps for (int currentPixelInd = 0; currentPixelInd < nPixelsDepthAcq; currentPixelInd++) { pixelsDepthSyncQVGA[currentPixelInd] = noDepthDefault; uvMapAcq[currentPixelInd] = data.uvMap[currentPixelInd]; if (data.depthMap[currentPixelInd] < noDepthThreshold) pixelsDepthAcq[currentPixelInd] = data.depthMap[currentPixelInd]; else pixelsDepthAcq[currentPixelInd] = noDepthDefault; if (interpolateDepthFlag == 0) { pixelsColorSyncQVGA[3*currentPixelInd] = noDepthBGR[2]; pixelsColorSyncQVGA[3*currentPixelInd+1] = noDepthBGR[1]; pixelsColorSyncQVGA[3*currentPixelInd+2] = noDepthBGR[0]; } } if (interpolateDepthFlag) { rescaleDepth(pixelsDepthAcq, pixelsDepthAcqVGA, widthQVGA, heightQVGA, widthVGA, heightVGA); rescaleUV(uvMapAcq, uvMapVGA, widthQVGA, heightQVGA, widthVGA, heightVGA); for (int currentPixelInd = 0; currentPixelInd < nPixelsVGA; currentPixelInd++) { uvToColorPixelInd(uvMapVGA[currentPixelInd], widthColor, heightColor, &colorPixelInd, &colorPixelRow, &colorPixelCol); if (colorPixelInd == -1) { pixelsColorSyncVGA[3*currentPixelInd] = noDepthBGR[2]; pixelsColorSyncVGA[3*currentPixelInd+1] = noDepthBGR[1]; pixelsColorSyncVGA[3*currentPixelInd+2] = noDepthBGR[0]; } else { pixelsDepthSync[colorPixelInd] = pixelsDepthAcqVGA[currentPixelInd]; pixelsColorSyncVGA[3*currentPixelInd] = pixelsColorAcq[3*colorPixelInd]; pixelsColorSyncVGA[3*currentPixelInd+1] = pixelsColorAcq[3*colorPixelInd+1]; pixelsColorSyncVGA[3*currentPixelInd+2] = pixelsColorAcq[3*colorPixelInd+2]; } } } else { for (int currentPixelInd = 0; currentPixelInd < nPixelsQVGA; currentPixelInd++) { uvToColorPixelInd(uvMapAcq[currentPixelInd], widthColor, heightColor, &colorPixelInd, &colorPixelRow, &colorPixelCol); if (colorPixelInd != -1) { pixelsDepthSync[colorPixelInd] = pixelsDepthAcq[currentPixelInd]; pixelsColorSyncQVGA[3*currentPixelInd] = pixelsColorAcq[3*colorPixelInd]; pixelsColorSyncQVGA[3*currentPixelInd+1] = pixelsColorAcq[3*colorPixelInd+1]; pixelsColorSyncQVGA[3*currentPixelInd+2] = pixelsColorAcq[3*colorPixelInd+2]; } } } g_dFrames++; pcl::PointCloud<pcl::PointXYZRGB> cloud; if (interpolateDepthFlag) { // Fill in the cloud data cloud.width = widthVGA; cloud.height = heightVGA; cloud.is_dense = false; cloud.points.resize (cloud.width * cloud.height); //for (size_t currentPixelInd = 0; currentPixelInd < cloud.points.size (); currentPixelInd++) //{ // cloud.points[currentPixelInd].z = (float) pixelsDepthAcqVGA[currentPixelInd]; // cloud.points[currentPixelInd].x = cloud.points[currentPixelInd].z*depthToPosMatXVGA[currentPixelInd]; // cloud.points[currentPixelInd].y = cloud.points[currentPixelInd].z*depthToPosMatYVGA[currentPixelInd]; // cloud.points[currentPixelInd].rgb = packRGB(&pixelsColorSyncVGA[3*currentPixelInd]); //} size_t currentPixelInd = 0; for (int i = 0; i < heightVGA; i++) { for (int j = 0; j < widthVGA; j++) { cloud.points[currentPixelInd].z = (float) pixelsDepthAcqVGA[currentPixelInd]; //cloud.points[currentPixelInd].x = 100*depthToPosMatXVGA[currentPixelInd]; //cloud.points[currentPixelInd].y = 100*depthToPosMatYVGA[currentPixelInd]; cloud.points[currentPixelInd].x = cloud.points[currentPixelInd].z*depthToPosMatXVGA[currentPixelInd]; cloud.points[currentPixelInd].y = cloud.points[currentPixelInd].z*depthToPosMatYVGA[currentPixelInd]; //cloud.points[currentPixelInd].x = (float) j; //cloud.points[currentPixelInd].y = (float) i; cloud.points[currentPixelInd].rgb = packRGB(&pixelsColorSyncVGA[3*currentPixelInd]); currentPixelInd++; } } } else { // Fill in the cloud data cloud.width = widthQVGA; cloud.height = heightQVGA; cloud.is_dense = false; cloud.points.resize (cloud.width * cloud.height); for (size_t i = 0; i < cloud.points.size (); ++i) { cloud.points[i].z = ((float) pixelsDepthAcqQVGA[i]); cloud.points[i].x = cloud.points[i].z*depthToPosMatXQVGA[i]; cloud.points[i].y = cloud.points[i].z*depthToPosMatYQVGA[i]; cloud.points[i].rgb = packRGB(&pixelsColorSyncQVGA[3*i]); } } sprintf(fileNamePCL,"%s%05u.pcd",baseNamePCL,frameCount); pcl::io::savePCDFileASCII (fileNamePCL, cloud); // if (saveDepthAcqFlag) { // sprintf(fileNameDepthAcq,"%s%05u.pnm",baseNameDepthAcq,frameCount); // if (interpolateDepthFlag) saveRawDepthFrame(fileNameDepthAcq, pixelsDepthAcqVGA, widthVGA, heightVGA, timeStamp); // else saveRawDepthFrame(fileNameDepthAcq, pixelsDepthAcq, widthQVGA, heightQVGA, timeStamp); // } // if (saveColorAcqFlag) { // sprintf(fileNameColorAcq,"%s%05u.pnm",baseNameColorAcq,frameCount); // saveRawColorFrame(fileNameColorAcq, pixelsColorAcq, widthColor, heightColor, timeStamp); // } // if (saveDepthSyncFlag) { // sprintf(fileNameDepthSync,"%s%05u.pnm",baseNameDepthSync,frameCount); // saveRawDepthFrame(fileNameDepthSync, pixelsDepthSync, widthColor, heightColor, timeStamp); // } // if (saveColorSyncFlag) { // sprintf(fileNameColorSync,"%s%05u.pnm",baseNameColorSync,frameCount); // if (interpolateDepthFlag) saveRawColorFrame(fileNameColorSync, pixelsColorSyncVGA, widthVGA, heightVGA, timeStamp); // else saveRawColorFrame(fileNameColorSync, pixelsColorSyncQVGA, widthQVGA, heightQVGA, timeStamp); // } frameCount++; } /*----------------------------------------------------------------------------*/ void configureAudioNode() { g_anode.newSampleReceivedEvent().connect(&onNewAudioSample); AudioNode::Configuration config = g_anode.getConfiguration(); config.sampleRate = 44100; try { g_context.requestControl(g_anode,0); g_anode.setConfiguration(config); g_anode.setInputMixerLevel(0.5f); } catch (ArgumentException& e) { printf("Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("Unauthorized Access Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ void configureDepthNode() { g_dnode.newSampleReceivedEvent().connect(&onNewDepthSample); DepthNode::Configuration config = g_dnode.getConfiguration(); config.frameFormat = frameFormatDepth; config.framerate = frameRateDepth; config.mode = DepthNode::CAMERA_MODE_CLOSE_MODE; config.saturation = true; g_dnode.setEnableDepthMap(true); g_dnode.setEnableUvMap(true); try { g_context.requestControl(g_dnode,0); g_dnode.setConfiguration(config); } catch (ArgumentException& e) { printf("DEPTH Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("DEPTH Unauthorized Access Exception: %s\n",e.what()); } catch (IOException& e) { printf("DEPTH IO Exception: %s\n",e.what()); } catch (InvalidOperationException& e) { printf("DEPTH Invalid Operation Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("DEPTH Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("DEPTH Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("DEPTH TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ void configureColorNode() { // connect new color sample handler g_cnode.newSampleReceivedEvent().connect(&onNewColorSample); ColorNode::Configuration config = g_cnode.getConfiguration(); config.frameFormat = frameFormatColor; config.compression = COMPRESSION_TYPE_MJPEG; // can also be COMPRESSION_TYPE_YUY2 config.powerLineFrequency = POWER_LINE_FREQUENCY_50HZ; config.framerate = frameRateColor; g_cnode.setEnableColorMap(true); try { g_context.requestControl(g_cnode,0); g_cnode.setConfiguration(config); g_cnode.setBrightness(0); g_cnode.setContrast(5); g_cnode.setSaturation(5); g_cnode.setHue(0); g_cnode.setGamma(3); g_cnode.setWhiteBalance(4650); g_cnode.setSharpness(5); g_cnode.setWhiteBalanceAuto(true); } catch (ArgumentException& e) { printf("COLOR Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("COLOR Unauthorized Access Exception: %s\n",e.what()); } catch (IOException& e) { printf("COLOR IO Exception: %s\n",e.what()); } catch (InvalidOperationException& e) { printf("COLOR Invalid Operation Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("COLOR Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("COLOR Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("COLOR TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ void configureNode(Node node) { if ((node.is<DepthNode>())&&(!g_dnode.isSet())) { g_dnode = node.as<DepthNode>(); configureDepthNode(); g_context.registerNode(node); } if ((node.is<ColorNode>())&&(!g_cnode.isSet())) { g_cnode = node.as<ColorNode>(); configureColorNode(); g_context.registerNode(node); } if ((node.is<AudioNode>())&&(!g_anode.isSet())) { g_anode = node.as<AudioNode>(); configureAudioNode(); //g_context.registerNode(node); // switch this off to save bandwidth } } /*----------------------------------------------------------------------------*/ void onNodeConnected(Device device, Device::NodeAddedData data) { configureNode(data.node); } /*----------------------------------------------------------------------------*/ void onNodeDisconnected(Device device, Device::NodeRemovedData data) { if (data.node.is<AudioNode>() && (data.node.as<AudioNode>() == g_anode)) g_anode.unset(); if (data.node.is<ColorNode>() && (data.node.as<ColorNode>() == g_cnode)) g_cnode.unset(); if (data.node.is<DepthNode>() && (data.node.as<DepthNode>() == g_dnode)) g_dnode.unset(); printf("Node disconnected\n"); } /*----------------------------------------------------------------------------*/ void onDeviceConnected(Context context, Context::DeviceAddedData data) { if (!g_bDeviceFound) { data.device.nodeAddedEvent().connect(&onNodeConnected); data.device.nodeRemovedEvent().connect(&onNodeDisconnected); g_bDeviceFound = true; } } /*----------------------------------------------------------------------------*/ void onDeviceDisconnected(Context context, Context::DeviceRemovedData data) { g_bDeviceFound = false; printf("Device disconnected\n"); } /*----------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { calcDepthToPosMat(depthToPosMatXQVGA,depthToPosMatYQVGA,fovDepthHorizontalDeg,fovDepthVerticalDeg,widthQVGA,heightQVGA); calcDepthToPosMat(depthToPosMatXVGA,depthToPosMatYVGA,fovDepthHorizontalDeg,fovDepthVerticalDeg,widthVGA,heightVGA); g_context = Context::create("localhost"); g_context.deviceAddedEvent().connect(&onDeviceConnected); g_context.deviceRemovedEvent().connect(&onDeviceDisconnected); // Get the list of currently connected devices vector<Device> da = g_context.getDevices(); // We are only interested in the first device if (da.size() >= 1) { g_bDeviceFound = true; da[0].nodeAddedEvent().connect(&onNodeConnected); da[0].nodeRemovedEvent().connect(&onNodeDisconnected); vector<Node> na = da[0].getNodes(); printf("Found %lu nodes\n",na.size()); for (int n = 0; n < (int)na.size(); n++) configureNode(na[n]); } printf("dml@Fordham version of DS ConsoleDemo. June 2013.\n"); printf("Updated Feb. 2014 (THP).\n"); printf("Click onto in image for commands. ESC to exit.\n"); printf("Use \'W\' or \'w\' to toggle frame dumping.\n"); clockStartGrab = clock()+CLOCKS_PER_SEC*waitSecondsBeforeGrab; g_context.startNodes(); printf("Waiting %i seconds before grabbing...\n",waitSecondsBeforeGrab); while (clock() < clockStartGrab); printf("Now grabbing!\n"); g_context.run(); g_context.stopNodes(); if (g_cnode.isSet()) g_context.unregisterNode(g_cnode); if (g_dnode.isSet()) g_context.unregisterNode(g_dnode); if (g_anode.isSet()) g_context.unregisterNode(g_anode); if (g_pProjHelper) delete g_pProjHelper; return 0; } PCL export to binary files // ConsoleDemo initial modification due to Damian Lyons // Code originally retrieved from SoftKinetic forum // http://www.softkinetic.com/Support/Forum/tabid/110/forumid/32/threadid/1450/scope/posts/language/en-US/Default.aspx // DepthSense 325 parameters and conversion fix - Tu-Hoa Pham (thp@pham.in) //////////////////////////////////////////////////////////////////////////////// // SoftKinetic DepthSense SDK // // COPYRIGHT AND CONFIDENTIALITY NOTICE - SOFTKINETIC CONFIDENTIAL // INFORMATION // // All rights reserved to SOFTKINETIC SENSORS NV (a // company incorporated and existing under the laws of Belgium, with // its principal place of business at Boulevard de la Plainelaan 15, // 1050 Brussels (Belgium), registered with the Crossroads bank for // enterprises under company number 0811 341 454 - "Softkinetic // Sensors"). // // The source code of the SoftKinetic DepthSense Camera Drivers is // proprietary and confidential information of Softkinetic Sensors NV. // // For any question about terms and conditions, please contact: // info@softkinetic.com Copyright (c) 2002-2012 Softkinetic Sensors NV //////////////////////////////////////////////////////////////////////////////// // Some OpenCV mods added below for viewing and saving - Damian Lyons, dlyons@fordham.edu #ifdef _MSC_VER #include <windows.h> #endif #include <stdio.h> #include <time.h> #include <vector> #include <exception> #include <DepthSense.hxx> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include "DepthSenseGrabberPCL.hxx" #include "../shared/ConversionTools.hxx" using namespace DepthSense; using namespace std; int waitSecondsBeforeGrab = 0; bool interpolateDepthFlag = 1; bool dispColorAcqFlag = 0; bool dispDepthAcqFlag = 0; bool dispColorSyncFlag = 0; bool dispDepthSyncFlag = 0; bool saveColorAcqFlag = 0; bool saveDepthAcqFlag = 1; bool saveColorSyncFlag = 1; bool saveDepthSyncFlag = 0; //int widthQVGA,heightQVGA,widthColor,heightColor; int frameRateDepth = 30; int frameRateColor = 30; int fovDepthHorizontalDeg = 74; int fovDepthVerticalDeg = 58; const int widthQVGA = 320, heightQVGA = 240; const int widthVGA = 640, heightVGA = 480; const int widthWXGA = 1280, heightWXGA = 720; const int widthNHD = 640, heightNHD = 360; const int nPixelsQVGA = widthQVGA*heightQVGA; const int nPixelsVGA = widthVGA*heightVGA; const int nPixelsWXGA = widthWXGA*heightWXGA; const int nPixelsNHD = widthNHD*heightNHD; // Acquired data uint16_t pixelsDepthAcqQVGA[nPixelsQVGA]; uint8_t pixelsColorAcqVGA[3*nPixelsVGA]; uint8_t pixelsColorAcqWXGA[3*nPixelsWXGA]; uint8_t pixelsColorAcqNHD[3*nPixelsNHD]; // UVmap-processed frames uint8_t pixelsColorSyncQVGA[3*nPixelsQVGA]; uint16_t pixelsDepthSyncQVGA[nPixelsQVGA]; uint16_t pixelsDepthSyncVGA[nPixelsVGA]; uint16_t pixelsDepthSyncWXGA[nPixelsWXGA]; uint16_t pixelsDepthSyncNHD[nPixelsNHD]; // Interpolated frames uint8_t pixelsColorSyncVGA[3*nPixelsVGA]; uint16_t pixelsDepthAcqVGA[nPixelsVGA]; FrameFormat frameFormatDepth = FRAME_FORMAT_QVGA; // Depth QVGA const int nPixelsDepthAcq = nPixelsQVGA; uint16_t* pixelsDepthAcq = pixelsDepthAcqQVGA; float depthToPosMatXQVGA[nPixelsQVGA]; float depthToPosMatYQVGA[nPixelsQVGA]; float depthToPosMatXVGA[nPixelsVGA]; float depthToPosMatYVGA[nPixelsVGA]; // Color VGA FrameFormat frameFormatColor = FRAME_FORMAT_VGA; const int widthColor = widthVGA, heightColor = heightVGA, nPixelsColorAcq = nPixelsVGA; uint8_t* pixelsColorAcq = pixelsColorAcqVGA; uint16_t* pixelsDepthSync = pixelsDepthSyncVGA; /* // Color WXGA FrameFormat frameFormatColor = FRAME_FORMAT_WXGA_H; const int widthColor = widthWXGA, heightColor = heightWXGA, nPixelsColorAcq = nPixelsWXGA; uint8_t* pixelsColorAcq = pixelsColorAcqWXGA; uint16_t* pixelsDepthSync = pixelsDepthSyncWXGA; */ /* // Color NHD FrameFormat frameFormatColor = FRAME_FORMAT_NHD; const int widthColor = widthNHD, heightColor = heightNHD, nPixelsColorAcq = nPixelsNHD; uint8_t* pixelsColorAcq = pixelsColorAcqNHD; uint16_t* pixelsDepthSync = pixelsDepthSyncNHD; */ const uint16_t noDepthDefault = 65535; const uint16_t noDepthThreshold = 2000; uint8_t noDepthBGR[3] = {255,255,255}; int colorPixelInd, colorPixelRow, colorPixelCol; int debugInt; UV uvMapAcq[nPixelsQVGA]; UV uvMapVGA[nPixelsVGA]; int timeStamp; clock_t clockStartGrab; unsigned int frameCount; Context g_context; DepthNode g_dnode; ColorNode g_cnode; AudioNode g_anode; uint32_t g_aFrames = 0; uint32_t g_cFrames = 0; uint32_t g_dFrames = 0; bool g_bDeviceFound = false; ProjectionHelper* g_pProjHelper = NULL; StereoCameraParameters g_scp; char fileNamePCL[50]; char fileNameColorAcq[50]; char fileNameDepthAcq[50]; char fileNameColorSync[50]; char fileNameDepthSync[50]; char baseNamePCL[20] = "pclFrame_0_"; char baseNameColorAcq[20] = "colorAcqFrame_0_"; char baseNameDepthAcq[20] = "depthFrame_0_"; char baseNameColorSync[20] = "colorFrame_0_"; char baseNameDepthSync[20] = "depthSyncFrame_0_"; /*----------------------------------------------------------------------------*/ // New audio sample event handler void onNewAudioSample(AudioNode node, AudioNode::NewSampleReceivedData data) { g_aFrames++; } /*----------------------------------------------------------------------------*/ // New color sample event handler /* Comments from SoftKinetic From data you can get ::DepthSense::Pointer< uint8_t > colorMap The color map. If captureConfiguration::compression is DepthSense::COMPRESSION_TYPE_MJPEG, the output format is BGR, otherwise the output format is YUY2. */ void onNewColorSample(ColorNode node, ColorNode::NewSampleReceivedData data) { for (int currentPixelInd = 0; currentPixelInd < nPixelsColorAcq; currentPixelInd++) { // Reinitialize synchronized depth pixelsDepthSync[currentPixelInd] = noDepthDefault; pixelsColorAcq[3*currentPixelInd] = data.colorMap[3*currentPixelInd+2]; pixelsColorAcq[3*currentPixelInd+1] = data.colorMap[3*currentPixelInd+1]; pixelsColorAcq[3*currentPixelInd+2] = data.colorMap[3*currentPixelInd]; } g_cFrames++; } /*----------------------------------------------------------------------------*/ // New depth sample event handler /* From SoftKinetic ::DepthSense::Pointer< int16_t > depthMap The depth map in fixed point format. This map represents the cartesian depth of each pixel, expressed in millimeters. Valid values lies in the range [0 - 31999]. Saturated pixels are given the special value 32002. • ::DepthSense::Pointer< float > depthMapFloatingPoint The depth map in floating point format. This map represents the cartesian depth of each pixel, expressed in meters. Saturated pixels are given the special value -2.0. */ void onNewDepthSample(DepthNode node, DepthNode::NewSampleReceivedData data) { timeStamp = (int) (((float)(1000*(clock()-clockStartGrab)))/CLOCKS_PER_SEC); /* for (int currentPixelInd = 0; currentPixelInd < nPixelsDepthVGA; currentPixelInd++) { pixelsDepthSyncWXGA[currentPixelInd] = noDepthDefault; } */ // Initialize raw depth and UV maps for (int currentPixelInd = 0; currentPixelInd < nPixelsDepthAcq; currentPixelInd++) { pixelsDepthSyncQVGA[currentPixelInd] = noDepthDefault; uvMapAcq[currentPixelInd] = data.uvMap[currentPixelInd]; if (data.depthMap[currentPixelInd] < noDepthThreshold) pixelsDepthAcq[currentPixelInd] = data.depthMap[currentPixelInd]; else pixelsDepthAcq[currentPixelInd] = noDepthDefault; if (interpolateDepthFlag == 0) { pixelsColorSyncQVGA[3*currentPixelInd] = noDepthBGR[2]; pixelsColorSyncQVGA[3*currentPixelInd+1] = noDepthBGR[1]; pixelsColorSyncQVGA[3*currentPixelInd+2] = noDepthBGR[0]; } } if (interpolateDepthFlag) { rescaleDepth(pixelsDepthAcq, pixelsDepthAcqVGA, widthQVGA, heightQVGA, widthVGA, heightVGA); rescaleUV(uvMapAcq, uvMapVGA, widthQVGA, heightQVGA, widthVGA, heightVGA); for (int currentPixelInd = 0; currentPixelInd < nPixelsVGA; currentPixelInd++) { uvToColorPixelInd(uvMapVGA[currentPixelInd], widthColor, heightColor, &colorPixelInd, &colorPixelRow, &colorPixelCol); if (colorPixelInd == -1) { pixelsColorSyncVGA[3*currentPixelInd] = noDepthBGR[2]; pixelsColorSyncVGA[3*currentPixelInd+1] = noDepthBGR[1]; pixelsColorSyncVGA[3*currentPixelInd+2] = noDepthBGR[0]; } else { pixelsDepthSync[colorPixelInd] = pixelsDepthAcqVGA[currentPixelInd]; pixelsColorSyncVGA[3*currentPixelInd] = pixelsColorAcq[3*colorPixelInd]; pixelsColorSyncVGA[3*currentPixelInd+1] = pixelsColorAcq[3*colorPixelInd+1]; pixelsColorSyncVGA[3*currentPixelInd+2] = pixelsColorAcq[3*colorPixelInd+2]; } } } else { for (int currentPixelInd = 0; currentPixelInd < nPixelsQVGA; currentPixelInd++) { uvToColorPixelInd(uvMapAcq[currentPixelInd], widthColor, heightColor, &colorPixelInd, &colorPixelRow, &colorPixelCol); if (colorPixelInd != -1) { pixelsDepthSync[colorPixelInd] = pixelsDepthAcq[currentPixelInd]; pixelsColorSyncQVGA[3*currentPixelInd] = pixelsColorAcq[3*colorPixelInd]; pixelsColorSyncQVGA[3*currentPixelInd+1] = pixelsColorAcq[3*colorPixelInd+1]; pixelsColorSyncQVGA[3*currentPixelInd+2] = pixelsColorAcq[3*colorPixelInd+2]; } } } g_dFrames++; pcl::PointCloud<pcl::PointXYZRGB> cloud; if (interpolateDepthFlag) { // Fill in the cloud data cloud.width = widthVGA; cloud.height = heightVGA; cloud.is_dense = false; cloud.points.resize (cloud.width * cloud.height); for (int currentPixelInd = 0; currentPixelInd < cloud.points.size (); currentPixelInd++) { cloud.points[currentPixelInd].z = (float) pixelsDepthAcqVGA[currentPixelInd]; cloud.points[currentPixelInd].x = cloud.points[currentPixelInd].z*depthToPosMatXVGA[currentPixelInd]; cloud.points[currentPixelInd].y = cloud.points[currentPixelInd].z*depthToPosMatYVGA[currentPixelInd]; cloud.points[currentPixelInd].rgb = packRGB(&pixelsColorSyncVGA[3*currentPixelInd]); } } else { // Fill in the cloud data cloud.width = widthQVGA; cloud.height = heightQVGA; cloud.is_dense = false; cloud.points.resize (cloud.width * cloud.height); for (int currentPixelInd = 0; currentPixelInd < cloud.points.size (); currentPixelInd++) { cloud.points[currentPixelInd].z = (float) pixelsDepthAcqQVGA[currentPixelInd]; cloud.points[currentPixelInd].x = cloud.points[currentPixelInd].z*depthToPosMatXQVGA[currentPixelInd]; cloud.points[currentPixelInd].y = cloud.points[currentPixelInd].z*depthToPosMatYQVGA[currentPixelInd]; cloud.points[currentPixelInd].rgb = packRGB(&pixelsColorSyncQVGA[3*currentPixelInd]); } //for (size_t i = 0; i < cloud.points.size (); ++i) //{ // cloud.points[i].z = ((float) pixelsDepthAcqQVGA[i]); // cloud.points[i].x = cloud.points[i].z*depthToPosMatXQVGA[i]; // cloud.points[i].y = cloud.points[i].z*depthToPosMatYQVGA[i]; // cloud.points[i].rgb = packRGB(&pixelsColorSyncQVGA[3*i]); //} } sprintf(fileNamePCL,"%s%05u.pcd",baseNamePCL,frameCount); pcl::io::savePCDFileBinary(fileNamePCL, cloud); frameCount++; } /*----------------------------------------------------------------------------*/ void configureAudioNode() { g_anode.newSampleReceivedEvent().connect(&onNewAudioSample); AudioNode::Configuration config = g_anode.getConfiguration(); config.sampleRate = 44100; try { g_context.requestControl(g_anode,0); g_anode.setConfiguration(config); g_anode.setInputMixerLevel(0.5f); } catch (ArgumentException& e) { printf("Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("Unauthorized Access Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ void configureDepthNode() { g_dnode.newSampleReceivedEvent().connect(&onNewDepthSample); DepthNode::Configuration config = g_dnode.getConfiguration(); config.frameFormat = frameFormatDepth; config.framerate = frameRateDepth; config.mode = DepthNode::CAMERA_MODE_CLOSE_MODE; config.saturation = true; g_dnode.setEnableDepthMap(true); g_dnode.setEnableUvMap(true); try { g_context.requestControl(g_dnode,0); g_dnode.setConfiguration(config); } catch (ArgumentException& e) { printf("DEPTH Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("DEPTH Unauthorized Access Exception: %s\n",e.what()); } catch (IOException& e) { printf("DEPTH IO Exception: %s\n",e.what()); } catch (InvalidOperationException& e) { printf("DEPTH Invalid Operation Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("DEPTH Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("DEPTH Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("DEPTH TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ void configureColorNode() { // connect new color sample handler g_cnode.newSampleReceivedEvent().connect(&onNewColorSample); ColorNode::Configuration config = g_cnode.getConfiguration(); config.frameFormat = frameFormatColor; config.compression = COMPRESSION_TYPE_MJPEG; // can also be COMPRESSION_TYPE_YUY2 config.powerLineFrequency = POWER_LINE_FREQUENCY_50HZ; config.framerate = frameRateColor; g_cnode.setEnableColorMap(true); try { g_context.requestControl(g_cnode,0); g_cnode.setConfiguration(config); g_cnode.setBrightness(0); g_cnode.setContrast(5); g_cnode.setSaturation(5); g_cnode.setHue(0); g_cnode.setGamma(3); g_cnode.setWhiteBalance(4650); g_cnode.setSharpness(5); g_cnode.setWhiteBalanceAuto(true); } catch (ArgumentException& e) { printf("COLOR Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("COLOR Unauthorized Access Exception: %s\n",e.what()); } catch (IOException& e) { printf("COLOR IO Exception: %s\n",e.what()); } catch (InvalidOperationException& e) { printf("COLOR Invalid Operation Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("COLOR Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("COLOR Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("COLOR TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ void configureNode(Node node) { if ((node.is<DepthNode>())&&(!g_dnode.isSet())) { g_dnode = node.as<DepthNode>(); configureDepthNode(); g_context.registerNode(node); } if ((node.is<ColorNode>())&&(!g_cnode.isSet())) { g_cnode = node.as<ColorNode>(); configureColorNode(); g_context.registerNode(node); } if ((node.is<AudioNode>())&&(!g_anode.isSet())) { g_anode = node.as<AudioNode>(); configureAudioNode(); //g_context.registerNode(node); // switch this off to save bandwidth } } /*----------------------------------------------------------------------------*/ void onNodeConnected(Device device, Device::NodeAddedData data) { configureNode(data.node); } /*----------------------------------------------------------------------------*/ void onNodeDisconnected(Device device, Device::NodeRemovedData data) { if (data.node.is<AudioNode>() && (data.node.as<AudioNode>() == g_anode)) g_anode.unset(); if (data.node.is<ColorNode>() && (data.node.as<ColorNode>() == g_cnode)) g_cnode.unset(); if (data.node.is<DepthNode>() && (data.node.as<DepthNode>() == g_dnode)) g_dnode.unset(); printf("Node disconnected\n"); } /*----------------------------------------------------------------------------*/ void onDeviceConnected(Context context, Context::DeviceAddedData data) { if (!g_bDeviceFound) { data.device.nodeAddedEvent().connect(&onNodeConnected); data.device.nodeRemovedEvent().connect(&onNodeDisconnected); g_bDeviceFound = true; } } /*----------------------------------------------------------------------------*/ void onDeviceDisconnected(Context context, Context::DeviceRemovedData data) { g_bDeviceFound = false; printf("Device disconnected\n"); } /*----------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { calcDepthToPosMat(depthToPosMatXQVGA,depthToPosMatYQVGA,fovDepthHorizontalDeg,fovDepthVerticalDeg,widthQVGA,heightQVGA); calcDepthToPosMat(depthToPosMatXVGA,depthToPosMatYVGA,fovDepthHorizontalDeg,fovDepthVerticalDeg,widthVGA,heightVGA); g_context = Context::create("localhost"); g_context.deviceAddedEvent().connect(&onDeviceConnected); g_context.deviceRemovedEvent().connect(&onDeviceDisconnected); // Get the list of currently connected devices vector<Device> da = g_context.getDevices(); // We are only interested in the first device if (da.size() >= 1) { g_bDeviceFound = true; da[0].nodeAddedEvent().connect(&onNodeConnected); da[0].nodeRemovedEvent().connect(&onNodeDisconnected); vector<Node> na = da[0].getNodes(); printf("Found %lu nodes\n",na.size()); for (int n = 0; n < (int)na.size(); n++) configureNode(na[n]); } printf("dml@Fordham version of DS ConsoleDemo. June 2013.\n"); printf("Updated Feb. 2014 (THP).\n"); printf("Click onto in image for commands. ESC to exit.\n"); printf("Use \'W\' or \'w\' to toggle frame dumping.\n"); clockStartGrab = clock()+CLOCKS_PER_SEC*waitSecondsBeforeGrab; g_context.startNodes(); printf("Waiting %i seconds before grabbing...\n",waitSecondsBeforeGrab); while (clock() < clockStartGrab); printf("Now grabbing!\n"); g_context.run(); g_context.stopNodes(); if (g_cnode.isSet()) g_context.unregisterNode(g_cnode); if (g_dnode.isSet()) g_context.unregisterNode(g_dnode); if (g_anode.isSet()) g_context.unregisterNode(g_anode); if (g_pProjHelper) delete g_pProjHelper; return 0; }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "materials/processedMaterial.h" #include "materials/sceneData.h" #include "materials/materialParameters.h" #include "materials/matTextureTarget.h" #include "materials/materialFeatureTypes.h" #include "materials/materialManager.h" #include "scene/sceneRenderState.h" #include "gfx/gfxPrimitiveBuffer.h" #include "gfx/gfxTextureManager.h" #include "gfx/sim/cubemapData.h" RenderPassData::RenderPassData() { reset(); } void RenderPassData::reset() { for( U32 i = 0; i < Material::MAX_TEX_PER_PASS; ++ i ) { destructInPlace( &mTexSlot[ i ] ); mSamplerNames[ i ].clear(); } dMemset( &mTexSlot, 0, sizeof(mTexSlot) ); dMemset( &mTexType, 0, sizeof(mTexType) ); mCubeMap = NULL; mNumTex = mNumTexReg = mStageNum = 0; mGlow = false; mBlendOp = Material::None; mFeatureData.clear(); for (U32 i = 0; i < STATE_MAX; i++) mRenderStates[i] = NULL; } String RenderPassData::describeSelf() const { String desc; // Now write all the textures. String texName; for ( U32 i=0; i < Material::MAX_TEX_PER_PASS; i++ ) { if ( mTexType[i] == Material::TexTarget ) texName = ( mTexSlot[i].texTarget ) ? mTexSlot[i].texTarget->getName() : "null_texTarget"; else if ( mTexType[i] == Material::Cube && mCubeMap ) texName = mCubeMap->getPath(); else if ( mTexSlot[i].texObject ) texName = mTexSlot[i].texObject->getPath(); else continue; desc += String::ToString( "TexSlot %d: %d, %s\n", i, mTexType[i], texName.c_str() ); } // Write out the first render state which is the // basis for all the other states and shoud be // enough to define the pass uniquely. desc += mRenderStates[0]->getDesc().describeSelf(); return desc; } ProcessedMaterial::ProcessedMaterial() : mMaterial( NULL ), mCurrentParams( NULL ), mHasSetStageData( false ), mHasGlow( false ), mHasAccumulation( false ), mMaxStages( 0 ), mVertexFormat( NULL ), mUserObject( NULL ) { VECTOR_SET_ASSOCIATION( mPasses ); } ProcessedMaterial::~ProcessedMaterial() { for_each( mPasses.begin(), mPasses.end(), delete_pointer() ); } void ProcessedMaterial::_setBlendState(Material::BlendOp blendOp, GFXStateBlockDesc& desc ) { switch( blendOp ) { case Material::Add: { desc.blendSrc = GFXBlendOne; desc.blendDest = GFXBlendOne; break; } case Material::AddAlpha: { desc.blendSrc = GFXBlendSrcAlpha; desc.blendDest = GFXBlendOne; break; } case Material::Mul: { desc.blendSrc = GFXBlendDestColor; desc.blendDest = GFXBlendZero; break; } case Material::LerpAlpha: { desc.blendSrc = GFXBlendSrcAlpha; desc.blendDest = GFXBlendInvSrcAlpha; break; } default: { // default to LerpAlpha desc.blendSrc = GFXBlendSrcAlpha; desc.blendDest = GFXBlendInvSrcAlpha; break; } } } void ProcessedMaterial::setBuffers(GFXVertexBufferHandleBase* vertBuffer, GFXPrimitiveBufferHandle* primBuffer) { GFX->setVertexBuffer( *vertBuffer ); GFX->setPrimitiveBuffer( *primBuffer ); } bool ProcessedMaterial::stepInstance() { AssertFatal( false, "ProcessedMaterial::stepInstance() - This type of material doesn't support instancing!" ); return false; } String ProcessedMaterial::_getTexturePath(const String& filename) { // if '/', then path is specified, use it. if( filename.find('/') != String::NPos ) { return filename; } // otherwise, construct path return mMaterial->getPath() + filename; } GFXTexHandle ProcessedMaterial::_createTexture( const char* filename, GFXTextureProfile *profile) { return GFXTexHandle( _getTexturePath(filename), profile, avar("%s() - NA (line %d)", __FUNCTION__, __LINE__) ); } void ProcessedMaterial::addStateBlockDesc(const GFXStateBlockDesc& sb) { mUserDefined = sb; } void ProcessedMaterial::_initStateBlockTemplates(GFXStateBlockDesc& stateTranslucent, GFXStateBlockDesc& stateGlow, GFXStateBlockDesc& stateReflect) { // Translucency stateTranslucent.blendDefined = true; stateTranslucent.blendEnable = mMaterial->mTranslucentBlendOp != Material::None; _setBlendState(mMaterial->mTranslucentBlendOp, stateTranslucent); stateTranslucent.zDefined = true; stateTranslucent.zWriteEnable = mMaterial->mTranslucentZWrite; stateTranslucent.alphaDefined = true; stateTranslucent.alphaTestEnable = mMaterial->mAlphaTest; stateTranslucent.alphaTestRef = mMaterial->mAlphaRef; stateTranslucent.alphaTestFunc = GFXCmpGreaterEqual; stateTranslucent.samplersDefined = true; stateTranslucent.samplers[0].textureColorOp = GFXTOPModulate; stateTranslucent.samplers[0].alphaOp = GFXTOPModulate; stateTranslucent.samplers[0].alphaArg1 = GFXTATexture; stateTranslucent.samplers[0].alphaArg2 = GFXTADiffuse; // Glow stateGlow.zDefined = true; stateGlow.zWriteEnable = false; // Reflect stateReflect.cullDefined = true; stateReflect.cullMode = mMaterial->mDoubleSided ? GFXCullNone : GFXCullCW; } void ProcessedMaterial::_initRenderPassDataStateBlocks() { for (U32 pass = 0; pass < mPasses.size(); pass++) _initRenderStateStateBlocks( mPasses[pass] ); } void ProcessedMaterial::_initPassStateBlock( RenderPassData *rpd, GFXStateBlockDesc &result ) { if ( rpd->mBlendOp != Material::None ) { result.blendDefined = true; result.blendEnable = true; _setBlendState( rpd->mBlendOp, result ); } if (mMaterial && mMaterial->isDoubleSided()) { result.cullDefined = true; result.cullMode = GFXCullNone; } if(mMaterial && mMaterial->mAlphaTest) { result.alphaDefined = true; result.alphaTestEnable = mMaterial->mAlphaTest; result.alphaTestRef = mMaterial->mAlphaRef; result.alphaTestFunc = GFXCmpGreaterEqual; } result.samplersDefined = true; NamedTexTarget *texTarget; U32 maxAnisotropy = 1; if (mMaterial && mMaterial->mUseAnisotropic[ rpd->mStageNum ] ) maxAnisotropy = MATMGR->getDefaultAnisotropy(); for( U32 i=0; i < rpd->mNumTex; i++ ) { U32 currTexFlag = rpd->mTexType[i]; switch( currTexFlag ) { default: { result.samplers[i].textureColorOp = GFXTOPModulate; result.samplers[i].addressModeU = GFXAddressWrap; result.samplers[i].addressModeV = GFXAddressWrap; if ( maxAnisotropy > 1 ) { result.samplers[i].minFilter = GFXTextureFilterAnisotropic; result.samplers[i].magFilter = GFXTextureFilterAnisotropic; result.samplers[i].maxAnisotropy = maxAnisotropy; } else { result.samplers[i].minFilter = GFXTextureFilterLinear; result.samplers[i].magFilter = GFXTextureFilterLinear; } break; } case Material::Cube: case Material::SGCube: case Material::NormalizeCube: { result.samplers[i].addressModeU = GFXAddressClamp; result.samplers[i].addressModeV = GFXAddressClamp; result.samplers[i].addressModeW = GFXAddressClamp; break; } case Material::TexTarget: { texTarget = mPasses[0]->mTexSlot[i].texTarget; if ( texTarget ) texTarget->setupSamplerState( &result.samplers[i] ); break; } } } // The prepass will take care of writing to the // zbuffer, so we don't have to by default. if ( MATMGR->getPrePassEnabled() && !mFeatures.hasFeature(MFT_ForwardShading)) result.setZReadWrite( result.zEnable, false ); result.addDesc(mUserDefined); } /// Creates the default state blocks for a list of render states void ProcessedMaterial::_initRenderStateStateBlocks( RenderPassData *rpd ) { GFXStateBlockDesc stateTranslucent; GFXStateBlockDesc stateGlow; GFXStateBlockDesc stateReflect; GFXStateBlockDesc statePass; _initStateBlockTemplates( stateTranslucent, stateGlow, stateReflect ); _initPassStateBlock( rpd, statePass ); // Ok, we've got our templates set up, let's combine them together based on state and // create our state blocks. for (U32 i = 0; i < RenderPassData::STATE_MAX; i++) { GFXStateBlockDesc stateFinal; if (i & RenderPassData::STATE_REFLECT) stateFinal.addDesc(stateReflect); if (i & RenderPassData::STATE_TRANSLUCENT) stateFinal.addDesc(stateTranslucent); if (i & RenderPassData::STATE_GLOW) stateFinal.addDesc(stateGlow); stateFinal.addDesc(statePass); if (i & RenderPassData::STATE_WIREFRAME) stateFinal.fillMode = GFXFillWireframe; GFXStateBlockRef sb = GFX->createStateBlock(stateFinal); rpd->mRenderStates[i] = sb; } } U32 ProcessedMaterial::_getRenderStateIndex( const SceneRenderState *sceneState, const SceneData &sgData ) { // Based on what the state of the world is, get our render state block U32 currState = 0; // NOTE: We should only use per-material or per-pass hints to // change the render state. This is importaint because we // only change the state blocks between material passes. // // For example sgData.visibility would be bad to use // in here without changing how RenderMeshMgr works. if ( sgData.binType == SceneData::GlowBin ) currState |= RenderPassData::STATE_GLOW; if ( sceneState && sceneState->isReflectPass() ) currState |= RenderPassData::STATE_REFLECT; if ( sgData.binType != SceneData::PrePassBin && mMaterial->isTranslucent() ) currState |= RenderPassData::STATE_TRANSLUCENT; if ( sgData.wireframe ) currState |= RenderPassData::STATE_WIREFRAME; return currState; } void ProcessedMaterial::_setRenderState( const SceneRenderState *state, const SceneData& sgData, U32 pass ) { // Make sure we have the pass if ( pass >= mPasses.size() ) return; U32 currState = _getRenderStateIndex( state, sgData ); GFX->setStateBlock(mPasses[pass]->mRenderStates[currState]); } void ProcessedMaterial::_setStageData() { // Only do this once if ( mHasSetStageData ) return; mHasSetStageData = true; U32 i; // Load up all the textures for every possible stage for( i=0; i<Material::MAX_STAGES; i++ ) { // DiffuseMap if( mMaterial->mDiffuseMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_DiffuseMap, _createTexture( mMaterial->mDiffuseMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if (!mStages[i].getTex( MFT_DiffuseMap )) { mMaterial->logError("Failed to load diffuse map %s for stage %i", _getTexturePath(mMaterial->mDiffuseMapFilename[i]).c_str(), i); // Load a debug texture to make it clear to the user // that the texture for this stage was missing. mStages[i].setTex( MFT_DiffuseMap, _createTexture( GFXTextureManager::getMissingTexturePath().c_str(), &GFXDefaultStaticDiffuseProfile ) ); } } // OverlayMap if( mMaterial->mOverlayMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_OverlayMap, _createTexture( mMaterial->mOverlayMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_OverlayMap )) mMaterial->logError("Failed to load overlay map %s for stage %i", _getTexturePath(mMaterial->mOverlayMapFilename[i]).c_str(), i); } // LightMap if( mMaterial->mLightMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_LightMap, _createTexture( mMaterial->mLightMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_LightMap )) mMaterial->logError("Failed to load light map %s for stage %i", _getTexturePath(mMaterial->mLightMapFilename[i]).c_str(), i); } // ToneMap if( mMaterial->mToneMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_ToneMap, _createTexture( mMaterial->mToneMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_ToneMap )) mMaterial->logError("Failed to load tone map %s for stage %i", _getTexturePath(mMaterial->mToneMapFilename[i]).c_str(), i); } // DetailMap if( mMaterial->mDetailMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_DetailMap, _createTexture( mMaterial->mDetailMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_DetailMap )) mMaterial->logError("Failed to load detail map %s for stage %i", _getTexturePath(mMaterial->mDetailMapFilename[i]).c_str(), i); } // NormalMap if( mMaterial->mNormalMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_NormalMap, _createTexture( mMaterial->mNormalMapFilename[i], &GFXDefaultStaticNormalMapProfile ) ); if(!mStages[i].getTex( MFT_NormalMap )) mMaterial->logError("Failed to load normal map %s for stage %i", _getTexturePath(mMaterial->mNormalMapFilename[i]).c_str(), i); } // Detail Normal Map if( mMaterial->mDetailNormalMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_DetailNormalMap, _createTexture( mMaterial->mDetailNormalMapFilename[i], &GFXDefaultStaticNormalMapProfile ) ); if(!mStages[i].getTex( MFT_DetailNormalMap )) mMaterial->logError("Failed to load normal map %s for stage %i", _getTexturePath(mMaterial->mDetailNormalMapFilename[i]).c_str(), i); } // SpecularMap if( mMaterial->mSpecularMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_SpecularMap, _createTexture( mMaterial->mSpecularMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_SpecularMap )) mMaterial->logError("Failed to load specular map %s for stage %i", _getTexturePath(mMaterial->mSpecularMapFilename[i]).c_str(), i); } } mMaterial->mCubemapData = dynamic_cast<CubemapData*>(Sim::findObject( mMaterial->mCubemapName )); if( !mMaterial->mCubemapData ) mMaterial->mCubemapData = NULL; // If we have a cubemap put it on stage 0 (cubemaps only supported on stage 0) if( mMaterial->mCubemapData ) { mMaterial->mCubemapData->createMap(); mStages[0].setCubemap( mMaterial->mCubemapData->mCubemap ); if ( !mStages[0].getCubemap() ) mMaterial->logError("Failed to load cubemap"); } } Adds a check so if we're trying to hit a named target, it doesn't spam the console with errors about not finding the diffuse texture. //----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "materials/processedMaterial.h" #include "materials/sceneData.h" #include "materials/materialParameters.h" #include "materials/matTextureTarget.h" #include "materials/materialFeatureTypes.h" #include "materials/materialManager.h" #include "scene/sceneRenderState.h" #include "gfx/gfxPrimitiveBuffer.h" #include "gfx/gfxTextureManager.h" #include "gfx/sim/cubemapData.h" RenderPassData::RenderPassData() { reset(); } void RenderPassData::reset() { for( U32 i = 0; i < Material::MAX_TEX_PER_PASS; ++ i ) { destructInPlace( &mTexSlot[ i ] ); mSamplerNames[ i ].clear(); } dMemset( &mTexSlot, 0, sizeof(mTexSlot) ); dMemset( &mTexType, 0, sizeof(mTexType) ); mCubeMap = NULL; mNumTex = mNumTexReg = mStageNum = 0; mGlow = false; mBlendOp = Material::None; mFeatureData.clear(); for (U32 i = 0; i < STATE_MAX; i++) mRenderStates[i] = NULL; } String RenderPassData::describeSelf() const { String desc; // Now write all the textures. String texName; for ( U32 i=0; i < Material::MAX_TEX_PER_PASS; i++ ) { if ( mTexType[i] == Material::TexTarget ) texName = ( mTexSlot[i].texTarget ) ? mTexSlot[i].texTarget->getName() : "null_texTarget"; else if ( mTexType[i] == Material::Cube && mCubeMap ) texName = mCubeMap->getPath(); else if ( mTexSlot[i].texObject ) texName = mTexSlot[i].texObject->getPath(); else continue; desc += String::ToString( "TexSlot %d: %d, %s\n", i, mTexType[i], texName.c_str() ); } // Write out the first render state which is the // basis for all the other states and shoud be // enough to define the pass uniquely. desc += mRenderStates[0]->getDesc().describeSelf(); return desc; } ProcessedMaterial::ProcessedMaterial() : mMaterial( NULL ), mCurrentParams( NULL ), mHasSetStageData( false ), mHasGlow( false ), mHasAccumulation( false ), mMaxStages( 0 ), mVertexFormat( NULL ), mUserObject( NULL ) { VECTOR_SET_ASSOCIATION( mPasses ); } ProcessedMaterial::~ProcessedMaterial() { for_each( mPasses.begin(), mPasses.end(), delete_pointer() ); } void ProcessedMaterial::_setBlendState(Material::BlendOp blendOp, GFXStateBlockDesc& desc ) { switch( blendOp ) { case Material::Add: { desc.blendSrc = GFXBlendOne; desc.blendDest = GFXBlendOne; break; } case Material::AddAlpha: { desc.blendSrc = GFXBlendSrcAlpha; desc.blendDest = GFXBlendOne; break; } case Material::Mul: { desc.blendSrc = GFXBlendDestColor; desc.blendDest = GFXBlendZero; break; } case Material::LerpAlpha: { desc.blendSrc = GFXBlendSrcAlpha; desc.blendDest = GFXBlendInvSrcAlpha; break; } default: { // default to LerpAlpha desc.blendSrc = GFXBlendSrcAlpha; desc.blendDest = GFXBlendInvSrcAlpha; break; } } } void ProcessedMaterial::setBuffers(GFXVertexBufferHandleBase* vertBuffer, GFXPrimitiveBufferHandle* primBuffer) { GFX->setVertexBuffer( *vertBuffer ); GFX->setPrimitiveBuffer( *primBuffer ); } bool ProcessedMaterial::stepInstance() { AssertFatal( false, "ProcessedMaterial::stepInstance() - This type of material doesn't support instancing!" ); return false; } String ProcessedMaterial::_getTexturePath(const String& filename) { // if '/', then path is specified, use it. if( filename.find('/') != String::NPos ) { return filename; } // otherwise, construct path return mMaterial->getPath() + filename; } GFXTexHandle ProcessedMaterial::_createTexture( const char* filename, GFXTextureProfile *profile) { return GFXTexHandle( _getTexturePath(filename), profile, avar("%s() - NA (line %d)", __FUNCTION__, __LINE__) ); } void ProcessedMaterial::addStateBlockDesc(const GFXStateBlockDesc& sb) { mUserDefined = sb; } void ProcessedMaterial::_initStateBlockTemplates(GFXStateBlockDesc& stateTranslucent, GFXStateBlockDesc& stateGlow, GFXStateBlockDesc& stateReflect) { // Translucency stateTranslucent.blendDefined = true; stateTranslucent.blendEnable = mMaterial->mTranslucentBlendOp != Material::None; _setBlendState(mMaterial->mTranslucentBlendOp, stateTranslucent); stateTranslucent.zDefined = true; stateTranslucent.zWriteEnable = mMaterial->mTranslucentZWrite; stateTranslucent.alphaDefined = true; stateTranslucent.alphaTestEnable = mMaterial->mAlphaTest; stateTranslucent.alphaTestRef = mMaterial->mAlphaRef; stateTranslucent.alphaTestFunc = GFXCmpGreaterEqual; stateTranslucent.samplersDefined = true; stateTranslucent.samplers[0].textureColorOp = GFXTOPModulate; stateTranslucent.samplers[0].alphaOp = GFXTOPModulate; stateTranslucent.samplers[0].alphaArg1 = GFXTATexture; stateTranslucent.samplers[0].alphaArg2 = GFXTADiffuse; // Glow stateGlow.zDefined = true; stateGlow.zWriteEnable = false; // Reflect stateReflect.cullDefined = true; stateReflect.cullMode = mMaterial->mDoubleSided ? GFXCullNone : GFXCullCW; } void ProcessedMaterial::_initRenderPassDataStateBlocks() { for (U32 pass = 0; pass < mPasses.size(); pass++) _initRenderStateStateBlocks( mPasses[pass] ); } void ProcessedMaterial::_initPassStateBlock( RenderPassData *rpd, GFXStateBlockDesc &result ) { if ( rpd->mBlendOp != Material::None ) { result.blendDefined = true; result.blendEnable = true; _setBlendState( rpd->mBlendOp, result ); } if (mMaterial && mMaterial->isDoubleSided()) { result.cullDefined = true; result.cullMode = GFXCullNone; } if(mMaterial && mMaterial->mAlphaTest) { result.alphaDefined = true; result.alphaTestEnable = mMaterial->mAlphaTest; result.alphaTestRef = mMaterial->mAlphaRef; result.alphaTestFunc = GFXCmpGreaterEqual; } result.samplersDefined = true; NamedTexTarget *texTarget; U32 maxAnisotropy = 1; if (mMaterial && mMaterial->mUseAnisotropic[ rpd->mStageNum ] ) maxAnisotropy = MATMGR->getDefaultAnisotropy(); for( U32 i=0; i < rpd->mNumTex; i++ ) { U32 currTexFlag = rpd->mTexType[i]; switch( currTexFlag ) { default: { result.samplers[i].textureColorOp = GFXTOPModulate; result.samplers[i].addressModeU = GFXAddressWrap; result.samplers[i].addressModeV = GFXAddressWrap; if ( maxAnisotropy > 1 ) { result.samplers[i].minFilter = GFXTextureFilterAnisotropic; result.samplers[i].magFilter = GFXTextureFilterAnisotropic; result.samplers[i].maxAnisotropy = maxAnisotropy; } else { result.samplers[i].minFilter = GFXTextureFilterLinear; result.samplers[i].magFilter = GFXTextureFilterLinear; } break; } case Material::Cube: case Material::SGCube: case Material::NormalizeCube: { result.samplers[i].addressModeU = GFXAddressClamp; result.samplers[i].addressModeV = GFXAddressClamp; result.samplers[i].addressModeW = GFXAddressClamp; break; } case Material::TexTarget: { texTarget = mPasses[0]->mTexSlot[i].texTarget; if ( texTarget ) texTarget->setupSamplerState( &result.samplers[i] ); break; } } } // The prepass will take care of writing to the // zbuffer, so we don't have to by default. if ( MATMGR->getPrePassEnabled() && !mFeatures.hasFeature(MFT_ForwardShading)) result.setZReadWrite( result.zEnable, false ); result.addDesc(mUserDefined); } /// Creates the default state blocks for a list of render states void ProcessedMaterial::_initRenderStateStateBlocks( RenderPassData *rpd ) { GFXStateBlockDesc stateTranslucent; GFXStateBlockDesc stateGlow; GFXStateBlockDesc stateReflect; GFXStateBlockDesc statePass; _initStateBlockTemplates( stateTranslucent, stateGlow, stateReflect ); _initPassStateBlock( rpd, statePass ); // Ok, we've got our templates set up, let's combine them together based on state and // create our state blocks. for (U32 i = 0; i < RenderPassData::STATE_MAX; i++) { GFXStateBlockDesc stateFinal; if (i & RenderPassData::STATE_REFLECT) stateFinal.addDesc(stateReflect); if (i & RenderPassData::STATE_TRANSLUCENT) stateFinal.addDesc(stateTranslucent); if (i & RenderPassData::STATE_GLOW) stateFinal.addDesc(stateGlow); stateFinal.addDesc(statePass); if (i & RenderPassData::STATE_WIREFRAME) stateFinal.fillMode = GFXFillWireframe; GFXStateBlockRef sb = GFX->createStateBlock(stateFinal); rpd->mRenderStates[i] = sb; } } U32 ProcessedMaterial::_getRenderStateIndex( const SceneRenderState *sceneState, const SceneData &sgData ) { // Based on what the state of the world is, get our render state block U32 currState = 0; // NOTE: We should only use per-material or per-pass hints to // change the render state. This is importaint because we // only change the state blocks between material passes. // // For example sgData.visibility would be bad to use // in here without changing how RenderMeshMgr works. if ( sgData.binType == SceneData::GlowBin ) currState |= RenderPassData::STATE_GLOW; if ( sceneState && sceneState->isReflectPass() ) currState |= RenderPassData::STATE_REFLECT; if ( sgData.binType != SceneData::PrePassBin && mMaterial->isTranslucent() ) currState |= RenderPassData::STATE_TRANSLUCENT; if ( sgData.wireframe ) currState |= RenderPassData::STATE_WIREFRAME; return currState; } void ProcessedMaterial::_setRenderState( const SceneRenderState *state, const SceneData& sgData, U32 pass ) { // Make sure we have the pass if ( pass >= mPasses.size() ) return; U32 currState = _getRenderStateIndex( state, sgData ); GFX->setStateBlock(mPasses[pass]->mRenderStates[currState]); } void ProcessedMaterial::_setStageData() { // Only do this once if ( mHasSetStageData ) return; mHasSetStageData = true; U32 i; // Load up all the textures for every possible stage for( i=0; i<Material::MAX_STAGES; i++ ) { // DiffuseMap if( mMaterial->mDiffuseMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_DiffuseMap, _createTexture( mMaterial->mDiffuseMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if (!mStages[i].getTex( MFT_DiffuseMap )) { //If we start with a #, we're probably actually attempting to hit a named target and it may not get a hit on the first pass. So we'll //pass on the error rather than spamming the console if (!mMaterial->mDiffuseMapFilename[i].startsWith("#")) mMaterial->logError("Failed to load diffuse map %s for stage %i", _getTexturePath(mMaterial->mDiffuseMapFilename[i]).c_str(), i); // Load a debug texture to make it clear to the user // that the texture for this stage was missing. mStages[i].setTex( MFT_DiffuseMap, _createTexture( GFXTextureManager::getMissingTexturePath().c_str(), &GFXDefaultStaticDiffuseProfile ) ); } } // OverlayMap if( mMaterial->mOverlayMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_OverlayMap, _createTexture( mMaterial->mOverlayMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_OverlayMap )) mMaterial->logError("Failed to load overlay map %s for stage %i", _getTexturePath(mMaterial->mOverlayMapFilename[i]).c_str(), i); } // LightMap if( mMaterial->mLightMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_LightMap, _createTexture( mMaterial->mLightMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_LightMap )) mMaterial->logError("Failed to load light map %s for stage %i", _getTexturePath(mMaterial->mLightMapFilename[i]).c_str(), i); } // ToneMap if( mMaterial->mToneMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_ToneMap, _createTexture( mMaterial->mToneMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_ToneMap )) mMaterial->logError("Failed to load tone map %s for stage %i", _getTexturePath(mMaterial->mToneMapFilename[i]).c_str(), i); } // DetailMap if( mMaterial->mDetailMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_DetailMap, _createTexture( mMaterial->mDetailMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_DetailMap )) mMaterial->logError("Failed to load detail map %s for stage %i", _getTexturePath(mMaterial->mDetailMapFilename[i]).c_str(), i); } // NormalMap if( mMaterial->mNormalMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_NormalMap, _createTexture( mMaterial->mNormalMapFilename[i], &GFXDefaultStaticNormalMapProfile ) ); if(!mStages[i].getTex( MFT_NormalMap )) mMaterial->logError("Failed to load normal map %s for stage %i", _getTexturePath(mMaterial->mNormalMapFilename[i]).c_str(), i); } // Detail Normal Map if( mMaterial->mDetailNormalMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_DetailNormalMap, _createTexture( mMaterial->mDetailNormalMapFilename[i], &GFXDefaultStaticNormalMapProfile ) ); if(!mStages[i].getTex( MFT_DetailNormalMap )) mMaterial->logError("Failed to load normal map %s for stage %i", _getTexturePath(mMaterial->mDetailNormalMapFilename[i]).c_str(), i); } // SpecularMap if( mMaterial->mSpecularMapFilename[i].isNotEmpty() ) { mStages[i].setTex( MFT_SpecularMap, _createTexture( mMaterial->mSpecularMapFilename[i], &GFXDefaultStaticDiffuseProfile ) ); if(!mStages[i].getTex( MFT_SpecularMap )) mMaterial->logError("Failed to load specular map %s for stage %i", _getTexturePath(mMaterial->mSpecularMapFilename[i]).c_str(), i); } } mMaterial->mCubemapData = dynamic_cast<CubemapData*>(Sim::findObject( mMaterial->mCubemapName )); if( !mMaterial->mCubemapData ) mMaterial->mCubemapData = NULL; // If we have a cubemap put it on stage 0 (cubemaps only supported on stage 0) if( mMaterial->mCubemapData ) { mMaterial->mCubemapData->createMap(); mStages[0].setCubemap( mMaterial->mCubemapData->mCubemap ); if ( !mStages[0].getCubemap() ) mMaterial->logError("Failed to load cubemap"); } }
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistration14.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates how to do registration with a 2D Rigid Transform // and with the Normalized Mutual Information metric. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageRegistrationMethod.h" #include "itkCenteredRigid2DTransform.h" #include "itkCenteredTransformInitializer.h" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkOnePlusOneEvolutionaryOptimizer.h" #include "itkNormalVariateGenerator.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" // The following section of code implements a Command observer // used to monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } double currentValue = optimizer->GetValue(); // Only print out when the Metric value changes if( fabs( m_LastMetricValue - currentValue ) > 1e-7 ) { std::cout << optimizer->GetCurrentIteration() << " "; std::cout << currentValue << " "; std::cout << optimizer->GetCurrentPosition() << std::endl; m_LastMetricValue = currentValue; } } private: double m_LastMetricValue; }; int main( int argc, char *argv[] ) { if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [differenceImage]" << std::endl; return 1; } const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::CenteredRigid2DTransform< double > TransformType; typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; typedef itk::NormalizedMutualInformationHistogramImageToImageMetric< FixedImageType, MovingImageType > MetricType; TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); MetricType::Pointer metric = MetricType::New(); registration->SetMetric( metric ); unsigned int numberOfBins = 32; MetricType::HistogramType::SizeType histogramSize; histogramSize[0] = numberOfBins; histogramSize[1] = numberOfBins; metric->SetHistogramSize( histogramSize ); const unsigned int numberOfParameters = transform->GetNumberOfParameters(); typedef MetricType::ScalesType ScalesType; ScalesType scales( numberOfParameters ); scales.Fill( 1.0 ); metric->SetDerivativeStepLengthScales(scales); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); fixedImageReader->Update(); registration->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() ); typedef itk::CenteredTransformInitializer< TransformType, FixedImageType, MovingImageType > TransformInitializerType; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); initializer->SetTransform( transform ); initializer->SetFixedImage( fixedImageReader->GetOutput() ); initializer->SetMovingImage( movingImageReader->GetOutput() ); initializer->GeometryOn(); initializer->InitializeTransform(); transform->SetAngle( 0.0 ); registration->SetInitialTransformParameters( transform->GetParameters() ); std::cout << "Initial transform parameters = "; std::cout << transform->GetParameters() << std::endl; typedef OptimizerType::ScalesType OptimizerScalesType; OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() ); const double translationScale = 1.0 / 100.0; optimizerScales[0] = 1.0; optimizerScales[1] = translationScale; optimizerScales[2] = translationScale; optimizerScales[3] = translationScale; optimizerScales[4] = translationScale; optimizer->SetScales( optimizerScales ); typedef itk::Statistics::NormalVariateGenerator GeneratorType; GeneratorType::Pointer generator = GeneratorType::New(); generator->Initialize(12345); optimizer->MaximizeOn(); optimizer->SetNormalVariateGenerator( generator ); const double initialRadius = 0.05; optimizer->Initialize( initialRadius ); optimizer->SetEpsilon( 0.001 ); optimizer->SetMaximumIteration( 500 ); // Create the Command observer and register it with the optimizer. // CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } typedef RegistrationType::ParametersType ParametersType; ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalAngle = finalParameters[0]; const double finalRotationCenterX = finalParameters[1]; const double finalRotationCenterY = finalParameters[2]; const double finalTranslationX = finalParameters[3]; const double finalTranslationY = finalParameters[4]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); // Print out results // const double finalAngleInDegrees = finalAngle * 45.0 / atan(1.0); std::cout << "Result = " << std::endl; std::cout << " Angle (radians) " << finalAngle << std::endl; std::cout << " Angle (degrees) " << finalAngleInDegrees << std::endl; std::cout << " Center X = " << finalRotationCenterX << std::endl; std::cout << " Center Y = " << finalRotationCenterY << std::endl; std::cout << " Translation X = " << finalTranslationX << std::endl; std::cout << " Translation Y = " << finalTranslationY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef itk::Image< PixelType, Dimension > OutputImageType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( resample->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet return 0; } FIX: UMR, m_LastMetricValue not initialized /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistration14.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates how to do registration with a 2D Rigid Transform // and with the Normalized Mutual Information metric. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageRegistrationMethod.h" #include "itkCenteredRigid2DTransform.h" #include "itkCenteredTransformInitializer.h" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkOnePlusOneEvolutionaryOptimizer.h" #include "itkNormalVariateGenerator.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" // The following section of code implements a Command observer // used to monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {m_LastMetricValue = 0;} public: typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } double currentValue = optimizer->GetValue(); // Only print out when the Metric value changes if( fabs( m_LastMetricValue - currentValue ) > 1e-7 ) { std::cout << optimizer->GetCurrentIteration() << " "; std::cout << currentValue << " "; std::cout << optimizer->GetCurrentPosition() << std::endl; m_LastMetricValue = currentValue; } } private: double m_LastMetricValue; }; int main( int argc, char *argv[] ) { if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [differenceImage]" << std::endl; return 1; } const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::CenteredRigid2DTransform< double > TransformType; typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; typedef itk::NormalizedMutualInformationHistogramImageToImageMetric< FixedImageType, MovingImageType > MetricType; TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); MetricType::Pointer metric = MetricType::New(); registration->SetMetric( metric ); unsigned int numberOfBins = 32; MetricType::HistogramType::SizeType histogramSize; histogramSize[0] = numberOfBins; histogramSize[1] = numberOfBins; metric->SetHistogramSize( histogramSize ); const unsigned int numberOfParameters = transform->GetNumberOfParameters(); typedef MetricType::ScalesType ScalesType; ScalesType scales( numberOfParameters ); scales.Fill( 1.0 ); metric->SetDerivativeStepLengthScales(scales); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); fixedImageReader->Update(); registration->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() ); typedef itk::CenteredTransformInitializer< TransformType, FixedImageType, MovingImageType > TransformInitializerType; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); initializer->SetTransform( transform ); initializer->SetFixedImage( fixedImageReader->GetOutput() ); initializer->SetMovingImage( movingImageReader->GetOutput() ); initializer->GeometryOn(); initializer->InitializeTransform(); transform->SetAngle( 0.0 ); registration->SetInitialTransformParameters( transform->GetParameters() ); std::cout << "Initial transform parameters = "; std::cout << transform->GetParameters() << std::endl; typedef OptimizerType::ScalesType OptimizerScalesType; OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() ); const double translationScale = 1.0 / 100.0; optimizerScales[0] = 1.0; optimizerScales[1] = translationScale; optimizerScales[2] = translationScale; optimizerScales[3] = translationScale; optimizerScales[4] = translationScale; optimizer->SetScales( optimizerScales ); typedef itk::Statistics::NormalVariateGenerator GeneratorType; GeneratorType::Pointer generator = GeneratorType::New(); generator->Initialize(12345); optimizer->MaximizeOn(); optimizer->SetNormalVariateGenerator( generator ); const double initialRadius = 0.05; optimizer->Initialize( initialRadius ); optimizer->SetEpsilon( 0.001 ); optimizer->SetMaximumIteration( 500 ); // Create the Command observer and register it with the optimizer. // CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } typedef RegistrationType::ParametersType ParametersType; ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalAngle = finalParameters[0]; const double finalRotationCenterX = finalParameters[1]; const double finalRotationCenterY = finalParameters[2]; const double finalTranslationX = finalParameters[3]; const double finalTranslationY = finalParameters[4]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); // Print out results // const double finalAngleInDegrees = finalAngle * 45.0 / atan(1.0); std::cout << "Result = " << std::endl; std::cout << " Angle (radians) " << finalAngle << std::endl; std::cout << " Angle (degrees) " << finalAngleInDegrees << std::endl; std::cout << " Center X = " << finalRotationCenterX << std::endl; std::cout << " Center Y = " << finalRotationCenterY << std::endl; std::cout << " Translation X = " << finalTranslationX << std::endl; std::cout << " Translation Y = " << finalTranslationY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef itk::Image< PixelType, Dimension > OutputImageType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( resample->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet return 0; }
// $Id$ /* * Plotting macro for comparing offline- and HLT- ESD trees from * HLT-OFFLINE-GLOBAL-comparison.root produced using $ALICE_ROOT/HLT/QA/tasks/AliAnalysisTaskHLT.* * * Usage: aliroot drawGlobalESDHistograms.C'("HLT-OFFLINE-GLOBAL-comparison.root")' * * It saves the canvas with the output histograms in a png file. * * @ingroup alihlt_qa * @author Camilla.Stokkevag@student.uib.no, Kalliopi.Kanaki@ift.uib.no */ void drawGlobalESDHistograms(const char* filename="HLT-OFFLINE-GLOBAL-comparison.root"){ gROOT->SetStyle("Plain"); gStyle->SetPalette(1); gStyle->SetOptStat(10); gStyle->SetTitleX(gStyle->GetPadLeftMargin()); TFile *f1 = TFile::Open(filename); if(!f1 || f1->IsZombie()) { printf("file %s does not exist or there is an error opening it\n", filename); return; } TList *l1 = (TList*)f1->Get("global_histograms"); if(!l1){ printf("No list %s contained in your input file\n", l1->GetName()); return; } //=================================================================// //--------------- READ HISTOGRAMS ---------------------------------// //=================================================================// TH1F *h1 = l1->FindObject("fNcluster_hlt"); TH1F *h2 = l1->FindObject("fNcluster_off"); h1->SetTitle("cluster distribution"); h1->GetXaxis()->SetTitle("TPC clusters per track"); h2->SetLineColor(2); if(h1->GetMaximum() >= h2->GetMaximum()) h2->SetMaximum(1.1*h1->GetMaximum()); else h1->SetMaximum(1.1*h2->GetMaximum()); TH1F *h3 = l1->FindObject("fDCA_hlt"); TH1F *h4 = l1->FindObject("fDCA_off"); TH1F *hSG = l1->FindObject("fDCA_hltSG"); h3->SetTitle("DCA between track and vertex on XY plane"); h3->GetXaxis()->SetTitle("DCAr (cm)"); h4->SetLineColor(2); hSG->SetLineColor(kBlue); if(h3->GetMaximum() >= h4->GetMaximum()) h4->SetMaximum(1.1*h3->GetMaximum()); else h3->SetMaximum(1.1*h4->GetMaximum()); TH1F *h5 = l1->FindObject("fMult_hlt"); TH1F *h6 = l1->FindObject("fMult_off"); h5->SetTitle("track multiplicity"); h6->SetLineColor(2); if(h5->GetMaximum() > h6->GetMaximum()) h6->SetMaximum(1.1*h5->GetMaximum()); else h5->SetMaximum(1.1*h6->GetMaximum()); TH1F *h7 = l1->FindObject("fCharge_hlt"); TH1F *h8 = l1->FindObject("fCharge_off"); h7->GetXaxis()->SetTitle("polarity"); h7->SetTitle("charge distribution"); h8->SetLineColor(2); if(h7->GetMaximum() > h8->GetMaximum()) h8->SetMaximum(1.1*h7->GetMaximum()); else h7->SetMaximum(1.1*h8->GetMaximum()); TH1F *h9 = l1->FindObject("fMomentum_hlt"); TH1F *h10 = l1->FindObject("fMomentum_off"); h9->GetXaxis()->SetTitle("p_{t} (GeV/c)"); h9->SetTitle("transverse momentum"); h10->SetLineColor(2); if(h9->GetMaximum() > h10->GetMaximum()) h10->SetMaximum(1.1*h9->GetMaximum()); else h9->SetMaximum(1.1*h10->GetMaximum()); TH1F *h11 = l1->FindObject("fEta_hlt"); TH1F *h12 = l1->FindObject("fEta_off"); h11->SetTitle("pseudorapidity"); h11->GetXaxis()->SetTitle("#eta"); h12->SetLineColor(2); if(h11->GetMaximum() > h12->GetMaximum()) h12->SetMaximum(1.1*h11->GetMaximum()); else h11->SetMaximum(1.1*h12->GetMaximum()); TH1F *h13 = l1->FindObject("fXvertex_hlt"); TH1F *h14 = l1->FindObject("fXvertex_off"); h13->GetXaxis()->SetTitle("x (cm)"); h13->SetTitle("x of primary vertex"); h14->SetLineColor(2); if(h13->GetMaximum() > h14->GetMaximum()) h14->SetMaximum(1.1*h13->GetMaximum()); else h13->SetMaximum(1.1*h14->GetMaximum()); TH1F *h15 = l1->FindObject("fYvertex_hlt"); TH1F *h16 = l1->FindObject("fYvertex_off"); h15->GetXaxis()->SetTitle("y (cm)"); h15->SetTitle("y of primary vertex"); h16->SetLineColor(2); if(h15->GetMaximum() > h16->GetMaximum()) h16->SetMaximum(1.1*h15->GetMaximum()); else h15->SetMaximum(1.1*h16->GetMaximum()); TH1F *h17 = l1->FindObject("fZvertex_hlt"); TH1F *h18 = l1->FindObject("fZvertex_off"); h17->GetXaxis()->SetTitle("z (cm)"); h17->SetTitle("z of primary vertex"); h18->SetLineColor(2); if(h17->GetMaximum() > h18->GetMaximum()) h18->SetMaximum(1.1*h17->GetMaximum()); else h17->SetMaximum(1.1*h18->GetMaximum()); // TH2F *h15 = l1->FindObject("fXYvertex_off"); // h15->GetXaxis()->SetTitle("X (cm)"); // h15->GetYaxis()->SetTitle("Y (cm)"); // h15->SetTitle("XY primary vertex Offline"); // // TH2F *h16 = l1->FindObject("fXYvertex_hlt"); // h16->GetXaxis()->SetTitle("X (cm)"); // h16->GetYaxis()->SetTitle("Y (cm)"); // h16->SetTitle("XY of primary vertex HLT"); TLegend *leg1 = new TLegend(0.6,0.6,0.8,0.8); leg1->SetFillColor(10); leg1->SetLineColor(10); leg1->AddEntry(h1,"HLT", "l"); leg1->AddEntry(h2,"OFF", "l"); //=================================================================// //--------------------- DRAW HISTOGRAMS ---------------------------// //=================================================================// TCanvas *c1 = new TCanvas("c1","HLT vs offline",1300,800); c1->Divide(3,3); c1->cd(1); h1->Draw(); h2->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st1 = (TPaveStats*)h1->FindObject("stats"); st1->SetLineColor(0); gPad->Update(); TPaveStats *st2 = (TPaveStats*)h2->FindObject("stats"); st2->SetY1NDC(st1->GetY1NDC()-0.05); st2->SetY2NDC(st1->GetY2NDC()-0.05); st2->SetLineColor(0); st2->SetTextColor(h2->GetLineColor()); st2->SetFillStyle(0); st2->Draw(); //====================== c1->cd(2)->SetLogy(); h3->Draw(); h4->Draw("sames"); hSG->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st3 = (TPaveStats*)h3->FindObject("stats"); st3->SetLineColor(0); gPad->Update(); TPaveStats *st4 = (TPaveStats*)h4->FindObject("stats"); st4->SetY1NDC(st3->GetY1NDC()-0.05); st4->SetY2NDC(st3->GetY2NDC()-0.05); st4->SetLineColor(0); st4->SetTextColor(h4->GetLineColor()); st4->SetFillStyle(0); st4->Draw(); gPad->Update(); TPaveStats *stSG = (TPaveStats*)hSG->FindObject("stats"); stSG->SetY1NDC(st4->GetY1NDC()-0.05); stSG->SetY2NDC(st4->GetY2NDC()-0.05); stSG->SetLineColor(0); stSG->SetTextColor(hSG->GetLineColor()); stSG->SetFillStyle(0); stSG->Draw(); //====================== c1->cd(3); h5->Draw(); h6->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st5 = (TPaveStats*)h5->FindObject("stats"); st5->SetLineColor(0); gPad->Update(); TPaveStats *st6 = (TPaveStats*)h6->FindObject("stats"); st6->SetY1NDC(st5->GetY1NDC()-0.05); st6->SetY2NDC(st5->GetY2NDC()-0.05); st6->SetLineColor(0); st6->SetTextColor(h6->GetLineColor()); st6->SetFillStyle(0); st6->Draw(); //====================== c1->cd(4); h7->Draw(); h8->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st7 = (TPaveStats*)h7->FindObject("stats"); st7->SetLineColor(0); gPad->Update(); TPaveStats *st8 = (TPaveStats*)h8->FindObject("stats"); st8->SetY1NDC(st7->GetY1NDC()-0.05); st8->SetY2NDC(st7->GetY2NDC()-0.05); st8->SetLineColor(0); st8->SetTextColor(h8->GetLineColor()); st8->SetFillStyle(0); st8->Draw(); //====================== c1->cd(5)->SetLogy(); h9->Draw(); h10->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st9 = (TPaveStats*)h9->FindObject("stats"); st9->SetLineColor(0); gPad->Update(); TPaveStats *st10 = (TPaveStats*)h10->FindObject("stats"); st10->SetY1NDC(st9->GetY1NDC()-0.05); st10->SetY2NDC(st9->GetY2NDC()-0.05); st10->SetLineColor(0); st10->SetTextColor(h10->GetLineColor()); st10->SetFillStyle(0); st10->Draw(); //====================== c1->cd(6); h11->Draw(); h12->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st11 = (TPaveStats*)h11->FindObject("stats"); st11->SetLineColor(0); gPad->Update(); TPaveStats *st12 = (TPaveStats*)h12->FindObject("stats"); st12->SetY1NDC(st11->GetY1NDC()-0.05); st12->SetY2NDC(st11->GetY2NDC()-0.05); st12->SetLineColor(0); st12->SetTextColor(h12->GetLineColor()); st12->SetFillStyle(0); st12->Draw(); //====================== c1->cd(7); h13->Draw(); h14->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st13 = (TPaveStats*)h13->FindObject("stats"); st13->SetLineColor(0); gPad->Update(); TPaveStats *st14 = (TPaveStats*)h14->FindObject("stats"); st14->SetY1NDC(st13->GetY1NDC()-0.05); st14->SetY2NDC(st13->GetY2NDC()-0.05); st14->SetLineColor(0); st14->SetTextColor(h14->GetLineColor()); st14->SetFillStyle(0); st14->Draw(); //====================== c1->cd(8); h15->Draw(); h16->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st15 = (TPaveStats*)h15->FindObject("stats"); st15->SetLineColor(0); gPad->Update(); TPaveStats *st16 = (TPaveStats*)h16->FindObject("stats"); st16->SetY1NDC(st15->GetY1NDC()-0.05); st16->SetY2NDC(st15->GetY2NDC()-0.05); st16->SetLineColor(0); st16->SetTextColor(h16->GetLineColor()); st16->SetFillStyle(0); st16->Draw(); //====================== c1->cd(9); h17->Draw(); h18->Draw("sames"); leg1->Draw("same"); gPad->Update(); TPaveStats *st17 = (TPaveStats*)h17->FindObject("stats"); st17->SetLineColor(0); gPad->Update(); TPaveStats *st18 = (TPaveStats*)h18->FindObject("stats"); st18->SetY1NDC(st17->GetY1NDC()-0.05); st18->SetY2NDC(st17->GetY2NDC()-0.05); st18->SetLineColor(0); st18->SetTextColor(h18->GetLineColor()); st18->SetFillStyle(0); st18->Draw(); //====================== c1->SaveAs("HLT-offline.png"); } - added functions to replace big parts of the macro that were being repeated - removed the DCA plot read from the HLTesdTree - saved a ROOT file in addition to the png output of the macro - can be run in compiled mode too // $Id$ /* * Plotting macro for comparing offline- and HLT- ESD trees from * HLT-OFFLINE-GLOBAL-comparison.root produced using $ALICE_ROOT/HLT/QA/tasks/AliAnalysisTaskHLT.* * * Usage: aliroot drawGlobalESDHistograms.C'("HLT-OFFLINE-GLOBAL-comparison.root")' * * or aliroot drawGlobalESDHistograms.C++ in compiled mode * * It saves the canvas with the output histograms in a png file. * * @ingroup alihlt_qa * @author Camilla.Stokkevag@student.uib.no, Kalliopi.Kanaki@ift.uib.no */ #if !defined(__CINT__) || defined(__MAKECINT__) #include "TSystem.h" #include "TROOT.h" #include "TFile.h" #include "TString.h" #include "TList.h" #include "TCanvas.h" #include "TText.h" #include "TPaveText.h" #include "TPaveStats.h" #include "TH1D.h" #include "TH2D.h" #include "TLegend.h" #include "TStyle.h" #include "TPad.h" #include <iostream> #include <cstdlib> using std::endl; #endif // --------------------- forward declerations --------------// void printStats(TH1F *h1, TH1F *h2); void plot(TH1F *h1, TH1F *h2); //==========================================================// void drawGlobalESDHistograms(const char* filename="HLT-OFFLINE-GLOBAL-comparison.root"){ gROOT->SetStyle("Plain"); gStyle->SetPalette(1); gStyle->SetOptStat("emr"); gStyle->SetTitleX(gStyle->GetPadLeftMargin()); TFile *f1 = TFile::Open(filename); if(!f1 || f1->IsZombie()) { printf("file %s does not exist or there is an error opening it\n", filename); return; } TList *l1 = (TList*)f1->Get("global_histograms"); if(!l1){ printf("No list %s contained in your input file\n", l1->GetName()); return; } TCanvas *c1 = new TCanvas("c1","HLT vs. offline",1200,700); c1->Divide(3,3); TH1F *h1 = NULL; TH1F *h2 = NULL; h1 = (TH1F*)l1->FindObject("fNcluster_hlt"); if(!h1) { printf("Empty histogram fNcluster_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fNcluster_off"); if(!h2) { printf("Empty histogram fNcluster_off\n"); return; } h1->SetTitle("TPC cluster distribution"); h1->GetXaxis()->SetTitle("TPC clusters per track"); TLegend *leg1 = new TLegend(0.7,0.6,0.88,0.77); leg1->SetFillColor(10); leg1->SetLineColor(10); leg1->AddEntry(h1,"HLT", "l"); leg1->AddEntry(h2,"OFF", "l"); c1->cd(1); plot(h1,h2); leg1->Draw("same"); //------------------------------------------------- h1 = (TH1F*)l1->FindObject("fDCA_hlt"); if(!h1) { printf("Empty histogram fDCA_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fDCA_off"); if(!h2) { printf("Empty histogram fDCA_off\n"); return; } h1->SetTitle("DCA between track and vertex on XY plane"); h1->SetXTitle("DCAr (cm)"); c1->cd(2); plot(h1,h2); //------------------------------------------------- h1 = (TH1F*)l1->FindObject("fMult_hlt"); if(!h1) { printf("Empty histogram fMult_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fMult_off"); if(!h2) { printf("Empty histogram fMult_off\n"); return; } h1->SetTitle("track multiplicity"); c1->cd(3); plot(h1,h2); //------------------------------------------------- h1 = (TH1F*)l1->FindObject("fCharge_hlt"); if(!h1) { printf("Empty histogram fCharge_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fCharge_off"); if(!h2) { printf("Empty histogram fCharge_off\n"); return; } h1->SetXTitle("polarity"); h1->SetTitle("charge distribution"); c1->cd(4); plot(h1,h2); //------------------------------------------------- h1 = (TH1F*)l1->FindObject("fMomentum_hlt"); if(!h1) { printf("Empty histogram fMomentum_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fMomentum_off"); if(!h2) { printf("Empty histogram fMomentum_off\n"); return; } h1->SetXTitle("p_{t} (GeV/c)"); h1->SetTitle("transverse momentum"); c1->cd(5); plot(h1,h2); //------------------------------------------------- h1 = (TH1F*)l1->FindObject("fEta_hlt"); if(!h1) { printf("Empty histogram fEta_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fEta_off"); if(!h2) { printf("Empty histogram fEta_off\n"); return; } h1->SetTitle("pseudorapidity"); h1->SetXTitle("#eta"); c1->cd(6); plot(h1,h2); //------------------------------------------------- h1 = (TH1F*)l1->FindObject("fXvertex_hlt"); if(!h1) { printf("Empty histogram fXvertex_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fXvertex_off"); if(!h2) { printf("Empty histogram fXvertex_off\n"); return; } h1->SetXTitle("x (cm)"); h1->SetTitle("x of primary vertex"); c1->cd(7); plot(h1,h2); //------------------------------------------------- h1 = (TH1F*)l1->FindObject("fYvertex_hlt"); if(!h1) { printf("Empty histogram fYvertex_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fYvertex_off"); if(!h2) { printf("Empty histogram fYvertex_off\n"); return; } h1->SetXTitle("y (cm)"); h1->SetTitle("y of primary vertex"); c1->cd(8); plot(h1,h2); //------------------------------------------------- h1 = (TH1F*)l1->FindObject("fZvertex_hlt"); if(!h1) { printf("Empty histogram fZvertex_hlt\n"); return; } h2 = (TH1F*)l1->FindObject("fZvertex_off"); if(!h2) { printf("Empty histogram fZvertex_off\n"); return; } h1->SetXTitle("z (cm)"); h1->SetTitle("z of primary vertex"); c1->cd(9); plot(h1,h2); //------------------------------------------------- c1->SaveAs("HLT-offline.png"); c1->SaveAs("HLT-offline.root"); return; } void printStats(TH1F* h1, TH1F* h2){ gPad->Update(); TPaveStats *st1 = (TPaveStats*)h1->FindObject("stats"); if(!st1) { printf("TPaveStats st1 is 0x0\n"); return; } st1->SetLineColor(0); gPad->Update(); TPaveStats *st2 = (TPaveStats*)h2->FindObject("stats"); if(!st2) { printf("TPaveStats st2 is 0x0\n"); return; } st2->SetY2NDC(st1->GetY1NDC()-0.05); st2->SetY1NDC(st2->GetY2NDC()-TMath::Abs(st1->GetY1NDC()-st1->GetY2NDC())); st2->SetLineColor(0); st2->SetTextColor(h2->GetLineColor()); st2->SetFillStyle(0); st2->Draw(); return; } void plot(TH1F *h1, TH1F *h2){ //Y axis if(h1->GetMaximum() > h2->GetMaximum()) h2->SetMaximum(1.1*h1->GetMaximum()); else h1->SetMaximum(1.1*h2->GetMaximum()); h1->SetMinimum(0); h2->SetMinimum(0); h2->SetLineColor(2); // X axis double xmin, xmax; if(h1->GetBinLowEdge(1) > h2->GetBinLowEdge(1)) xmin = h1->GetBinLowEdge(1); else xmin = h2->GetBinLowEdge(1); if(h1->GetBinLowEdge(h1->GetNbinsX()+1) > h2->GetBinLowEdge(h1->GetNbinsX()+1)) xmax = h1->GetBinLowEdge(h1->GetNbinsX()+1); else xmax = h2->GetBinLowEdge(h2->GetNbinsX()+1); h2->SetAxisRange(xmin, xmax, "X"); printStats(h1,h2); h1->Draw(); h2->Draw("sames"); return; }
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2022 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/digitaluniverse/rendering/renderablebillboardscloud.h> #include <modules/digitaluniverse/digitaluniversemodule.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/engine/globals.h> #include <openspace/engine/windowdelegate.h> #include <openspace/util/updatestructures.h> #include <openspace/rendering/renderengine.h> #include <ghoul/filesystem/cachemanager.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/font/fontmanager.h> #include <ghoul/font/fontrenderer.h> #include <ghoul/glm.h> #include <ghoul/io/texture/texturereader.h> #include <ghoul/logging/logmanager.h> #include <ghoul/misc/crc32.h> #include <ghoul/misc/templatefactory.h> #include <ghoul/misc/profiling.h> #include <ghoul/opengl/openglstatecache.h> #include <ghoul/opengl/programobject.h> #include <ghoul/opengl/texture.h> #include <ghoul/opengl/textureunit.h> #include <glm/gtx/string_cast.hpp> #include <array> #include <cstdint> #include <filesystem> #include <fstream> #include <locale> #include <optional> #include <string> namespace { constexpr const char* _loggerCat = "RenderableBillboardsCloud"; constexpr const char* ProgramObjectName = "RenderableBillboardsCloud"; constexpr const char* RenderToPolygonProgram = "RenderableBillboardsCloud_Polygon"; constexpr const std::array<const char*, 21> UniformNames = { "cameraViewProjectionMatrix", "modelMatrix", "cameraPosition", "cameraLookUp", "renderOption", "minBillboardSize", "maxBillboardSize", "correctionSizeEndDistance", "correctionSizeFactor", "color", "alphaValue", "scaleFactor", "up", "right", "fadeInValue", "screenSize", "spriteTexture", "hasColorMap", "useColorMap", "enabledRectSizeControl", "hasDvarScaling" }; enum RenderOption { ViewDirection = 0, PositionNormal }; constexpr openspace::properties::Property::PropertyInfo SpriteTextureInfo = { "Texture", "Point Sprite Texture", "The path to the texture that should be used as the point sprite." }; constexpr openspace::properties::Property::PropertyInfo ScaleFactorInfo = { "ScaleFactor", "Scale Factor", "This value is used as a multiplicative factor that is applied to the apparent " "size of each point." }; constexpr openspace::properties::Property::PropertyInfo UseColorMapInfo = { "UseColorMap", "Use Color Map", "If this value is set to 'true', the provided color map is used (if one was " "provided in the configuration). If no color map was provided, changing this " "setting does not do anything." }; constexpr openspace::properties::Property::PropertyInfo ColorInfo = { "Color", "Color", "This value is used to define the color of the astronomical object." }; constexpr openspace::properties::Property::PropertyInfo ColorMapInfo = { "ColorMap", "Color Map File", "The path to the color map file of the astronomical object." }; constexpr openspace::properties::Property::PropertyInfo TextColorInfo = { "TextColor", "Text Color", "The text color for the astronomical object." }; constexpr openspace::properties::Property::PropertyInfo TextOpacityInfo = { "TextOpacity", "Text Opacity", "Determines the transparency of the text label, where 1 is completely opaque " "and 0 fully transparent." }; constexpr openspace::properties::Property::PropertyInfo TextSizeInfo = { "TextSize", "Text Size", "The text size for the astronomical object labels." }; constexpr openspace::properties::Property::PropertyInfo LabelMinMaxSizeInfo = { "TextMinMaxSize", "Text Min/Max Size", "The minimal and maximal size (in pixels) of the text for the labels for the " "astronomical objects being rendered." }; constexpr openspace::properties::Property::PropertyInfo DrawElementsInfo = { "DrawElements", "Draw Elements", "Enables/Disables the drawing of the astronomical objects." }; constexpr openspace::properties::Property::PropertyInfo DrawLabelInfo = { "DrawLabels", "Draw Labels", "Determines whether labels should be drawn or hidden." }; constexpr openspace::properties::Property::PropertyInfo ColorOptionInfo = { "ColorOption", "Color Option", "This value determines which paramenter is used for default color of the " "astronomical objects." }; constexpr openspace::properties::Property::PropertyInfo OptionColorRangeInfo = { "OptionColorRange", "Option Color Range", "This value changes the range of values to be mapped with the current color map." }; constexpr openspace::properties::Property::PropertyInfo SizeOptionInfo = { "SizeOption", "Size Option Variable", "This value determines which paramenter (datavar) is used for scaling " "of the astronomical objects." }; constexpr openspace::properties::Property::PropertyInfo RenderOptionInfo = { "RenderOption", "Render Option", "Debug option for rendering of billboards and texts." }; constexpr openspace::properties::Property::PropertyInfo FadeInDistancesInfo = { "FadeInDistances", "Fade-In Start and End Distances", "These values determine the initial and final distances from the center of " "our galaxy from which the astronomical object will start and end " "fading-in." }; constexpr openspace::properties::Property::PropertyInfo DisableFadeInInfo = { "DisableFadeIn", "Disable Fade-in Effect", "Enables/Disables the Fade-in effect." }; constexpr openspace::properties::Property::PropertyInfo PixelSizeControlInfo = { "EnablePixelSizeControl", "Enable Pixel Size Control", "Enable pixel size control for rectangular projections. If set to true, the " "billboard size is restricted by the min/max size in pixels property." }; constexpr openspace::properties::Property::PropertyInfo BillboardMinMaxSizeInfo = { "BillboardMinMaxSize", "Billboard Min/Max Size in Pixels", "The minimum and maximum size (in pixels) for the billboard representing the " "astronomical object." }; constexpr openspace::properties::Property::PropertyInfo CorrectionSizeEndDistanceInfo = { "CorrectionSizeEndDistance", "Distance in 10^X meters where correction size stops acting", "Distance in 10^X meters where correction size stops acting." }; constexpr openspace::properties::Property::PropertyInfo CorrectionSizeFactorInfo = { "CorrectionSizeFactor", "Control variable for distance size", "" }; constexpr openspace::properties::Property::PropertyInfo UseLinearFiltering = { "UseLinearFiltering", "Use Linear Filtering", "Determines whether the provided color map should be sampled nearest neighbor " "(=off) or linearly (=on)" }; constexpr openspace::properties::Property::PropertyInfo SetRangeFromData = { "SetRangeFromData", "Set Data Range from Data", "Set the data range based on the available data" }; struct [[codegen::Dictionary(RenderableBillboardsCloud)]] Parameters { // The path to the SPECK file that contains information about the astronomical // object being rendered std::optional<std::string> file; // [[codegen::verbatim(ColorInfo.description)]] glm::vec3 color [[codegen::color()]]; // [[codegen::verbatim(SpriteTextureInfo.description)]] std::optional<std::string> texture; // [[codegen::verbatim(DrawElementsInfo.description)]] std::optional<bool> drawElements; enum class [[codegen::map(RenderOption)]] RenderOption { ViewDirection [[codegen::key("Camera View Direction")]], PositionNormal [[codegen::key("Camera Position Normal")]] }; // [[codegen::verbatim(RenderOptionInfo.description)]] std::optional<RenderOption> renderOption; enum class [[codegen::map(openspace::DistanceUnit)]] Unit { Meter [[codegen::key("m")]], Kilometer [[codegen::key("Km")]], Parsec [[codegen::key("pc")]], Kiloparsec [[codegen::key("Kpc")]], Megaparsec [[codegen::key("Mpc")]], Gigaparsec [[codegen::key("Gpc")]], Gigalightyear [[codegen::key("Gly")]] }; // The unit used for all distances. Must match the unit of any // distances/positions in the data files std::optional<Unit> unit; // [[codegen::verbatim(ScaleFactorInfo.description)]] std::optional<float> scaleFactor; // [[codegen::verbatim(UseColorMapInfo.description)]] std::optional<bool> useColorMap; // [[codegen::verbatim(ColorMapInfo.description)]] std::optional<std::string> colorMap; // Set a 1 to 1 relationship between the color index variable and the colormap // entrered value std::optional<bool> exactColorMap; // The number of sides for the polygon used to represent the astronomical object std::optional<int> polygonSides; // [[codegen::verbatim(DrawLabelInfo.description)]] std::optional<bool> drawLabels; // [[codegen::verbatim(TextColorInfo.description)]] std::optional<glm::vec3> textColor [[codegen::color()]]; // [[codegen::verbatim(TextOpacityInfo.description)]] std::optional<float> textOpacity; // [[codegen::verbatim(TextSizeInfo.description)]] std::optional<float> textSize; // The path to the label file that contains information about the astronomical // objects being rendered std::optional<std::string> labelFile; // [[codegen::verbatim(LabelMinMaxSizeInfo.description)]] std::optional<glm::ivec2> textMinMaxSize; // [[codegen::verbatim(ColorOptionInfo.description)]] std::optional<std::vector<std::string>> colorOption; // [[codegen::verbatim(SizeOptionInfo.description)]] std::optional<std::vector<std::string>> sizeOption; // This value determines the colormap ranges for the color parameters of the // astronomical objects std::optional<std::vector<glm::vec2>> colorRange; // Transformation matrix to be applied to each astronomical object std::optional<glm::dmat4x4> transformationMatrix; // [[codegen::verbatim(FadeInDistancesInfo.description)]] std::optional<glm::dvec2> fadeInDistances; // [[codegen::verbatim(DisableFadeInInfo.description)]] std::optional<bool> disableFadeIn; // [[codegen::verbatim(BillboardMinMaxSizeInfo.description)]] std::optional<glm::vec2> billboardMinMaxSize; // [[codegen::verbatim(CorrectionSizeEndDistanceInfo.description)]] std::optional<float> correctionSizeEndDistance; // [[codegen::verbatim(CorrectionSizeFactorInfo.description)]] std::optional<float> correctionSizeFactor; // [[codegen::verbatim(PixelSizeControlInfo.description)]] std::optional<bool> enablePixelSizeControl; // [[codegen::verbatim(UseLinearFiltering.description)]] std::optional<bool> useLinearFiltering; }; #include "renderablebillboardscloud_codegen.cpp" } // namespace namespace openspace { documentation::Documentation RenderableBillboardsCloud::Documentation() { return codegen::doc<Parameters>("digitaluniverse_RenderableBillboardsCloud"); } RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _scaleFactor(ScaleFactorInfo, 1.f, 0.f, 600.f) , _useColorMap(UseColorMapInfo, true) , _pointColor(ColorInfo, glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) , _spriteTexturePath(SpriteTextureInfo) , _textColor(TextColorInfo, glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) , _textOpacity(TextOpacityInfo, 1.f, 0.f, 1.f) , _textSize(TextSizeInfo, 8.f, 0.5f, 24.f) , _textMinMaxSize( LabelMinMaxSizeInfo, glm::ivec2(8, 20), glm::ivec2(0), glm::ivec2(100) ) , _drawElements(DrawElementsInfo, true) , _drawLabels(DrawLabelInfo, false) , _pixelSizeControl(PixelSizeControlInfo, false) , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) , _optionColorRangeData(OptionColorRangeInfo, glm::vec2(0.f)) , _datavarSizeOption( SizeOptionInfo, properties::OptionProperty::DisplayType::Dropdown ) , _fadeInDistances( FadeInDistancesInfo, glm::vec2(0.f), glm::vec2(0.f), glm::vec2(100.f) ) , _disableFadeInDistance(DisableFadeInInfo, true) , _billboardMinMaxSize( BillboardMinMaxSizeInfo, glm::vec2(0.f, 400.f), glm::vec2(0.f), glm::vec2(1000.f) ) , _correctionSizeEndDistance(CorrectionSizeEndDistanceInfo, 17.f, 12.f, 25.f) , _correctionSizeFactor(CorrectionSizeFactorInfo, 8.f, 0.f, 20.f) , _useLinearFiltering(UseLinearFiltering, false) , _setRangeFromData(SetRangeFromData) , _renderOption(RenderOptionInfo, properties::OptionProperty::DisplayType::Dropdown) { const Parameters p = codegen::bake<Parameters>(dictionary); if (p.file.has_value()) { _speckFile = absPath(*p.file).string(); } _hasSpeckFile = p.file.has_value(); _useColorMap = p.useColorMap.value_or(_useColorMap); _drawElements = p.drawElements.value_or(_drawElements); _drawElements.onChange([&]() { _hasSpeckFile = !_hasSpeckFile; }); addProperty(_drawElements); _renderOption.addOption(RenderOption::ViewDirection, "Camera View Direction"); _renderOption.addOption(RenderOption::PositionNormal, "Camera Position Normal"); if (p.renderOption.has_value()) { _renderOption = codegen::map<RenderOption>(*p.renderOption); } else { _renderOption = RenderOption::ViewDirection; } addProperty(_renderOption); if (p.unit.has_value()) { _unit = codegen::map<DistanceUnit>(*p.unit); } else { _unit = DistanceUnit::Meter; } if (p.texture.has_value()) { _spriteTexturePath = absPath(*p.texture).string(); _spriteTexturePath.onChange([&]() { _spriteTextureIsDirty = true; }); // @TODO (abock, 2021-01-31) I don't know why we only add this property if the // texture is given, but I think it's a bug // @TODO (emmbr, 2021-05-24) This goes for several properties in this renderable addProperty(_spriteTexturePath); } _hasSpriteTexture = p.texture.has_value(); if (p.colorMap.has_value()) { _colorMapFile = absPath(*p.colorMap).string(); _hasColorMapFile = true; if (p.colorOption.has_value()) { std::vector<std::string> opts = *p.colorOption; for (size_t i = 0; i < opts.size(); ++i) { _colorOption.addOption(static_cast<int>(i), opts[i]); _optionConversionMap.insert({ static_cast<int>(i), opts[i] }); _colorOptionString = opts[i]; } } _colorOption.onChange([&]() { _dataIsDirty = true; const glm::vec2 colorRange = _colorRangeData[_colorOption.value()]; _optionColorRangeData = colorRange; _colorOptionString = _optionConversionMap[_colorOption.value()]; }); addProperty(_colorOption); _colorRangeData = p.colorRange.value_or(_colorRangeData); if (!_colorRangeData.empty()) { _optionColorRangeData = _colorRangeData[_colorRangeData.size() - 1]; } _optionColorRangeData.onChange([&]() { const glm::vec2 colorRange = _optionColorRangeData; _colorRangeData[_colorOption.value()] = colorRange; _dataIsDirty = true; }); addProperty(_optionColorRangeData); _isColorMapExact = p.exactColorMap.value_or(_isColorMapExact); } _pointColor = p.color; _pointColor.setViewOption(properties::Property::ViewOptions::Color); addProperty(_pointColor); addProperty(_opacity); _scaleFactor = p.scaleFactor.value_or(_scaleFactor); addProperty(_scaleFactor); if (p.sizeOption.has_value()) { std::vector<std::string> opts = *p.sizeOption; for (size_t i = 0; i < opts.size(); ++i) { _datavarSizeOption.addOption(static_cast<int>(i), opts[i]); _optionConversionSizeMap.insert({ static_cast<int>(i), opts[i] }); _datavarSizeOptionString = opts[i]; } _datavarSizeOption.onChange([&]() { _dataIsDirty = true; _datavarSizeOptionString = _optionConversionSizeMap[_datavarSizeOption]; }); addProperty(_datavarSizeOption); _hasDatavarSize = true; } _polygonSides = p.polygonSides.value_or(_polygonSides); _hasPolygon = p.polygonSides.has_value(); if (p.labelFile.has_value()) { _drawLabels = p.drawLabels.value_or(_drawLabels); addProperty(_drawLabels); _labelFile = absPath(*p.labelFile).string(); _hasLabel = true; _textColor = p.textColor.value_or(_textColor); _hasLabel = p.textColor.has_value(); _textColor.setViewOption(properties::Property::ViewOptions::Color); addProperty(_textColor); _textColor.onChange([&]() { _textColorIsDirty = true; }); _textOpacity = p.textOpacity.value_or(_textOpacity); addProperty(_textOpacity); _textSize = p.textSize.value_or(_textSize); addProperty(_textSize); _textMinMaxSize = p.textMinMaxSize.value_or(_textMinMaxSize); _textMinMaxSize.setViewOption(properties::Property::ViewOptions::MinMaxRange); addProperty(_textMinMaxSize); } _transformationMatrix = p.transformationMatrix.value_or(_transformationMatrix); if (p.fadeInDistances.has_value()) { _fadeInDistances = *p.fadeInDistances; _fadeInDistances.setViewOption(properties::Property::ViewOptions::MinMaxRange); addProperty(_fadeInDistances); _disableFadeInDistance = false; addProperty(_disableFadeInDistance); } _pixelSizeControl = p.enablePixelSizeControl.value_or(_pixelSizeControl); addProperty(_pixelSizeControl); _billboardMinMaxSize = p.billboardMinMaxSize.value_or(_billboardMinMaxSize); _billboardMinMaxSize.setViewOption(properties::Property::ViewOptions::MinMaxRange); addProperty(_billboardMinMaxSize); _correctionSizeEndDistance = p.correctionSizeEndDistance.value_or(_correctionSizeEndDistance); addProperty(_correctionSizeEndDistance); _correctionSizeFactor = p.correctionSizeFactor.value_or(_correctionSizeFactor); if (p.correctionSizeFactor.has_value()) { addProperty(_correctionSizeFactor); } _setRangeFromData.onChange([this]() { const int colorMapInUse = _hasColorMapFile ? _dataset.index(_colorOptionString) : 0; float minValue = std::numeric_limits<float>::max(); float maxValue = -std::numeric_limits<float>::max(); for (const speck::Dataset::Entry& e : _dataset.entries) { float color = e.data[colorMapInUse]; minValue = std::min(minValue, color); maxValue = std::max(maxValue, color); } _optionColorRangeData = glm::vec2(minValue, maxValue); }); addProperty(_setRangeFromData); _useColorMap.onChange([this]() { _dataIsDirty = true; }); addProperty(_useColorMap); _useLinearFiltering = p.useLinearFiltering.value_or(_useLinearFiltering); _useLinearFiltering.onChange([&]() { _dataIsDirty = true; }); addProperty(_useLinearFiltering); } bool RenderableBillboardsCloud::isReady() const { return (_program && (!_dataset.entries.empty())) || (!_labelset.entries.empty()); } void RenderableBillboardsCloud::initialize() { ZoneScoped if (_hasSpeckFile) { _dataset = speck::data::loadFileWithCache(_speckFile); } if (_hasColorMapFile) { _colorMap = speck::color::loadFileWithCache(_colorMapFile); } if (!_labelFile.empty()) { _labelset = speck::label::loadFileWithCache(_labelFile); for (speck::Labelset::Entry& e : _labelset.entries) { e.position = glm::vec3(_transformationMatrix * glm::dvec4(e.position, 1.0)); } } if (!_colorOptionString.empty() && (_colorRangeData.size() > 1)) { // Following DU behavior here. The last colormap variable // entry is the one selected by default. _colorOption.setValue(static_cast<int>(_colorRangeData.size() - 1)); } setRenderBin(Renderable::RenderBin::PreDeferredTransparent); } void RenderableBillboardsCloud::initializeGL() { ZoneScoped _program = DigitalUniverseModule::ProgramObjectManager.request( ProgramObjectName, []() { return global::renderEngine->buildRenderProgram( ProgramObjectName, absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_fs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_gs.glsl") ); } ); _renderToPolygonProgram = DigitalUniverseModule::ProgramObjectManager.request( RenderToPolygonProgram, []() { return ghoul::opengl::ProgramObject::Build( RenderToPolygonProgram, absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_fs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_gs.glsl") ); } ); ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); if (_hasPolygon) { createPolygonTexture(); } if (_hasLabel) { if (!_font) { size_t _fontSize = 50; _font = global::fontManager->font( "Mono", static_cast<float>(_fontSize), ghoul::fontrendering::FontManager::Outline::Yes, ghoul::fontrendering::FontManager::LoadGlyphs::No ); } } } void RenderableBillboardsCloud::deinitializeGL() { glDeleteBuffers(1, &_vbo); _vbo = 0; glDeleteVertexArrays(1, &_vao); _vao = 0; DigitalUniverseModule::ProgramObjectManager.release( ProgramObjectName, [](ghoul::opengl::ProgramObject* p) { global::renderEngine->removeRenderProgram(p); } ); _program = nullptr; DigitalUniverseModule::ProgramObjectManager.release(RenderToPolygonProgram); _renderToPolygonProgram = nullptr; DigitalUniverseModule::TextureManager.release(_spriteTexture); _spriteTexture = nullptr; if (_hasPolygon) { _polygonTexture = nullptr; glDeleteTextures(1, &_pTexture); } } void RenderableBillboardsCloud::renderBillboards(const RenderData& data, const glm::dmat4& modelMatrix, const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable) { glDepthMask(false); glEnablei(GL_BLEND, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE); _program->activate(); _program->setUniform( "screenSize", glm::vec2(global::renderEngine->renderingResolution()) ); _program->setUniform(_uniformCache.cameraPos, data.camera.positionVec3()); _program->setUniform( _uniformCache.cameraLookup, glm::vec3(data.camera.lookUpVectorWorldSpace()) ); _program->setUniform(_uniformCache.renderOption, _renderOption.value()); _program->setUniform(_uniformCache.modelMatrix, modelMatrix); _program->setUniform( _uniformCache.cameraViewProjectionMatrix, glm::mat4( glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix() ) ); const float minBillboardSize = _billboardMinMaxSize.value().x; // in pixels const float maxBillboardSize = _billboardMinMaxSize.value().y; // in pixels _program->setUniform(_uniformCache.minBillboardSize, minBillboardSize); _program->setUniform(_uniformCache.maxBillboardSize, maxBillboardSize); _program->setUniform(_uniformCache.color, _pointColor); _program->setUniform(_uniformCache.alphaValue, opacity()); _program->setUniform(_uniformCache.scaleFactor, _scaleFactor); _program->setUniform(_uniformCache.up, glm::vec3(orthoUp)); _program->setUniform(_uniformCache.right, glm::vec3(orthoRight)); _program->setUniform(_uniformCache.fadeInValue, fadeInVariable); _program->setUniform( _uniformCache.correctionSizeEndDistance, _correctionSizeEndDistance ); _program->setUniform(_uniformCache.correctionSizeFactor, _correctionSizeFactor); _program->setUniform(_uniformCache.enabledRectSizeControl, _pixelSizeControl); _program->setUniform(_uniformCache.hasDvarScaling, _hasDatavarSize); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); _program->setUniform(_uniformCache.screenSize, glm::vec2(viewport[2], viewport[3])); ghoul::opengl::TextureUnit textureUnit; textureUnit.activate(); if (_hasPolygon) { glBindTexture(GL_TEXTURE_2D, _pTexture); } else if (_spriteTexture) { _spriteTexture->bind(); } _program->setUniform(_uniformCache.spriteTexture, textureUnit); _program->setUniform(_uniformCache.hasColormap, _hasColorMapFile); _program->setUniform(_uniformCache.useColormap, _useColorMap); glBindVertexArray(_vao); glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(_dataset.entries.size())); glBindVertexArray(0); _program->deactivate(); global::renderEngine->openglStateCache().resetBlendState(); global::renderEngine->openglStateCache().resetDepthState(); } void RenderableBillboardsCloud::renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable) { glm::vec4 textColor = glm::vec4(glm::vec3(_textColor), _textOpacity * fadeInVariable); ghoul::fontrendering::FontRenderer::ProjectedLabelsInformation labelInfo; labelInfo.orthoRight = orthoRight; labelInfo.orthoUp = orthoUp; labelInfo.minSize = _textMinMaxSize.value().x; labelInfo.maxSize = _textMinMaxSize.value().y; labelInfo.cameraPos = data.camera.positionVec3(); labelInfo.cameraLookUp = data.camera.lookUpVectorWorldSpace(); labelInfo.renderType = _renderOption; labelInfo.mvpMatrix = modelViewProjectionMatrix; labelInfo.scale = pow(10.f, _textSize); labelInfo.enableDepth = true; labelInfo.enableFalseDepth = false; for (const speck::Labelset::Entry& e : _labelset.entries) { glm::vec3 scaledPos(e.position); scaledPos *= toMeter(_unit); ghoul::fontrendering::FontRenderer::defaultProjectionRenderer().render( *_font, scaledPos, e.text, textColor, labelInfo ); } } void RenderableBillboardsCloud::render(const RenderData& data, RendererTasks&) { float fadeInVar = 1.f; if (!_disableFadeInDistance) { float distCamera = static_cast<float>(glm::length(data.camera.positionVec3())); const glm::vec2 fadeRange = _fadeInDistances; const float a = static_cast<float>( 1.f / ((fadeRange.y - fadeRange.x) * toMeter(_unit)) ); const float b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); const float funcValue = a * distCamera + b; fadeInVar *= funcValue > 1.f ? 1.f : funcValue; if (funcValue < 0.01f) { return; } } glm::dmat4 modelMatrix = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation glm::dmat4(data.modelTransform.rotation) * // Spice rotation glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); glm::dmat4 modelViewMatrix = data.camera.combinedViewMatrix() * modelMatrix; glm::mat4 projectionMatrix = data.camera.projectionMatrix(); glm::dmat4 modelViewProjectionMatrix = glm::dmat4(projectionMatrix) * modelViewMatrix; glm::dvec3 cameraViewDirectionWorld = -data.camera.viewDirectionWorldSpace(); glm::dvec3 cameraUpDirectionWorld = data.camera.lookUpVectorWorldSpace(); glm::dvec3 orthoRight = glm::normalize( glm::cross(cameraUpDirectionWorld, cameraViewDirectionWorld) ); if (orthoRight == glm::dvec3(0.0)) { glm::dvec3 otherVector( cameraUpDirectionWorld.y, cameraUpDirectionWorld.x, cameraUpDirectionWorld.z ); orthoRight = glm::normalize(glm::cross(otherVector, cameraViewDirectionWorld)); } glm::dvec3 orthoUp = glm::normalize(glm::cross(cameraViewDirectionWorld, orthoRight)); if (_hasSpeckFile && _drawElements) { renderBillboards(data, modelMatrix, orthoRight, orthoUp, fadeInVar); } if (_drawLabels && _hasLabel) { renderLabels(data, modelViewProjectionMatrix, orthoRight, orthoUp, fadeInVar); } } void RenderableBillboardsCloud::update(const UpdateData&) { ZoneScoped if (_dataIsDirty && _hasSpeckFile) { ZoneScopedN("Data dirty") TracyGpuZone("Data dirty") LDEBUG("Regenerating data"); std::vector<float> slice = createDataSlice(); int size = static_cast<int>(slice.size()); if (_vao == 0) { glGenVertexArrays(1, &_vao); LDEBUG(fmt::format("Generating Vertex Array id '{}'", _vao)); } if (_vbo == 0) { glGenBuffers(1, &_vbo); LDEBUG(fmt::format("Generating Vertex Buffer Object id '{}'", _vbo)); } glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, size * sizeof(float), slice.data(), GL_STATIC_DRAW); GLint positionAttrib = _program->attributeLocation("in_position"); if (_hasColorMapFile && _hasDatavarSize) { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float), nullptr ); GLint colorMapAttrib = _program->attributeLocation("in_colormap"); glEnableVertexAttribArray(colorMapAttrib); glVertexAttribPointer( colorMapAttrib, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float), reinterpret_cast<void*>(4 * sizeof(float)) ); GLint dvarScalingAttrib = _program->attributeLocation("in_dvarScaling"); glEnableVertexAttribArray(dvarScalingAttrib); glVertexAttribPointer( dvarScalingAttrib, 1, GL_FLOAT, GL_FALSE, 9 * sizeof(float), reinterpret_cast<void*>(8 * sizeof(float)) ); } else if (_hasColorMapFile) { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), nullptr ); GLint colorMapAttrib = _program->attributeLocation("in_colormap"); glEnableVertexAttribArray(colorMapAttrib); glVertexAttribPointer( colorMapAttrib, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void*>(4 * sizeof(float)) ); } else if (_hasDatavarSize) { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), nullptr ); GLint dvarScalingAttrib = _program->attributeLocation("in_dvarScaling"); glEnableVertexAttribArray(dvarScalingAttrib); glVertexAttribPointer( dvarScalingAttrib, 1, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(4 * sizeof(float)) ); } else { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, 4, GL_FLOAT, GL_FALSE, 0, nullptr ); } glBindVertexArray(0); _dataIsDirty = false; } if (_hasSpriteTexture && _spriteTextureIsDirty && !_spriteTexturePath.value().empty()) { ZoneScopedN("Sprite texture") TracyGpuZone("Sprite texture") ghoul::opengl::Texture* texture = _spriteTexture; unsigned int hash = ghoul::hashCRC32File(_spriteTexturePath); _spriteTexture = DigitalUniverseModule::TextureManager.request( std::to_string(hash), [path = _spriteTexturePath]() -> std::unique_ptr<ghoul::opengl::Texture> { std::filesystem::path p = absPath(path); LINFO(fmt::format("Loaded texture from {}", p)); std::unique_ptr<ghoul::opengl::Texture> t = ghoul::io::TextureReader::ref().loadTexture(p.string(), 2); t->uploadTexture(); t->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); t->purgeFromRAM(); return t; } ); DigitalUniverseModule::TextureManager.release(texture); _spriteTextureIsDirty = false; } } std::vector<float> RenderableBillboardsCloud::createDataSlice() { ZoneScoped if (_dataset.entries.empty()) { return std::vector<float>(); } std::vector<float> result; if (_hasColorMapFile) { result.reserve(8 * _dataset.entries.size()); } else { result.reserve(4 * _dataset.entries.size()); } // what datavar in use for the index color int colorMapInUse = _hasColorMapFile ? _dataset.index(_colorOptionString) : 0; // what datavar in use for the size scaling (if present) int sizeScalingInUse = _hasDatavarSize ? _dataset.index(_datavarSizeOptionString) : -1; float minColorIdx = std::numeric_limits<float>::max(); float maxColorIdx = -std::numeric_limits<float>::max(); for (const speck::Dataset::Entry& e : _dataset.entries) { if (e.data.size() > 0) { float color = e.data[colorMapInUse]; minColorIdx = std::min(color, minColorIdx); maxColorIdx = std::max(color, maxColorIdx); } else { minColorIdx = 0; maxColorIdx = 0; } } double maxRadius = 0.0; float biggestCoord = -1.f; for (const speck::Dataset::Entry& e : _dataset.entries) { glm::vec3 transformedPos = glm::vec3(_transformationMatrix * glm::vec4( e.position, 1.0 )); float unitValue = 0.f; // (abock, 2022-01-02) This is vestigial from a previous rewrite. I just want to // make it work for now and we can rewrite it properly later switch (_unit) { case DistanceUnit::Meter: unitValue = 0.f; break; case DistanceUnit::Kilometer: unitValue = 1.f; break; case DistanceUnit::Parsec: unitValue = 2; break; case DistanceUnit::Kiloparsec: unitValue = 3; break; case DistanceUnit::Megaparsec: unitValue = 4; break; case DistanceUnit::Gigaparsec: unitValue = 5; break; case DistanceUnit::Gigalightyear: unitValue = 6; break; default: throw ghoul::MissingCaseException(); } glm::vec4 position(transformedPos, unitValue); const double unitMeter = toMeter(_unit); glm::dvec3 p = glm::dvec3(position) * unitMeter; const double r = glm::length(p); maxRadius = std::max(maxRadius, r); if (_hasColorMapFile) { for (int j = 0; j < 4; ++j) { result.push_back(position[j]); } biggestCoord = std::max(biggestCoord, glm::compMax(position)); // Note: if exact colormap option is not selected, the first color and the // last color in the colormap file are the outliers colors. float variableColor = e.data[colorMapInUse]; float cmax, cmin; if (_colorRangeData.empty()) { cmax = maxColorIdx; // Max value of datavar used for the index color cmin = minColorIdx; // Min value of datavar used for the index color } else { glm::vec2 currentColorRange = _colorRangeData[_colorOption.value()]; cmax = currentColorRange.y; cmin = currentColorRange.x; } if (_isColorMapExact) { int colorIndex = static_cast<int>(variableColor + cmin); for (int j = 0; j < 4; ++j) { result.push_back(_colorMap.entries[colorIndex][j]); } } else { if (_useLinearFiltering) { float valueT = (variableColor - cmin) / (cmax - cmin); // in [0, 1) valueT = std::clamp(valueT, 0.f, 1.f); const float idx = valueT * (_colorMap.entries.size() - 1); const int floorIdx = static_cast<int>(std::floor(idx)); const int ceilIdx = static_cast<int>(std::ceil(idx)); const glm::vec4 floorColor = _colorMap.entries[floorIdx]; const glm::vec4 ceilColor = _colorMap.entries[ceilIdx]; if (floorColor != ceilColor) { const glm::vec4 c = floorColor + idx * (ceilColor - floorColor); result.push_back(c.r); result.push_back(c.g); result.push_back(c.b); result.push_back(c.a); } else { result.push_back(floorColor.r); result.push_back(floorColor.g); result.push_back(floorColor.b); result.push_back(floorColor.a); } } else { float ncmap = static_cast<float>(_colorMap.entries.size()); float normalization = ((cmax != cmin) && (ncmap > 2.f)) ? (ncmap - 2.f) / (cmax - cmin) : 0; int colorIndex = static_cast<int>( (variableColor - cmin) * normalization + 1.f ); colorIndex = colorIndex < 0 ? 0 : colorIndex; colorIndex = colorIndex >= ncmap ? static_cast<int>(ncmap - 1.f) : colorIndex; for (int j = 0; j < 4; ++j) { result.push_back(_colorMap.entries[colorIndex][j]); } } } if (_hasDatavarSize) { result.push_back(e.data[sizeScalingInUse]); } } else if (_hasDatavarSize) { result.push_back(e.data[sizeScalingInUse]); for (int j = 0; j < 4; ++j) { result.push_back(position[j]); } } else { for (int j = 0; j < 4; ++j) { result.push_back(position[j]); } } } setBoundingSphere(maxRadius); _fadeInDistances.setMaxValue(glm::vec2(10.f * biggestCoord)); return result; } void RenderableBillboardsCloud::createPolygonTexture() { ZoneScoped LDEBUG("Creating Polygon Texture"); glGenTextures(1, &_pTexture); glBindTexture(GL_TEXTURE_2D, _pTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, 256, 0, GL_RGBA, GL_BYTE, nullptr); renderToTexture(_pTexture, 256, 256); } void RenderableBillboardsCloud::renderToTexture(GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight) { LDEBUG("Rendering to Texture"); // Saves initial Application's OpenGL State GLint defaultFBO; GLint viewport[4]; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); glGetIntegerv(GL_VIEWPORT, viewport); GLuint textureFBO; glGenFramebuffers(1, &textureFBO); glBindFramebuffer(GL_FRAMEBUFFER, textureFBO); GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, drawBuffers); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureToRenderTo, 0); glViewport(viewport[0], viewport[1], textureWidth, textureHeight); loadPolygonGeometryForRendering(); renderPolygonGeometry(_polygonVao); // Restores Applications' OpenGL State glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); glDeleteBuffers(1, &_polygonVbo); glDeleteVertexArrays(1, &_polygonVao); glDeleteFramebuffers(1, &textureFBO); } void RenderableBillboardsCloud::loadPolygonGeometryForRendering() { glGenVertexArrays(1, &_polygonVao); glGenBuffers(1, &_polygonVbo); glBindVertexArray(_polygonVao); glBindBuffer(GL_ARRAY_BUFFER, _polygonVbo); constexpr const std::array<GLfloat, 4> VertexData = { // x y z w 0.f, 0.f, 0.f, 1.f, }; glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(0); glBindVertexArray(0); } void RenderableBillboardsCloud::renderPolygonGeometry(GLuint vao) { std::unique_ptr<ghoul::opengl::ProgramObject> program = ghoul::opengl::ProgramObject::Build( "RenderableBillboardsCloud_Polygon", absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_fs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_gs.glsl") ); program->activate(); constexpr const glm::vec4 Black = glm::vec4(0.f, 0.f, 0.f, 0.f); glClearBufferfv(GL_COLOR, 0, glm::value_ptr(Black)); program->setUniform("sides", _polygonSides); program->setUniform("polygonColor", _pointColor); glBindVertexArray(vao); glDrawArrays(GL_POINTS, 0, 1); glBindVertexArray(0); program->deactivate(); } } // namespace openspace Prevent crash from using colormap without entries Can happen if all colormap variables were set, but the file didn't exist or couldn't be loaded /***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2022 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/digitaluniverse/rendering/renderablebillboardscloud.h> #include <modules/digitaluniverse/digitaluniversemodule.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/engine/globals.h> #include <openspace/engine/windowdelegate.h> #include <openspace/util/updatestructures.h> #include <openspace/rendering/renderengine.h> #include <ghoul/filesystem/cachemanager.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/font/fontmanager.h> #include <ghoul/font/fontrenderer.h> #include <ghoul/glm.h> #include <ghoul/io/texture/texturereader.h> #include <ghoul/logging/logmanager.h> #include <ghoul/misc/crc32.h> #include <ghoul/misc/templatefactory.h> #include <ghoul/misc/profiling.h> #include <ghoul/opengl/openglstatecache.h> #include <ghoul/opengl/programobject.h> #include <ghoul/opengl/texture.h> #include <ghoul/opengl/textureunit.h> #include <glm/gtx/string_cast.hpp> #include <array> #include <cstdint> #include <filesystem> #include <fstream> #include <locale> #include <optional> #include <string> namespace { constexpr const char* _loggerCat = "RenderableBillboardsCloud"; constexpr const char* ProgramObjectName = "RenderableBillboardsCloud"; constexpr const char* RenderToPolygonProgram = "RenderableBillboardsCloud_Polygon"; constexpr const std::array<const char*, 21> UniformNames = { "cameraViewProjectionMatrix", "modelMatrix", "cameraPosition", "cameraLookUp", "renderOption", "minBillboardSize", "maxBillboardSize", "correctionSizeEndDistance", "correctionSizeFactor", "color", "alphaValue", "scaleFactor", "up", "right", "fadeInValue", "screenSize", "spriteTexture", "hasColorMap", "useColorMap", "enabledRectSizeControl", "hasDvarScaling" }; enum RenderOption { ViewDirection = 0, PositionNormal }; constexpr openspace::properties::Property::PropertyInfo SpriteTextureInfo = { "Texture", "Point Sprite Texture", "The path to the texture that should be used as the point sprite." }; constexpr openspace::properties::Property::PropertyInfo ScaleFactorInfo = { "ScaleFactor", "Scale Factor", "This value is used as a multiplicative factor that is applied to the apparent " "size of each point." }; constexpr openspace::properties::Property::PropertyInfo UseColorMapInfo = { "UseColorMap", "Use Color Map", "If this value is set to 'true', the provided color map is used (if one was " "provided in the configuration). If no color map was provided, changing this " "setting does not do anything." }; constexpr openspace::properties::Property::PropertyInfo ColorInfo = { "Color", "Color", "This value is used to define the color of the astronomical object." }; constexpr openspace::properties::Property::PropertyInfo ColorMapInfo = { "ColorMap", "Color Map File", "The path to the color map file of the astronomical object." }; constexpr openspace::properties::Property::PropertyInfo TextColorInfo = { "TextColor", "Text Color", "The text color for the astronomical object." }; constexpr openspace::properties::Property::PropertyInfo TextOpacityInfo = { "TextOpacity", "Text Opacity", "Determines the transparency of the text label, where 1 is completely opaque " "and 0 fully transparent." }; constexpr openspace::properties::Property::PropertyInfo TextSizeInfo = { "TextSize", "Text Size", "The text size for the astronomical object labels." }; constexpr openspace::properties::Property::PropertyInfo LabelMinMaxSizeInfo = { "TextMinMaxSize", "Text Min/Max Size", "The minimal and maximal size (in pixels) of the text for the labels for the " "astronomical objects being rendered." }; constexpr openspace::properties::Property::PropertyInfo DrawElementsInfo = { "DrawElements", "Draw Elements", "Enables/Disables the drawing of the astronomical objects." }; constexpr openspace::properties::Property::PropertyInfo DrawLabelInfo = { "DrawLabels", "Draw Labels", "Determines whether labels should be drawn or hidden." }; constexpr openspace::properties::Property::PropertyInfo ColorOptionInfo = { "ColorOption", "Color Option", "This value determines which paramenter is used for default color of the " "astronomical objects." }; constexpr openspace::properties::Property::PropertyInfo OptionColorRangeInfo = { "OptionColorRange", "Option Color Range", "This value changes the range of values to be mapped with the current color map." }; constexpr openspace::properties::Property::PropertyInfo SizeOptionInfo = { "SizeOption", "Size Option Variable", "This value determines which paramenter (datavar) is used for scaling " "of the astronomical objects." }; constexpr openspace::properties::Property::PropertyInfo RenderOptionInfo = { "RenderOption", "Render Option", "Debug option for rendering of billboards and texts." }; constexpr openspace::properties::Property::PropertyInfo FadeInDistancesInfo = { "FadeInDistances", "Fade-In Start and End Distances", "These values determine the initial and final distances from the center of " "our galaxy from which the astronomical object will start and end " "fading-in." }; constexpr openspace::properties::Property::PropertyInfo DisableFadeInInfo = { "DisableFadeIn", "Disable Fade-in Effect", "Enables/Disables the Fade-in effect." }; constexpr openspace::properties::Property::PropertyInfo PixelSizeControlInfo = { "EnablePixelSizeControl", "Enable Pixel Size Control", "Enable pixel size control for rectangular projections. If set to true, the " "billboard size is restricted by the min/max size in pixels property." }; constexpr openspace::properties::Property::PropertyInfo BillboardMinMaxSizeInfo = { "BillboardMinMaxSize", "Billboard Min/Max Size in Pixels", "The minimum and maximum size (in pixels) for the billboard representing the " "astronomical object." }; constexpr openspace::properties::Property::PropertyInfo CorrectionSizeEndDistanceInfo = { "CorrectionSizeEndDistance", "Distance in 10^X meters where correction size stops acting", "Distance in 10^X meters where correction size stops acting." }; constexpr openspace::properties::Property::PropertyInfo CorrectionSizeFactorInfo = { "CorrectionSizeFactor", "Control variable for distance size", "" }; constexpr openspace::properties::Property::PropertyInfo UseLinearFiltering = { "UseLinearFiltering", "Use Linear Filtering", "Determines whether the provided color map should be sampled nearest neighbor " "(=off) or linearly (=on)" }; constexpr openspace::properties::Property::PropertyInfo SetRangeFromData = { "SetRangeFromData", "Set Data Range from Data", "Set the data range based on the available data" }; struct [[codegen::Dictionary(RenderableBillboardsCloud)]] Parameters { // The path to the SPECK file that contains information about the astronomical // object being rendered std::optional<std::string> file; // [[codegen::verbatim(ColorInfo.description)]] glm::vec3 color [[codegen::color()]]; // [[codegen::verbatim(SpriteTextureInfo.description)]] std::optional<std::string> texture; // [[codegen::verbatim(DrawElementsInfo.description)]] std::optional<bool> drawElements; enum class [[codegen::map(RenderOption)]] RenderOption { ViewDirection [[codegen::key("Camera View Direction")]], PositionNormal [[codegen::key("Camera Position Normal")]] }; // [[codegen::verbatim(RenderOptionInfo.description)]] std::optional<RenderOption> renderOption; enum class [[codegen::map(openspace::DistanceUnit)]] Unit { Meter [[codegen::key("m")]], Kilometer [[codegen::key("Km")]], Parsec [[codegen::key("pc")]], Kiloparsec [[codegen::key("Kpc")]], Megaparsec [[codegen::key("Mpc")]], Gigaparsec [[codegen::key("Gpc")]], Gigalightyear [[codegen::key("Gly")]] }; // The unit used for all distances. Must match the unit of any // distances/positions in the data files std::optional<Unit> unit; // [[codegen::verbatim(ScaleFactorInfo.description)]] std::optional<float> scaleFactor; // [[codegen::verbatim(UseColorMapInfo.description)]] std::optional<bool> useColorMap; // [[codegen::verbatim(ColorMapInfo.description)]] std::optional<std::string> colorMap; // Set a 1 to 1 relationship between the color index variable and the colormap // entrered value std::optional<bool> exactColorMap; // The number of sides for the polygon used to represent the astronomical object std::optional<int> polygonSides; // [[codegen::verbatim(DrawLabelInfo.description)]] std::optional<bool> drawLabels; // [[codegen::verbatim(TextColorInfo.description)]] std::optional<glm::vec3> textColor [[codegen::color()]]; // [[codegen::verbatim(TextOpacityInfo.description)]] std::optional<float> textOpacity; // [[codegen::verbatim(TextSizeInfo.description)]] std::optional<float> textSize; // The path to the label file that contains information about the astronomical // objects being rendered std::optional<std::string> labelFile; // [[codegen::verbatim(LabelMinMaxSizeInfo.description)]] std::optional<glm::ivec2> textMinMaxSize; // [[codegen::verbatim(ColorOptionInfo.description)]] std::optional<std::vector<std::string>> colorOption; // [[codegen::verbatim(SizeOptionInfo.description)]] std::optional<std::vector<std::string>> sizeOption; // This value determines the colormap ranges for the color parameters of the // astronomical objects std::optional<std::vector<glm::vec2>> colorRange; // Transformation matrix to be applied to each astronomical object std::optional<glm::dmat4x4> transformationMatrix; // [[codegen::verbatim(FadeInDistancesInfo.description)]] std::optional<glm::dvec2> fadeInDistances; // [[codegen::verbatim(DisableFadeInInfo.description)]] std::optional<bool> disableFadeIn; // [[codegen::verbatim(BillboardMinMaxSizeInfo.description)]] std::optional<glm::vec2> billboardMinMaxSize; // [[codegen::verbatim(CorrectionSizeEndDistanceInfo.description)]] std::optional<float> correctionSizeEndDistance; // [[codegen::verbatim(CorrectionSizeFactorInfo.description)]] std::optional<float> correctionSizeFactor; // [[codegen::verbatim(PixelSizeControlInfo.description)]] std::optional<bool> enablePixelSizeControl; // [[codegen::verbatim(UseLinearFiltering.description)]] std::optional<bool> useLinearFiltering; }; #include "renderablebillboardscloud_codegen.cpp" } // namespace namespace openspace { documentation::Documentation RenderableBillboardsCloud::Documentation() { return codegen::doc<Parameters>("digitaluniverse_RenderableBillboardsCloud"); } RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _scaleFactor(ScaleFactorInfo, 1.f, 0.f, 600.f) , _useColorMap(UseColorMapInfo, true) , _pointColor(ColorInfo, glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) , _spriteTexturePath(SpriteTextureInfo) , _textColor(TextColorInfo, glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) , _textOpacity(TextOpacityInfo, 1.f, 0.f, 1.f) , _textSize(TextSizeInfo, 8.f, 0.5f, 24.f) , _textMinMaxSize( LabelMinMaxSizeInfo, glm::ivec2(8, 20), glm::ivec2(0), glm::ivec2(100) ) , _drawElements(DrawElementsInfo, true) , _drawLabels(DrawLabelInfo, false) , _pixelSizeControl(PixelSizeControlInfo, false) , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) , _optionColorRangeData(OptionColorRangeInfo, glm::vec2(0.f)) , _datavarSizeOption( SizeOptionInfo, properties::OptionProperty::DisplayType::Dropdown ) , _fadeInDistances( FadeInDistancesInfo, glm::vec2(0.f), glm::vec2(0.f), glm::vec2(100.f) ) , _disableFadeInDistance(DisableFadeInInfo, true) , _billboardMinMaxSize( BillboardMinMaxSizeInfo, glm::vec2(0.f, 400.f), glm::vec2(0.f), glm::vec2(1000.f) ) , _correctionSizeEndDistance(CorrectionSizeEndDistanceInfo, 17.f, 12.f, 25.f) , _correctionSizeFactor(CorrectionSizeFactorInfo, 8.f, 0.f, 20.f) , _useLinearFiltering(UseLinearFiltering, false) , _setRangeFromData(SetRangeFromData) , _renderOption(RenderOptionInfo, properties::OptionProperty::DisplayType::Dropdown) { const Parameters p = codegen::bake<Parameters>(dictionary); if (p.file.has_value()) { _speckFile = absPath(*p.file).string(); } _hasSpeckFile = p.file.has_value(); _useColorMap = p.useColorMap.value_or(_useColorMap); _drawElements = p.drawElements.value_or(_drawElements); _drawElements.onChange([&]() { _hasSpeckFile = !_hasSpeckFile; }); addProperty(_drawElements); _renderOption.addOption(RenderOption::ViewDirection, "Camera View Direction"); _renderOption.addOption(RenderOption::PositionNormal, "Camera Position Normal"); if (p.renderOption.has_value()) { _renderOption = codegen::map<RenderOption>(*p.renderOption); } else { _renderOption = RenderOption::ViewDirection; } addProperty(_renderOption); if (p.unit.has_value()) { _unit = codegen::map<DistanceUnit>(*p.unit); } else { _unit = DistanceUnit::Meter; } if (p.texture.has_value()) { _spriteTexturePath = absPath(*p.texture).string(); _spriteTexturePath.onChange([&]() { _spriteTextureIsDirty = true; }); // @TODO (abock, 2021-01-31) I don't know why we only add this property if the // texture is given, but I think it's a bug // @TODO (emmbr, 2021-05-24) This goes for several properties in this renderable addProperty(_spriteTexturePath); } _hasSpriteTexture = p.texture.has_value(); if (p.colorMap.has_value()) { _colorMapFile = absPath(*p.colorMap).string(); _hasColorMapFile = true; if (p.colorOption.has_value()) { std::vector<std::string> opts = *p.colorOption; for (size_t i = 0; i < opts.size(); ++i) { _colorOption.addOption(static_cast<int>(i), opts[i]); _optionConversionMap.insert({ static_cast<int>(i), opts[i] }); _colorOptionString = opts[i]; } } _colorOption.onChange([&]() { _dataIsDirty = true; const glm::vec2 colorRange = _colorRangeData[_colorOption.value()]; _optionColorRangeData = colorRange; _colorOptionString = _optionConversionMap[_colorOption.value()]; }); addProperty(_colorOption); _colorRangeData = p.colorRange.value_or(_colorRangeData); if (!_colorRangeData.empty()) { _optionColorRangeData = _colorRangeData[_colorRangeData.size() - 1]; } _optionColorRangeData.onChange([&]() { const glm::vec2 colorRange = _optionColorRangeData; _colorRangeData[_colorOption.value()] = colorRange; _dataIsDirty = true; }); addProperty(_optionColorRangeData); _isColorMapExact = p.exactColorMap.value_or(_isColorMapExact); } _pointColor = p.color; _pointColor.setViewOption(properties::Property::ViewOptions::Color); addProperty(_pointColor); addProperty(_opacity); _scaleFactor = p.scaleFactor.value_or(_scaleFactor); addProperty(_scaleFactor); if (p.sizeOption.has_value()) { std::vector<std::string> opts = *p.sizeOption; for (size_t i = 0; i < opts.size(); ++i) { _datavarSizeOption.addOption(static_cast<int>(i), opts[i]); _optionConversionSizeMap.insert({ static_cast<int>(i), opts[i] }); _datavarSizeOptionString = opts[i]; } _datavarSizeOption.onChange([&]() { _dataIsDirty = true; _datavarSizeOptionString = _optionConversionSizeMap[_datavarSizeOption]; }); addProperty(_datavarSizeOption); _hasDatavarSize = true; } _polygonSides = p.polygonSides.value_or(_polygonSides); _hasPolygon = p.polygonSides.has_value(); if (p.labelFile.has_value()) { _drawLabels = p.drawLabels.value_or(_drawLabels); addProperty(_drawLabels); _labelFile = absPath(*p.labelFile).string(); _hasLabel = true; _textColor = p.textColor.value_or(_textColor); _hasLabel = p.textColor.has_value(); _textColor.setViewOption(properties::Property::ViewOptions::Color); addProperty(_textColor); _textColor.onChange([&]() { _textColorIsDirty = true; }); _textOpacity = p.textOpacity.value_or(_textOpacity); addProperty(_textOpacity); _textSize = p.textSize.value_or(_textSize); addProperty(_textSize); _textMinMaxSize = p.textMinMaxSize.value_or(_textMinMaxSize); _textMinMaxSize.setViewOption(properties::Property::ViewOptions::MinMaxRange); addProperty(_textMinMaxSize); } _transformationMatrix = p.transformationMatrix.value_or(_transformationMatrix); if (p.fadeInDistances.has_value()) { _fadeInDistances = *p.fadeInDistances; _fadeInDistances.setViewOption(properties::Property::ViewOptions::MinMaxRange); addProperty(_fadeInDistances); _disableFadeInDistance = false; addProperty(_disableFadeInDistance); } _pixelSizeControl = p.enablePixelSizeControl.value_or(_pixelSizeControl); addProperty(_pixelSizeControl); _billboardMinMaxSize = p.billboardMinMaxSize.value_or(_billboardMinMaxSize); _billboardMinMaxSize.setViewOption(properties::Property::ViewOptions::MinMaxRange); addProperty(_billboardMinMaxSize); _correctionSizeEndDistance = p.correctionSizeEndDistance.value_or(_correctionSizeEndDistance); addProperty(_correctionSizeEndDistance); _correctionSizeFactor = p.correctionSizeFactor.value_or(_correctionSizeFactor); if (p.correctionSizeFactor.has_value()) { addProperty(_correctionSizeFactor); } _setRangeFromData.onChange([this]() { const int colorMapInUse = _hasColorMapFile ? _dataset.index(_colorOptionString) : 0; float minValue = std::numeric_limits<float>::max(); float maxValue = -std::numeric_limits<float>::max(); for (const speck::Dataset::Entry& e : _dataset.entries) { float color = e.data[colorMapInUse]; minValue = std::min(minValue, color); maxValue = std::max(maxValue, color); } _optionColorRangeData = glm::vec2(minValue, maxValue); }); addProperty(_setRangeFromData); _useColorMap.onChange([this]() { _dataIsDirty = true; }); addProperty(_useColorMap); _useLinearFiltering = p.useLinearFiltering.value_or(_useLinearFiltering); _useLinearFiltering.onChange([&]() { _dataIsDirty = true; }); addProperty(_useLinearFiltering); } bool RenderableBillboardsCloud::isReady() const { return (_program && (!_dataset.entries.empty())) || (!_labelset.entries.empty()); } void RenderableBillboardsCloud::initialize() { ZoneScoped if (_hasSpeckFile) { _dataset = speck::data::loadFileWithCache(_speckFile); } if (_hasColorMapFile) { _colorMap = speck::color::loadFileWithCache(_colorMapFile); } if (!_labelFile.empty()) { _labelset = speck::label::loadFileWithCache(_labelFile); for (speck::Labelset::Entry& e : _labelset.entries) { e.position = glm::vec3(_transformationMatrix * glm::dvec4(e.position, 1.0)); } } if (!_colorOptionString.empty() && (_colorRangeData.size() > 1)) { // Following DU behavior here. The last colormap variable // entry is the one selected by default. _colorOption.setValue(static_cast<int>(_colorRangeData.size() - 1)); } setRenderBin(Renderable::RenderBin::PreDeferredTransparent); } void RenderableBillboardsCloud::initializeGL() { ZoneScoped _program = DigitalUniverseModule::ProgramObjectManager.request( ProgramObjectName, []() { return global::renderEngine->buildRenderProgram( ProgramObjectName, absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_fs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_gs.glsl") ); } ); _renderToPolygonProgram = DigitalUniverseModule::ProgramObjectManager.request( RenderToPolygonProgram, []() { return ghoul::opengl::ProgramObject::Build( RenderToPolygonProgram, absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_fs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_gs.glsl") ); } ); ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); if (_hasPolygon) { createPolygonTexture(); } if (_hasLabel) { if (!_font) { size_t _fontSize = 50; _font = global::fontManager->font( "Mono", static_cast<float>(_fontSize), ghoul::fontrendering::FontManager::Outline::Yes, ghoul::fontrendering::FontManager::LoadGlyphs::No ); } } } void RenderableBillboardsCloud::deinitializeGL() { glDeleteBuffers(1, &_vbo); _vbo = 0; glDeleteVertexArrays(1, &_vao); _vao = 0; DigitalUniverseModule::ProgramObjectManager.release( ProgramObjectName, [](ghoul::opengl::ProgramObject* p) { global::renderEngine->removeRenderProgram(p); } ); _program = nullptr; DigitalUniverseModule::ProgramObjectManager.release(RenderToPolygonProgram); _renderToPolygonProgram = nullptr; DigitalUniverseModule::TextureManager.release(_spriteTexture); _spriteTexture = nullptr; if (_hasPolygon) { _polygonTexture = nullptr; glDeleteTextures(1, &_pTexture); } } void RenderableBillboardsCloud::renderBillboards(const RenderData& data, const glm::dmat4& modelMatrix, const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable) { glDepthMask(false); glEnablei(GL_BLEND, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE); _program->activate(); _program->setUniform( "screenSize", glm::vec2(global::renderEngine->renderingResolution()) ); _program->setUniform(_uniformCache.cameraPos, data.camera.positionVec3()); _program->setUniform( _uniformCache.cameraLookup, glm::vec3(data.camera.lookUpVectorWorldSpace()) ); _program->setUniform(_uniformCache.renderOption, _renderOption.value()); _program->setUniform(_uniformCache.modelMatrix, modelMatrix); _program->setUniform( _uniformCache.cameraViewProjectionMatrix, glm::mat4( glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix() ) ); const float minBillboardSize = _billboardMinMaxSize.value().x; // in pixels const float maxBillboardSize = _billboardMinMaxSize.value().y; // in pixels _program->setUniform(_uniformCache.minBillboardSize, minBillboardSize); _program->setUniform(_uniformCache.maxBillboardSize, maxBillboardSize); _program->setUniform(_uniformCache.color, _pointColor); _program->setUniform(_uniformCache.alphaValue, opacity()); _program->setUniform(_uniformCache.scaleFactor, _scaleFactor); _program->setUniform(_uniformCache.up, glm::vec3(orthoUp)); _program->setUniform(_uniformCache.right, glm::vec3(orthoRight)); _program->setUniform(_uniformCache.fadeInValue, fadeInVariable); _program->setUniform( _uniformCache.correctionSizeEndDistance, _correctionSizeEndDistance ); _program->setUniform(_uniformCache.correctionSizeFactor, _correctionSizeFactor); _program->setUniform(_uniformCache.enabledRectSizeControl, _pixelSizeControl); _program->setUniform(_uniformCache.hasDvarScaling, _hasDatavarSize); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); _program->setUniform(_uniformCache.screenSize, glm::vec2(viewport[2], viewport[3])); ghoul::opengl::TextureUnit textureUnit; textureUnit.activate(); if (_hasPolygon) { glBindTexture(GL_TEXTURE_2D, _pTexture); } else if (_spriteTexture) { _spriteTexture->bind(); } _program->setUniform(_uniformCache.spriteTexture, textureUnit); _program->setUniform(_uniformCache.hasColormap, _hasColorMapFile); _program->setUniform(_uniformCache.useColormap, _useColorMap); glBindVertexArray(_vao); glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(_dataset.entries.size())); glBindVertexArray(0); _program->deactivate(); global::renderEngine->openglStateCache().resetBlendState(); global::renderEngine->openglStateCache().resetDepthState(); } void RenderableBillboardsCloud::renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable) { glm::vec4 textColor = glm::vec4(glm::vec3(_textColor), _textOpacity * fadeInVariable); ghoul::fontrendering::FontRenderer::ProjectedLabelsInformation labelInfo; labelInfo.orthoRight = orthoRight; labelInfo.orthoUp = orthoUp; labelInfo.minSize = _textMinMaxSize.value().x; labelInfo.maxSize = _textMinMaxSize.value().y; labelInfo.cameraPos = data.camera.positionVec3(); labelInfo.cameraLookUp = data.camera.lookUpVectorWorldSpace(); labelInfo.renderType = _renderOption; labelInfo.mvpMatrix = modelViewProjectionMatrix; labelInfo.scale = pow(10.f, _textSize); labelInfo.enableDepth = true; labelInfo.enableFalseDepth = false; for (const speck::Labelset::Entry& e : _labelset.entries) { glm::vec3 scaledPos(e.position); scaledPos *= toMeter(_unit); ghoul::fontrendering::FontRenderer::defaultProjectionRenderer().render( *_font, scaledPos, e.text, textColor, labelInfo ); } } void RenderableBillboardsCloud::render(const RenderData& data, RendererTasks&) { float fadeInVar = 1.f; if (!_disableFadeInDistance) { float distCamera = static_cast<float>(glm::length(data.camera.positionVec3())); const glm::vec2 fadeRange = _fadeInDistances; const float a = static_cast<float>( 1.f / ((fadeRange.y - fadeRange.x) * toMeter(_unit)) ); const float b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); const float funcValue = a * distCamera + b; fadeInVar *= funcValue > 1.f ? 1.f : funcValue; if (funcValue < 0.01f) { return; } } glm::dmat4 modelMatrix = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation glm::dmat4(data.modelTransform.rotation) * // Spice rotation glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); glm::dmat4 modelViewMatrix = data.camera.combinedViewMatrix() * modelMatrix; glm::mat4 projectionMatrix = data.camera.projectionMatrix(); glm::dmat4 modelViewProjectionMatrix = glm::dmat4(projectionMatrix) * modelViewMatrix; glm::dvec3 cameraViewDirectionWorld = -data.camera.viewDirectionWorldSpace(); glm::dvec3 cameraUpDirectionWorld = data.camera.lookUpVectorWorldSpace(); glm::dvec3 orthoRight = glm::normalize( glm::cross(cameraUpDirectionWorld, cameraViewDirectionWorld) ); if (orthoRight == glm::dvec3(0.0)) { glm::dvec3 otherVector( cameraUpDirectionWorld.y, cameraUpDirectionWorld.x, cameraUpDirectionWorld.z ); orthoRight = glm::normalize(glm::cross(otherVector, cameraViewDirectionWorld)); } glm::dvec3 orthoUp = glm::normalize(glm::cross(cameraViewDirectionWorld, orthoRight)); if (_hasSpeckFile && _drawElements) { renderBillboards(data, modelMatrix, orthoRight, orthoUp, fadeInVar); } if (_drawLabels && _hasLabel) { renderLabels(data, modelViewProjectionMatrix, orthoRight, orthoUp, fadeInVar); } } void RenderableBillboardsCloud::update(const UpdateData&) { ZoneScoped if (_dataIsDirty && _hasSpeckFile) { ZoneScopedN("Data dirty") TracyGpuZone("Data dirty") LDEBUG("Regenerating data"); std::vector<float> slice = createDataSlice(); int size = static_cast<int>(slice.size()); if (_vao == 0) { glGenVertexArrays(1, &_vao); LDEBUG(fmt::format("Generating Vertex Array id '{}'", _vao)); } if (_vbo == 0) { glGenBuffers(1, &_vbo); LDEBUG(fmt::format("Generating Vertex Buffer Object id '{}'", _vbo)); } glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, size * sizeof(float), slice.data(), GL_STATIC_DRAW); GLint positionAttrib = _program->attributeLocation("in_position"); if (_hasColorMapFile && _hasDatavarSize) { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float), nullptr ); GLint colorMapAttrib = _program->attributeLocation("in_colormap"); glEnableVertexAttribArray(colorMapAttrib); glVertexAttribPointer( colorMapAttrib, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float), reinterpret_cast<void*>(4 * sizeof(float)) ); GLint dvarScalingAttrib = _program->attributeLocation("in_dvarScaling"); glEnableVertexAttribArray(dvarScalingAttrib); glVertexAttribPointer( dvarScalingAttrib, 1, GL_FLOAT, GL_FALSE, 9 * sizeof(float), reinterpret_cast<void*>(8 * sizeof(float)) ); } else if (_hasColorMapFile) { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), nullptr ); GLint colorMapAttrib = _program->attributeLocation("in_colormap"); glEnableVertexAttribArray(colorMapAttrib); glVertexAttribPointer( colorMapAttrib, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void*>(4 * sizeof(float)) ); } else if (_hasDatavarSize) { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), nullptr ); GLint dvarScalingAttrib = _program->attributeLocation("in_dvarScaling"); glEnableVertexAttribArray(dvarScalingAttrib); glVertexAttribPointer( dvarScalingAttrib, 1, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(4 * sizeof(float)) ); } else { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, 4, GL_FLOAT, GL_FALSE, 0, nullptr ); } glBindVertexArray(0); _dataIsDirty = false; } if (_hasSpriteTexture && _spriteTextureIsDirty && !_spriteTexturePath.value().empty()) { ZoneScopedN("Sprite texture") TracyGpuZone("Sprite texture") ghoul::opengl::Texture* texture = _spriteTexture; unsigned int hash = ghoul::hashCRC32File(_spriteTexturePath); _spriteTexture = DigitalUniverseModule::TextureManager.request( std::to_string(hash), [path = _spriteTexturePath]() -> std::unique_ptr<ghoul::opengl::Texture> { std::filesystem::path p = absPath(path); LINFO(fmt::format("Loaded texture from {}", p)); std::unique_ptr<ghoul::opengl::Texture> t = ghoul::io::TextureReader::ref().loadTexture(p.string(), 2); t->uploadTexture(); t->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); t->purgeFromRAM(); return t; } ); DigitalUniverseModule::TextureManager.release(texture); _spriteTextureIsDirty = false; } } std::vector<float> RenderableBillboardsCloud::createDataSlice() { ZoneScoped if (_dataset.entries.empty()) { return std::vector<float>(); } std::vector<float> result; if (_hasColorMapFile) { result.reserve(8 * _dataset.entries.size()); } else { result.reserve(4 * _dataset.entries.size()); } // what datavar in use for the index color int colorMapInUse = _hasColorMapFile ? _dataset.index(_colorOptionString) : 0; // what datavar in use for the size scaling (if present) int sizeScalingInUse = _hasDatavarSize ? _dataset.index(_datavarSizeOptionString) : -1; float minColorIdx = std::numeric_limits<float>::max(); float maxColorIdx = -std::numeric_limits<float>::max(); for (const speck::Dataset::Entry& e : _dataset.entries) { if (e.data.size() > 0) { float color = e.data[colorMapInUse]; minColorIdx = std::min(color, minColorIdx); maxColorIdx = std::max(color, maxColorIdx); } else { minColorIdx = 0; maxColorIdx = 0; } } double maxRadius = 0.0; float biggestCoord = -1.f; for (const speck::Dataset::Entry& e : _dataset.entries) { glm::vec3 transformedPos = glm::vec3(_transformationMatrix * glm::vec4( e.position, 1.0 )); float unitValue = 0.f; // (abock, 2022-01-02) This is vestigial from a previous rewrite. I just want to // make it work for now and we can rewrite it properly later switch (_unit) { case DistanceUnit::Meter: unitValue = 0.f; break; case DistanceUnit::Kilometer: unitValue = 1.f; break; case DistanceUnit::Parsec: unitValue = 2; break; case DistanceUnit::Kiloparsec: unitValue = 3; break; case DistanceUnit::Megaparsec: unitValue = 4; break; case DistanceUnit::Gigaparsec: unitValue = 5; break; case DistanceUnit::Gigalightyear: unitValue = 6; break; default: throw ghoul::MissingCaseException(); } glm::vec4 position(transformedPos, unitValue); const double unitMeter = toMeter(_unit); glm::dvec3 p = glm::dvec3(position) * unitMeter; const double r = glm::length(p); maxRadius = std::max(maxRadius, r); if (_hasColorMapFile && _useColorMap && !_colorMap.entries.empty()) { for (int j = 0; j < 4; ++j) { result.push_back(position[j]); } biggestCoord = std::max(biggestCoord, glm::compMax(position)); // Note: if exact colormap option is not selected, the first color and the // last color in the colormap file are the outliers colors. float variableColor = e.data[colorMapInUse]; float cmax, cmin; if (_colorRangeData.empty()) { cmax = maxColorIdx; // Max value of datavar used for the index color cmin = minColorIdx; // Min value of datavar used for the index color } else { glm::vec2 currentColorRange = _colorRangeData[_colorOption.value()]; cmax = currentColorRange.y; cmin = currentColorRange.x; } if (_isColorMapExact) { int colorIndex = static_cast<int>(variableColor + cmin); for (int j = 0; j < 4; ++j) { result.push_back(_colorMap.entries[colorIndex][j]); } } else { if (_useLinearFiltering) { float valueT = (variableColor - cmin) / (cmax - cmin); // in [0, 1) valueT = std::clamp(valueT, 0.f, 1.f); const float idx = valueT * (_colorMap.entries.size() - 1); const int floorIdx = static_cast<int>(std::floor(idx)); const int ceilIdx = static_cast<int>(std::ceil(idx)); const glm::vec4 floorColor = _colorMap.entries[floorIdx]; const glm::vec4 ceilColor = _colorMap.entries[ceilIdx]; if (floorColor != ceilColor) { const glm::vec4 c = floorColor + idx * (ceilColor - floorColor); result.push_back(c.r); result.push_back(c.g); result.push_back(c.b); result.push_back(c.a); } else { result.push_back(floorColor.r); result.push_back(floorColor.g); result.push_back(floorColor.b); result.push_back(floorColor.a); } } else { float ncmap = static_cast<float>(_colorMap.entries.size()); float normalization = ((cmax != cmin) && (ncmap > 2.f)) ? (ncmap - 2.f) / (cmax - cmin) : 0; int colorIndex = static_cast<int>( (variableColor - cmin) * normalization + 1.f ); colorIndex = colorIndex < 0 ? 0 : colorIndex; colorIndex = colorIndex >= ncmap ? static_cast<int>(ncmap - 1.f) : colorIndex; for (int j = 0; j < 4; ++j) { result.push_back(_colorMap.entries[colorIndex][j]); } } } if (_hasDatavarSize) { result.push_back(e.data[sizeScalingInUse]); } } else if (_hasDatavarSize) { result.push_back(e.data[sizeScalingInUse]); for (int j = 0; j < 4; ++j) { result.push_back(position[j]); } } else { for (int j = 0; j < 4; ++j) { result.push_back(position[j]); } } } setBoundingSphere(maxRadius); _fadeInDistances.setMaxValue(glm::vec2(10.f * biggestCoord)); return result; } void RenderableBillboardsCloud::createPolygonTexture() { ZoneScoped LDEBUG("Creating Polygon Texture"); glGenTextures(1, &_pTexture); glBindTexture(GL_TEXTURE_2D, _pTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, 256, 0, GL_RGBA, GL_BYTE, nullptr); renderToTexture(_pTexture, 256, 256); } void RenderableBillboardsCloud::renderToTexture(GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight) { LDEBUG("Rendering to Texture"); // Saves initial Application's OpenGL State GLint defaultFBO; GLint viewport[4]; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); glGetIntegerv(GL_VIEWPORT, viewport); GLuint textureFBO; glGenFramebuffers(1, &textureFBO); glBindFramebuffer(GL_FRAMEBUFFER, textureFBO); GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, drawBuffers); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureToRenderTo, 0); glViewport(viewport[0], viewport[1], textureWidth, textureHeight); loadPolygonGeometryForRendering(); renderPolygonGeometry(_polygonVao); // Restores Applications' OpenGL State glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); glDeleteBuffers(1, &_polygonVbo); glDeleteVertexArrays(1, &_polygonVao); glDeleteFramebuffers(1, &textureFBO); } void RenderableBillboardsCloud::loadPolygonGeometryForRendering() { glGenVertexArrays(1, &_polygonVao); glGenBuffers(1, &_polygonVbo); glBindVertexArray(_polygonVao); glBindBuffer(GL_ARRAY_BUFFER, _polygonVbo); constexpr const std::array<GLfloat, 4> VertexData = { // x y z w 0.f, 0.f, 0.f, 1.f, }; glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(0); glBindVertexArray(0); } void RenderableBillboardsCloud::renderPolygonGeometry(GLuint vao) { std::unique_ptr<ghoul::opengl::ProgramObject> program = ghoul::opengl::ProgramObject::Build( "RenderableBillboardsCloud_Polygon", absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_fs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_gs.glsl") ); program->activate(); constexpr const glm::vec4 Black = glm::vec4(0.f, 0.f, 0.f, 0.f); glClearBufferfv(GL_COLOR, 0, glm::value_ptr(Black)); program->setUniform("sides", _polygonSides); program->setUniform("polygonColor", _pointColor); glBindVertexArray(vao); glDrawArrays(GL_POINTS, 0, 1); glBindVertexArray(0); program->deactivate(); } } // namespace openspace
#include <algorithm> #include <random> #include <iostream> #include <vector> #include <iterator> #include <numeric> #include <string> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" #include <boost/test/unit_test.hpp> #pragma GCC diagnostic pop #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <boost/algorithm/string/predicate.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/account_object.hpp> #include <eosio/chain/contract_table_objects.hpp> #include <eosio/chain/block_summary_object.hpp> #include <eosio/chain/global_property_object.hpp> #include <eosio/chain/generated_transaction_object.hpp> #include <eosio/chain/resource_limits.hpp> #include <fc/crypto/digest.hpp> #include <fc/exception/exception.hpp> #include <fc/variant_object.hpp> #include <Inline/BasicTypes.h> #include <Runtime/Runtime.h> #include <contracts.hpp> #define DUMMY_ACTION_DEFAULT_A 0x45 #define DUMMY_ACTION_DEFAULT_B 0xab11cd1244556677 #define DUMMY_ACTION_DEFAULT_C 0x7451ae12 static constexpr unsigned int DJBH(const char* cp) { unsigned int hash = 5381; while (*cp) hash = 33 * hash ^ (unsigned char) *cp++; return hash; } static constexpr unsigned long long WASM_TEST_ACTION(const char* cls, const char* method) { return static_cast<unsigned long long>(DJBH(cls)) << 32 | static_cast<unsigned long long>(DJBH(method)); } struct dummy_action { static eosio::chain::name get_name() { return N(dummyaction); } static eosio::chain::name get_account() { return N(testapi); } char a; //1 uint64_t b; //8 int32_t c; //4 }; struct u128_action { unsigned __int128 values[3]; //16*3 }; struct cf_action { static eosio::chain::name get_name() { return N(cfaction); } static eosio::chain::name get_account() { return N(testapi); } uint32_t payload = 100; uint32_t cfd_idx = 0; // context free data index }; // Deferred Transaction Trigger Action struct dtt_action { static uint64_t get_name() { return WASM_TEST_ACTION("test_transaction", "send_deferred_tx_with_dtt_action"); } static uint64_t get_account() { return N(testapi).to_uint64_t(); } uint64_t payer = N(testapi).to_uint64_t(); uint64_t deferred_account = N(testapi).to_uint64_t(); uint64_t deferred_action = WASM_TEST_ACTION("test_transaction", "deferred_print"); uint64_t permission_name = N(active).to_uint64_t(); uint32_t delay_sec = 2; }; struct invalid_access_action { uint64_t code; uint64_t val; uint32_t index; bool store; }; FC_REFLECT( dummy_action, (a)(b)(c) ) FC_REFLECT( u128_action, (values) ) FC_REFLECT( cf_action, (payload)(cfd_idx) ) FC_REFLECT( dtt_action, (payer)(deferred_account)(deferred_action)(permission_name)(delay_sec) ) FC_REFLECT( invalid_access_action, (code)(val)(index)(store) ) #ifdef NON_VALIDATING_TEST #define TESTER tester #else #define TESTER validating_tester #endif using namespace eosio; using namespace eosio::testing; using namespace chain; using namespace fc; namespace bio = boost::iostreams; template<uint64_t NAME> struct test_api_action { static account_name get_account() { return N(testapi); } static action_name get_name() { return action_name(NAME); } }; FC_REFLECT_TEMPLATE((uint64_t T), test_api_action<T>, BOOST_PP_SEQ_NIL) template<uint64_t NAME> struct test_chain_action { static account_name get_account() { return account_name(config::system_account_name); } static action_name get_name() { return action_name(NAME); } }; FC_REFLECT_TEMPLATE((uint64_t T), test_chain_action<T>, BOOST_PP_SEQ_NIL) struct check_auth { account_name account; permission_name permission; vector<public_key_type> pubkeys; }; FC_REFLECT(check_auth, (account)(permission)(pubkeys) ) struct test_permission_last_used_action { account_name account; permission_name permission; fc::time_point last_used_time; }; FC_REFLECT( test_permission_last_used_action, (account)(permission)(last_used_time) ) constexpr uint64_t TEST_METHOD(const char* CLASS, const char *METHOD) { return ( (uint64_t(DJBH(CLASS))<<32) | uint32_t(DJBH(METHOD)) ); } string I64Str(int64_t i) { std::stringstream ss; ss << i; return ss.str(); } string U64Str(uint64_t i) { std::stringstream ss; ss << i; return ss.str(); } string U128Str(unsigned __int128 i) { return fc::variant(fc::uint128_t(i)).get_string(); } template <typename T> transaction_trace_ptr CallAction(TESTER& test, T ac, const vector<account_name>& scope = {N(testapi)}) { signed_transaction trx; auto pl = vector<permission_level>{{scope[0], config::active_name}}; if (scope.size() > 1) for (size_t i = 1; i < scope.size(); i++) pl.push_back({scope[i], config::active_name}); action act(pl, ac); trx.actions.push_back(act); test.set_transaction_headers(trx); auto sigs = trx.sign(test.get_private_key(scope[0], "active"), test.control->get_chain_id()); flat_set<public_key_type> keys; trx.get_signature_keys(test.control->get_chain_id(), fc::time_point::maximum(), keys); auto res = test.push_transaction(trx); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); test.produce_block(); return res; } template <typename T> transaction_trace_ptr CallFunction(TESTER& test, T ac, const vector<char>& data, const vector<account_name>& scope = {N(testapi)}, bool no_throw = false) { { signed_transaction trx; auto pl = vector<permission_level>{{scope[0], config::active_name}}; if (scope.size() > 1) for (unsigned int i=1; i < scope.size(); i++) pl.push_back({scope[i], config::active_name}); action act(pl, ac); act.data = data; act.authorization = {{N(testapi), config::active_name}}; trx.actions.push_back(act); test.set_transaction_headers(trx, test.DEFAULT_EXPIRATION_DELTA); auto sigs = trx.sign(test.get_private_key(scope[0], "active"), test.control->get_chain_id()); flat_set<public_key_type> keys; trx.get_signature_keys(test.control->get_chain_id(), fc::time_point::maximum(), keys); auto res = test.push_transaction(trx, fc::time_point::maximum(), TESTER::DEFAULT_BILLED_CPU_TIME_US, no_throw); if (!no_throw) { BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); } test.produce_block(); return res; } } #define CALL_TEST_FUNCTION(_TESTER, CLS, MTH, DATA) CallFunction(_TESTER, test_api_action<TEST_METHOD(CLS, MTH)>{}, DATA) #define CALL_TEST_FUNCTION_SYSTEM(_TESTER, CLS, MTH, DATA) CallFunction(_TESTER, test_chain_action<TEST_METHOD(CLS, MTH)>{}, DATA, {config::system_account_name} ) #define CALL_TEST_FUNCTION_SCOPE(_TESTER, CLS, MTH, DATA, ACCOUNT) CallFunction(_TESTER, test_api_action<TEST_METHOD(CLS, MTH)>{}, DATA, ACCOUNT) #define CALL_TEST_FUNCTION_NO_THROW(_TESTER, CLS, MTH, DATA) CallFunction(_TESTER, test_api_action<TEST_METHOD(CLS, MTH)>{}, DATA, {N(testapi)}, true) #define CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION(_TESTER, CLS, MTH, DATA, EXC, EXC_MESSAGE) \ BOOST_CHECK_EXCEPTION( \ CALL_TEST_FUNCTION( _TESTER, CLS, MTH, DATA), \ EXC, \ [](const EXC& e) { \ return expect_assert_message(e, EXC_MESSAGE); \ } \ ); bool is_access_violation(fc::unhandled_exception const & e) { try { std::rethrow_exception(e.get_inner_exception()); } catch (const eosio::chain::wasm_execution_error& e) { return true; } catch (...) { } return false; } bool is_access_violation(const Runtime::Exception& e) { return true; } bool is_assert_exception(fc::assert_exception const & e) { return true; } bool is_page_memory_error(page_memory_error const &e) { return true; } bool is_unsatisfied_authorization(unsatisfied_authorization const & e) { return true;} bool is_wasm_execution_error(eosio::chain::wasm_execution_error const& e) {return true;} bool is_tx_net_usage_exceeded(const tx_net_usage_exceeded& e) { return true; } bool is_block_net_usage_exceeded(const tx_cpu_usage_exceeded& e) { return true; } bool is_tx_cpu_usage_exceeded(const tx_cpu_usage_exceeded& e) { return true; } bool is_block_cpu_usage_exceeded(const tx_cpu_usage_exceeded& e) { return true; } bool is_deadline_exception(const deadline_exception& e) { return true; } /* * register test suite `api_tests` */ BOOST_AUTO_TEST_SUITE(api_tests) /* * Print capturing stuff */ std::vector<std::string> capture; struct MySink : public bio::sink { std::streamsize write(const char* s, std::streamsize n) { std::string tmp; tmp.assign(s, n); capture.push_back(tmp); std::cout << "stream : [" << tmp << "]" << std::endl; return n; } }; uint32_t last_fnc_err = 0; BOOST_FIXTURE_TEST_CASE(action_receipt_tests, TESTER) { try { produce_blocks(2); create_account( N(test) ); set_code( N(test), contracts::payloadless_wasm() ); produce_blocks(1); auto call_doit_and_check = [&]( account_name contract, account_name signer, auto&& checker ) { signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{signer, config::active_name}}, contract, N(doit), bytes{} ); this->set_transaction_headers( trx, this->DEFAULT_EXPIRATION_DELTA ); trx.sign( this->get_private_key(signer, "active"), control->get_chain_id() ); auto res = this->push_transaction(trx); checker( res ); }; auto call_provereset_and_check = [&]( account_name contract, account_name signer, auto&& checker ) { signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{signer, config::active_name}}, contract, N(provereset), bytes{} ); this->set_transaction_headers( trx, this->DEFAULT_EXPIRATION_DELTA ); trx.sign( this->get_private_key(signer, "active"), control->get_chain_id() ); auto res = this->push_transaction(trx); checker( res ); }; auto result = push_reqauth( config::system_account_name, "active" ); BOOST_REQUIRE_EQUAL( result->receipt->status, transaction_receipt::executed ); BOOST_REQUIRE( result->action_traces[0].receipt->auth_sequence.find( config::system_account_name ) != result->action_traces[0].receipt->auth_sequence.end() ); auto base_global_sequence_num = result->action_traces[0].receipt->global_sequence; auto base_system_recv_seq_num = result->action_traces[0].receipt->recv_sequence; auto base_system_auth_seq_num = result->action_traces[0].receipt->auth_sequence[config::system_account_name]; auto base_system_code_seq_num = result->action_traces[0].receipt->code_sequence.value; auto base_system_abi_seq_num = result->action_traces[0].receipt->abi_sequence.value; uint64_t base_test_recv_seq_num = 0; uint64_t base_test_auth_seq_num = 0; call_doit_and_check( N(test), N(test), [&]( const transaction_trace_ptr& res ) { BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->global_sequence, base_global_sequence_num + 1 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->code_sequence.value, 1 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->abi_sequence.value, 0 ); base_test_recv_seq_num = res->action_traces[0].receipt->recv_sequence; BOOST_CHECK( base_test_recv_seq_num > 0 ); base_test_recv_seq_num--; const auto& m = res->action_traces[0].receipt->auth_sequence; BOOST_CHECK_EQUAL( m.size(), 1 ); BOOST_CHECK_EQUAL( m.begin()->first.to_string(), "test" ); base_test_auth_seq_num = m.begin()->second; BOOST_CHECK( base_test_auth_seq_num > 0 ); --base_test_auth_seq_num; } ); set_code( N(test), contracts::asserter_wasm() ); set_code( config::system_account_name, contracts::payloadless_wasm() ); call_provereset_and_check( N(test), N(test), [&]( const transaction_trace_ptr& res ) { BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->global_sequence, base_global_sequence_num + 4 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->recv_sequence, base_test_recv_seq_num + 2 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->code_sequence.value, 2 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->abi_sequence.value, 0 ); const auto& m = res->action_traces[0].receipt->auth_sequence; BOOST_CHECK_EQUAL( m.size(), 1 ); BOOST_CHECK_EQUAL( m.begin()->first.to_string(), "test" ); BOOST_CHECK_EQUAL( m.begin()->second, base_test_auth_seq_num + 3 ); } ); produce_blocks(1); // Added to avoid the last doit transaction from being considered a duplicate. // Adding a block also retires an onblock action which increments both the global sequence number // and the recv and auth sequences numbers for the system account. call_doit_and_check( config::system_account_name, N(test), [&]( const transaction_trace_ptr& res ) { BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->global_sequence, base_global_sequence_num + 6 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->recv_sequence, base_system_recv_seq_num + 4 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->code_sequence.value, base_system_code_seq_num + 1 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->abi_sequence.value, base_system_abi_seq_num ); const auto& m = res->action_traces[0].receipt->auth_sequence; BOOST_CHECK_EQUAL( m.size(), 1 ); BOOST_CHECK_EQUAL( m.begin()->first.to_string(), "test" ); BOOST_CHECK_EQUAL( m.begin()->second, base_test_auth_seq_num + 4 ); } ); set_code( config::system_account_name, contracts::eosio_bios_wasm() ); set_code( N(test), contracts::eosio_bios_wasm() ); set_abi( N(test), contracts::eosio_bios_abi().data() ); set_code( N(test), contracts::payloadless_wasm() ); call_doit_and_check( N(test), N(test), [&]( const transaction_trace_ptr& res ) { BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->global_sequence, base_global_sequence_num + 11 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->recv_sequence, base_test_recv_seq_num + 3 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->code_sequence.value, 4 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->abi_sequence.value, 1 ); const auto& m = res->action_traces[0].receipt->auth_sequence; BOOST_CHECK_EQUAL( m.size(), 1 ); BOOST_CHECK_EQUAL( m.begin()->first.to_string(), "test" ); BOOST_CHECK_EQUAL( m.begin()->second, base_test_auth_seq_num + 8 ); } ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * action_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(acc1) ); create_account( N(acc2) ); create_account( N(acc3) ); create_account( N(acc4) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); // test assert_true CALL_TEST_FUNCTION( *this, "test_action", "assert_true", {}); //test assert_false BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_action", "assert_false", {} ), eosio_assert_message_exception, eosio_assert_message_is("test_action::assert_false") ); // test read_action_normal dummy_action dummy13{DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C}; CALL_TEST_FUNCTION( *this, "test_action", "read_action_normal", fc::raw::pack(dummy13)); // test read_action_to_0 std::vector<char> raw_bytes((1<<16)); CALL_TEST_FUNCTION( *this, "test_action", "read_action_to_0", raw_bytes ); // test read_action_to_0 raw_bytes.resize((1<<16)+1); BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "read_action_to_0", raw_bytes), eosio::chain::wasm_execution_error, [](const eosio::chain::wasm_execution_error& e) { return expect_assert_message(e, "access violation"); } ); // test read_action_to_64k raw_bytes.resize(1); CALL_TEST_FUNCTION( *this, "test_action", "read_action_to_64k", raw_bytes ); // test read_action_to_64k raw_bytes.resize(3); BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "read_action_to_64k", raw_bytes ), eosio::chain::wasm_execution_error, [](const eosio::chain::wasm_execution_error& e) { return expect_assert_message(e, "access violation"); } ); // test require_notice auto scope = std::vector<account_name>{N(testapi)}; auto test_require_notice = [this](auto& test, std::vector<char>& data, std::vector<account_name>& scope){ signed_transaction trx; auto tm = test_api_action<TEST_METHOD("test_action", "require_notice")>{}; action act(std::vector<permission_level>{{N(testapi), config::active_name}}, tm); vector<char>& dest = *(vector<char> *)(&act.data); std::copy(data.begin(), data.end(), std::back_inserter(dest)); trx.actions.push_back(act); test.set_transaction_headers(trx); trx.sign(test.get_private_key(N(inita), "active"), control->get_chain_id()); auto res = test.push_transaction(trx); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); }; BOOST_CHECK_EXCEPTION(test_require_notice(*this, raw_bytes, scope), unsatisfied_authorization, [](const unsatisfied_authorization& e) { return expect_assert_message(e, "transaction declares authority"); } ); // test require_auth BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "require_auth", {}), missing_auth_exception, [](const missing_auth_exception& e) { return expect_assert_message(e, "missing authority of"); } ); // test require_auth auto a3only = std::vector<permission_level>{{N(acc3), config::active_name}}; BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "require_auth", fc::raw::pack(a3only)), missing_auth_exception, [](const missing_auth_exception& e) { return expect_assert_message(e, "missing authority of"); } ); // test require_auth auto a4only = std::vector<permission_level>{{N(acc4), config::active_name}}; BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "require_auth", fc::raw::pack(a4only)), missing_auth_exception, [](const missing_auth_exception& e) { return expect_assert_message(e, "missing authority of"); } ); // test require_auth auto a3a4 = std::vector<permission_level>{{N(acc3), config::active_name}, {N(acc4), config::active_name}}; auto a3a4_scope = std::vector<account_name>{N(acc3), N(acc4)}; { signed_transaction trx; auto tm = test_api_action<TEST_METHOD("test_action", "require_auth")>{}; auto pl = a3a4; if (a3a4_scope.size() > 1) for (unsigned int i=1; i < a3a4_scope.size(); i++) pl.push_back({a3a4_scope[i], config::active_name}); action act(pl, tm); auto dat = fc::raw::pack(a3a4); vector<char>& dest = *(vector<char> *)(&act.data); std::copy(dat.begin(), dat.end(), std::back_inserter(dest)); act.authorization = {{N(testapi), config::active_name}, {N(acc3), config::active_name}, {N(acc4), config::active_name}}; trx.actions.push_back(act); set_transaction_headers(trx); trx.sign(get_private_key(N(testapi), "active"), control->get_chain_id()); trx.sign(get_private_key(N(acc3), "active"), control->get_chain_id()); trx.sign(get_private_key(N(acc4), "active"), control->get_chain_id()); auto res = push_transaction(trx); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); } uint64_t now = static_cast<uint64_t>( control->head_block_time().time_since_epoch().count() ); now += config::block_interval_us; CALL_TEST_FUNCTION( *this, "test_action", "test_current_time", fc::raw::pack(now)); // test current_time produce_block(); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_action", "test_current_time", fc::raw::pack(now) ), eosio_assert_message_exception, eosio_assert_message_is("tmp == current_time()") ); // test test_current_receiver CALL_TEST_FUNCTION( *this, "test_action", "test_current_receiver", fc::raw::pack(N(testapi))); // test send_action_sender CALL_TEST_FUNCTION( *this, "test_transaction", "send_action_sender", fc::raw::pack(N(testapi))); produce_block(); // test_publication_time uint64_t pub_time = static_cast<uint64_t>( control->head_block_time().time_since_epoch().count() ); pub_time += config::block_interval_us; CALL_TEST_FUNCTION( *this, "test_action", "test_publication_time", fc::raw::pack(pub_time) ); // test test_abort BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "test_abort", {} ), abort_called, [](const fc::exception& e) { return expect_assert_message(e, "abort() called"); } ); dummy_action da = { DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C }; CallAction(*this, da); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } // test require_recipient loop (doesn't cause infinite loop) BOOST_FIXTURE_TEST_CASE(require_notice_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(acc5) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); set_code( N(acc5), contracts::test_api_wasm() ); produce_blocks(1); // test require_notice signed_transaction trx; auto tm = test_api_action<TEST_METHOD( "test_action", "require_notice_tests" )>{}; action act( std::vector<permission_level>{{N( testapi ), config::active_name}}, tm ); trx.actions.push_back( act ); set_transaction_headers( trx ); trx.sign( get_private_key( N( testapi ), "active" ), control->get_chain_id() ); auto res = push_transaction( trx ); BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(ram_billing_in_notify_tests) { try { fc::temp_directory tempdir; validating_tester chain( tempdir, true ); chain.execute_setup_policy( setup_policy::preactivate_feature_and_new_bios ); const auto& pfm = chain.control->get_protocol_feature_manager(); const auto& d = pfm.get_builtin_digest(builtin_protocol_feature_t::action_return_value); // testapi requires this BOOST_REQUIRE(d); chain.preactivate_protocol_features( {*d} ); chain.produce_blocks(2); chain.create_account( N(testapi) ); chain.create_account( N(testapi2) ); chain.produce_blocks(10); chain.set_code( N(testapi), contracts::test_api_wasm() ); chain.produce_blocks(1); chain.set_code( N(testapi2), contracts::test_api_wasm() ); chain.produce_blocks(1); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( chain, "test_action", "test_ram_billing_in_notify", fc::raw::pack( ((unsigned __int128)N(testapi2).to_uint64_t() << 64) | N(testapi).to_uint64_t() ) ), subjective_block_production_exception, fc_exception_message_is("Cannot charge RAM to other accounts during notify.") ); CALL_TEST_FUNCTION( chain, "test_action", "test_ram_billing_in_notify", fc::raw::pack( ((unsigned __int128)N(testapi2).to_uint64_t() << 64) | 0 ) ); CALL_TEST_FUNCTION( chain, "test_action", "test_ram_billing_in_notify", fc::raw::pack( ((unsigned __int128)N(testapi2).to_uint64_t() << 64) | N(testapi2).to_uint64_t() ) ); BOOST_REQUIRE_EQUAL( chain.validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * context free action tests *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(cf_action_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(dummy) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); cf_action cfa; signed_transaction trx; set_transaction_headers(trx); // need at least one normal action BOOST_CHECK_EXCEPTION(push_transaction(trx), tx_no_auths, [](const fc::assert_exception& e) { return expect_assert_message(e, "transaction must have at least one authorization"); } ); action act({}, cfa); trx.context_free_actions.push_back(act); trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(100)); // verify payload matches context free data trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(200)); set_transaction_headers(trx); BOOST_CHECK_EXCEPTION(push_transaction(trx), tx_no_auths, [](const fc::exception& e) { return expect_assert_message(e, "transaction must have at least one authorization"); } ); trx.signatures.clear(); // add a normal action along with cfa dummy_action da = { DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C }; auto pl = vector<permission_level>{{N(testapi), config::active_name}}; action act1(pl, da); trx.actions.push_back(act1); set_transaction_headers(trx); // run normal passing case auto sigs = trx.sign(get_private_key(N(testapi), "active"), control->get_chain_id()); auto res = push_transaction(trx); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); // attempt to access context free api in non context free action da = { DUMMY_ACTION_DEFAULT_A, 200, DUMMY_ACTION_DEFAULT_C }; action act2(pl, da); trx.signatures.clear(); trx.actions.clear(); trx.actions.push_back(act2); set_transaction_headers(trx); // run (dummy_action.b = 200) case looking for invalid use of context_free api sigs = trx.sign(get_private_key(N(testapi), "active"), control->get_chain_id()); BOOST_CHECK_EXCEPTION(push_transaction(trx), unaccessible_api, [](const fc::exception& e) { return expect_assert_message(e, "this API may only be called from context_free apply"); } ); { // back to normal action action act1(pl, da); signed_transaction trx; trx.context_free_actions.push_back(act); trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(100)); // verify payload matches context free data trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(200)); trx.actions.push_back(act1); // attempt to access non context free api for (uint32_t i = 200; i <= 212; ++i) { trx.context_free_actions.clear(); trx.context_free_data.clear(); cfa.payload = i; cfa.cfd_idx = 1; action cfa_act({}, cfa); trx.context_free_actions.emplace_back(cfa_act); trx.signatures.clear(); set_transaction_headers(trx); sigs = trx.sign(get_private_key(N(testapi), "active"), control->get_chain_id()); BOOST_CHECK_EXCEPTION(push_transaction(trx), unaccessible_api, [](const fc::exception& e) { return expect_assert_message(e, "only context free api's can be used in this context" ); } ); } } produce_block(); // test send context free action auto ttrace = CALL_TEST_FUNCTION( *this, "test_transaction", "send_cf_action", {} ); BOOST_REQUIRE_EQUAL(ttrace->action_traces.size(), 2); BOOST_CHECK_EQUAL((int)(ttrace->action_traces[1].creator_action_ordinal), 1); BOOST_CHECK_EQUAL(ttrace->action_traces[1].receiver, account_name("dummy")); BOOST_CHECK_EQUAL(ttrace->action_traces[1].act.account, account_name("dummy")); BOOST_CHECK_EQUAL(ttrace->action_traces[1].act.name, account_name("event1")); BOOST_CHECK_EQUAL(ttrace->action_traces[1].act.authorization.size(), 0); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_transaction", "send_cf_action_fail", {} ), eosio_assert_message_exception, eosio_assert_message_is("context free actions cannot have authorizations") ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(cfa_tx_signature, TESTER) try { action cfa({}, cf_action()); signed_transaction tx1; tx1.context_free_data.emplace_back(fc::raw::pack<uint32_t>(100)); tx1.context_free_actions.push_back(cfa); set_transaction_headers(tx1); signed_transaction tx2; tx2.context_free_data.emplace_back(fc::raw::pack<uint32_t>(200)); tx2.context_free_actions.push_back(cfa); set_transaction_headers(tx2); const private_key_type& priv_key = get_private_key(name("dummy"), "active"); BOOST_TEST(tx1.sign(priv_key, control->get_chain_id()).to_string() != tx2.sign(priv_key, control->get_chain_id()).to_string()); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE(cfa_stateful_api, TESTER) try { create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); account_name a = N(testapi2); account_name creator = config::system_account_name; signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{creator,config::active_name}}, newaccount{ .creator = creator, .name = a, .owner = authority( get_public_key( a, "owner" ) ), .active = authority( get_public_key( a, "active" ) ) }); action act({}, test_api_action<TEST_METHOD("test_transaction", "stateful_api")>{}); trx.context_free_actions.push_back(act); set_transaction_headers(trx); trx.sign( get_private_key( creator, "active" ), control->get_chain_id() ); BOOST_CHECK_EXCEPTION(push_transaction( trx ), fc::exception, [&](const fc::exception &e) { return expect_assert_message(e, "only context free api's can be used in this context"); }); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE(deferred_cfa_failed, TESTER) try { create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); account_name a = N(testapi2); account_name creator = config::system_account_name; signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{creator,config::active_name}}, newaccount{ .creator = creator, .name = a, .owner = authority( get_public_key( a, "owner" ) ), .active = authority( get_public_key( a, "active" ) ) }); action act({}, test_api_action<TEST_METHOD("test_transaction", "stateful_api")>{}); trx.context_free_actions.push_back(act); set_transaction_headers(trx, 10, 2); trx.sign( get_private_key( creator, "active" ), control->get_chain_id() ); BOOST_CHECK_EXCEPTION(push_transaction( trx ), fc::exception, [&](const fc::exception &e) { return expect_assert_message(e, "only context free api's can be used in this context"); }); produce_blocks(10); // CFA failed, testapi2 not created create_account( N(testapi2) ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE(deferred_cfa_success, TESTER) try { create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); account_name a = N(testapi2); account_name creator = config::system_account_name; signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{creator,config::active_name}}, newaccount{ .creator = creator, .name = a, .owner = authority( get_public_key( a, "owner" ) ), .active = authority( get_public_key( a, "active" ) ) }); action act({}, test_api_action<TEST_METHOD("test_transaction", "context_free_api")>{}); trx.context_free_actions.push_back(act); set_transaction_headers(trx, 10, 2); trx.sign( get_private_key( creator, "active" ), control->get_chain_id() ); auto trace = push_transaction( trx ); BOOST_REQUIRE(trace != nullptr); if (trace) { BOOST_REQUIRE_EQUAL(transaction_receipt_header::status_enum::delayed, trace->receipt->status); BOOST_REQUIRE_EQUAL(1, trace->action_traces.size()); } produce_blocks(10); // CFA success, testapi2 created BOOST_CHECK_EXCEPTION(create_account( N(testapi2) ), fc::exception, [&](const fc::exception &e) { return expect_assert_message(e, "Cannot create account named testapi2, as that name is already taken"); }); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() BOOST_AUTO_TEST_CASE(light_validation_skip_cfa) try { tester chain(setup_policy::full); std::vector<signed_block_ptr> blocks; blocks.push_back(chain.produce_block()); chain.create_account( N(testapi) ); chain.create_account( N(dummy) ); blocks.push_back(chain.produce_block()); chain.set_code( N(testapi), contracts::test_api_wasm() ); blocks.push_back(chain.produce_block()); cf_action cfa; signed_transaction trx; action act({}, cfa); trx.context_free_actions.push_back(act); trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(100)); // verify payload matches context free data trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(200)); // add a normal action along with cfa dummy_action da = { DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C }; action act1(vector<permission_level>{{N(testapi), config::active_name}}, da); trx.actions.push_back(act1); chain.set_transaction_headers(trx); // run normal passing case auto sigs = trx.sign(chain.get_private_key(N(testapi), "active"), chain.control->get_chain_id()); auto trace = chain.push_transaction(trx); blocks.push_back(chain.produce_block()); BOOST_REQUIRE(trace->receipt); BOOST_CHECK_EQUAL(trace->receipt->status, transaction_receipt::executed); BOOST_CHECK_EQUAL(2, trace->action_traces.size()); BOOST_CHECK(trace->action_traces.at(0).context_free); // cfa BOOST_CHECK_EQUAL("test\n", trace->action_traces.at(0).console); // cfa executed BOOST_CHECK(!trace->action_traces.at(1).context_free); // non-cfa BOOST_CHECK_EQUAL("", trace->action_traces.at(1).console); fc::temp_directory tempdir; auto conf_genesis = tester::default_config( tempdir ); auto& cfg = conf_genesis.first; cfg.trusted_producers = { N(eosio) }; // light validation tester other( conf_genesis.first, conf_genesis.second ); other.execute_setup_policy( setup_policy::full ); transaction_trace_ptr other_trace; auto cc = other.control->applied_transaction.connect( [&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if( t && t->id == trace->id ) { other_trace = t; } } ); for (auto& new_block : blocks) { other.push_block(new_block); } blocks.clear(); BOOST_REQUIRE(other_trace); BOOST_REQUIRE(other_trace->receipt); BOOST_CHECK_EQUAL(other_trace->receipt->status, transaction_receipt::executed); BOOST_CHECK(*trace->receipt == *other_trace->receipt); BOOST_CHECK_EQUAL(2, other_trace->action_traces.size()); BOOST_CHECK(other_trace->action_traces.at(0).context_free); // cfa BOOST_CHECK_EQUAL("", other_trace->action_traces.at(0).console); // cfa not executed for light validation (trusted producer) BOOST_CHECK_EQUAL(trace->action_traces.at(0).receipt->global_sequence, other_trace->action_traces.at(0).receipt->global_sequence); BOOST_CHECK_EQUAL(trace->action_traces.at(0).receipt->digest(), other_trace->action_traces.at(0).receipt->digest()); BOOST_CHECK(!other_trace->action_traces.at(1).context_free); // non-cfa BOOST_CHECK_EQUAL("", other_trace->action_traces.at(1).console); BOOST_CHECK_EQUAL(trace->action_traces.at(1).receipt->global_sequence, other_trace->action_traces.at(1).receipt->global_sequence); BOOST_CHECK_EQUAL(trace->action_traces.at(1).receipt->digest(), other_trace->action_traces.at(1).receipt->digest()); other.close(); } FC_LOG_AND_RETHROW() /************************************************************************************* * checktime_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(checktime_pass_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); // test checktime_pass CALL_TEST_FUNCTION( *this, "test_checktime", "checktime_pass", {}); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } template<class T> void call_test(TESTER& test, T ac, uint32_t billed_cpu_time_us , uint32_t max_cpu_usage_ms = 200, std::vector<char> payload = {} ) { signed_transaction trx; auto pl = vector<permission_level>{{N(testapi), config::active_name}}; action act(pl, ac); act.data = payload; trx.actions.push_back(act); test.set_transaction_headers(trx); auto sigs = trx.sign(test.get_private_key(N(testapi), "active"), test.control->get_chain_id()); flat_set<public_key_type> keys; trx.get_signature_keys(test.control->get_chain_id(), fc::time_point::maximum(), keys); auto res = test.push_transaction( trx, fc::time_point::now() + fc::milliseconds(max_cpu_usage_ms), billed_cpu_time_us ); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); test.produce_block(); }; BOOST_AUTO_TEST_CASE(checktime_fail_tests) { try { TESTER t; t.produce_blocks(2); ilog( "create account" ); t.create_account( N(testapi) ); ilog( "set code" ); t.set_code( N(testapi), contracts::test_api_wasm() ); ilog( "produce block" ); t.produce_blocks(1); int64_t x; int64_t net; int64_t cpu; t.control->get_resource_limits_manager().get_account_limits( N(testapi), x, net, cpu ); wdump((net)(cpu)); #warning TODO call the contract before testing to cache it, and validate that it was cached BOOST_CHECK_EXCEPTION( call_test( t, test_api_action<TEST_METHOD("test_checktime", "checktime_failure")>{}, 5000, 200, fc::raw::pack(10000000000000000000ULL) ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( t, test_api_action<TEST_METHOD("test_checktime", "checktime_failure")>{}, 0, 200, fc::raw::pack(10000000000000000000ULL) ), tx_cpu_usage_exceeded, is_tx_cpu_usage_exceeded ); uint32_t time_left_in_block_us = config::default_max_block_cpu_usage - config::default_min_transaction_cpu_usage; std::string dummy_string = "nonce"; uint32_t increment = config::default_max_transaction_cpu_usage / 3; for( auto i = 0; time_left_in_block_us > 2*increment; ++i ) { t.push_dummy( N(testapi), dummy_string + std::to_string(i), increment ); time_left_in_block_us -= increment; } BOOST_CHECK_EXCEPTION( call_test( t, test_api_action<TEST_METHOD("test_checktime", "checktime_failure")>{}, 0, 200, fc::raw::pack(10000000000000000000ULL) ), block_cpu_usage_exceeded, is_block_cpu_usage_exceeded ); BOOST_REQUIRE_EQUAL( t.validate(), true ); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(checktime_intrinsic, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); produce_blocks(10); std::stringstream ss; ss << R"CONTRACT( (module (type $FUNCSIG$vij (func (param i32 i64))) (type $FUNCSIG$j (func (result i64))) (type $FUNCSIG$vjj (func (param i64 i64))) (type $FUNCSIG$vii (func (param i32 i32))) (type $FUNCSIG$i (func (result i32))) (type $FUNCSIG$iii (func (param i32 i32) (result i32))) (type $FUNCSIG$iiii (func (param i32 i32 i32) (result i32))) (type $FUNCSIG$vi (func (param i32))) (type $FUNCSIG$v (func )) (type $_1 (func (param i64 i64 i64))) (export "apply" (func $apply)) (import "env" "memmove" (func $memmove (param i32 i32 i32) (result i32))) (import "env" "printui" (func $printui (param i64))) (memory $0 1) (func $apply (type $_1) (param $0 i64) (param $1 i64) (param $2 i64) (drop (grow_memory (i32.const 527))) (call $printui (i64.const 11)) )CONTRACT"; for(unsigned int i = 0; i < 5000; ++i) { ss << R"CONTRACT( (drop (call $memmove (i32.const 1) (i32.const 9) (i32.const 33554432) )) )CONTRACT"; } ss<< "))"; set_code( N(testapi), ss.str().c_str() ); produce_blocks(1); //initialize cache BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("doesn't matter", "doesn't matter")>{}, 5000, 10 ), deadline_exception, is_deadline_exception ); #warning TODO validate that the contract was successfully cached //it will always call BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("doesn't matter", "doesn't matter")>{}, 5000, 10 ), deadline_exception, is_deadline_exception ); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(checktime_hashing_fail, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); //hit deadline exception, but cache the contract BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_sha1_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); #warning TODO validate that the contract was successfully cached //the contract should be cached, now we should get deadline_exception because of calls to checktime() from hashing function BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_sha1_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_assert_sha1_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_sha256_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_assert_sha256_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_sha512_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_assert_sha512_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_ripemd160_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_assert_ripemd160_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * transaction_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(transaction_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); produce_blocks(100); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); // test for zero auth { signed_transaction trx; auto tm = test_api_action<TEST_METHOD("test_action", "require_auth")>{}; action act({}, tm); trx.actions.push_back(act); set_transaction_headers(trx); BOOST_CHECK_EXCEPTION(push_transaction(trx), transaction_exception, [](const fc::exception& e) { return expect_assert_message(e, "transaction must have at least one authorization"); } ); } // test send_action CALL_TEST_FUNCTION(*this, "test_transaction", "send_action", {}); // test send_action_empty CALL_TEST_FUNCTION(*this, "test_transaction", "send_action_empty", {}); // test send_action_large BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION(*this, "test_transaction", "send_action_large", {}), inline_action_too_big, [](const fc::exception& e) { return expect_assert_message(e, "inline action too big"); } ); // test send_action_inline_fail BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION(*this, "test_transaction", "send_action_inline_fail", {}), eosio_assert_message_exception, eosio_assert_message_is("test_action::assert_false") ); // test send_transaction CALL_TEST_FUNCTION(*this, "test_transaction", "send_transaction", {}); // test send_transaction_empty BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION(*this, "test_transaction", "send_transaction_empty", {}), tx_no_auths, [](const fc::exception& e) { return expect_assert_message(e, "transaction must have at least one authorization"); } ); { produce_blocks(10); transaction_trace_ptr trace; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->receipt && t->receipt->status != transaction_receipt::executed) { trace = t; } } ); block_state_ptr bsp; auto c2 = control->accepted_block.connect([&](const block_state_ptr& b) { bsp = b; }); // test error handling on deferred transaction failure auto test_trace = CALL_TEST_FUNCTION(*this, "test_transaction", "send_transaction_trigger_error_handler", {}); BOOST_REQUIRE(trace); BOOST_CHECK_EQUAL(trace->receipt->status, transaction_receipt::soft_fail); std::set<transaction_id_type> block_ids; for( const auto& receipt : bsp->block->transactions ) { transaction_id_type id; if( receipt.trx.contains<packed_transaction>() ) { const auto& pt = receipt.trx.get<packed_transaction>(); id = pt.id(); } else { id = receipt.trx.get<transaction_id_type>(); } block_ids.insert( id ); } BOOST_CHECK_EQUAL(2, block_ids.size() ); // originating trx and deferred BOOST_CHECK_EQUAL(1, block_ids.count( test_trace->id ) ); // originating BOOST_CHECK( !test_trace->failed_dtrx_trace ); BOOST_CHECK_EQUAL(0, block_ids.count( trace->id ) ); // onerror id, not in block BOOST_CHECK_EQUAL(1, block_ids.count( trace->failed_dtrx_trace->id ) ); // deferred id since trace moved to failed_dtrx_trace BOOST_CHECK( trace->action_traces.at(0).act.name == N(onerror) ); c.disconnect(); c2.disconnect(); } // test test_transaction_size CALL_TEST_FUNCTION(*this, "test_transaction", "test_transaction_size", fc::raw::pack(54) ); // TODO: Need a better way to test this. // test test_read_transaction // this is a bit rough, but I couldn't figure out a better way to compare the hashes auto tx_trace = CALL_TEST_FUNCTION( *this, "test_transaction", "test_read_transaction", {} ); string sha_expect = tx_trace->id; BOOST_TEST_MESSAGE( "tx_trace->action_traces.front().console: = " << tx_trace->action_traces.front().console ); BOOST_TEST_MESSAGE( "sha_expect = " << sha_expect ); BOOST_CHECK_EQUAL(tx_trace->action_traces.front().console == sha_expect, true); // test test_tapos_block_num CALL_TEST_FUNCTION(*this, "test_transaction", "test_tapos_block_num", fc::raw::pack(control->head_block_num()) ); // test test_tapos_block_prefix CALL_TEST_FUNCTION(*this, "test_transaction", "test_tapos_block_prefix", fc::raw::pack(control->head_block_id()._hash[1]) ); // test send_action_recurse BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION(*this, "test_transaction", "send_action_recurse", {}), eosio::chain::transaction_exception, [](const eosio::chain::transaction_exception& e) { return expect_assert_message(e, "max inline action depth per transaction reached"); } ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(deferred_transaction_tests, TESTER) { try { produce_blocks(2); create_accounts( {N(testapi), N(testapi2), N(alice)} ); set_code( N(testapi), contracts::test_api_wasm() ); set_code( N(testapi2), contracts::test_api_wasm() ); produce_blocks(1); //schedule { transaction_trace_ptr trace; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t->scheduled) { trace = t; } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction", {} ); BOOST_CHECK(!trace); produce_block( fc::seconds(2) ); //check that it gets executed afterwards BOOST_REQUIRE(trace); //confirm printed message BOOST_TEST(!trace->action_traces.empty()); BOOST_TEST(trace->action_traces.back().console == "deferred executed\n"); c.disconnect(); } produce_blocks(10); //schedule twice without replace_existing flag (second deferred transaction should replace first one) { transaction_trace_ptr trace; uint32_t count = 0; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->scheduled) { trace = t; ++count; } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction", {}); BOOST_CHECK_THROW(CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction", {}), deferred_tx_duplicate); produce_blocks( 3 ); //check that only one deferred transaction executed auto dtrxs = get_scheduled_transactions(); BOOST_CHECK_EQUAL(dtrxs.size(), 1); for (const auto& trx: dtrxs) { control->push_scheduled_transaction(trx, fc::time_point::maximum(), 0, false); } BOOST_CHECK_EQUAL(1, count); BOOST_REQUIRE(trace); BOOST_CHECK_EQUAL( 1, trace->action_traces.size() ); c.disconnect(); } produce_blocks(10); //schedule twice with replace_existing flag (second deferred transaction should replace first one) { transaction_trace_ptr trace; uint32_t count = 0; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->scheduled) { trace = t; ++count; } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction_replace", {}); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction_replace", {}); produce_blocks( 3 ); //check that only one deferred transaction executed auto billed_cpu_time_us = control->get_global_properties().configuration.min_transaction_cpu_usage; auto dtrxs = get_scheduled_transactions(); BOOST_CHECK_EQUAL(dtrxs.size(), 1); for (const auto& trx: dtrxs) { control->push_scheduled_transaction(trx, fc::time_point::maximum(), billed_cpu_time_us, true); } BOOST_CHECK_EQUAL(1, count); BOOST_CHECK(trace); BOOST_CHECK_EQUAL( 1, trace->action_traces.size() ); c.disconnect(); } produce_blocks(10); //schedule and cancel { transaction_trace_ptr trace; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->scheduled) { trace = t; } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction", {}); CALL_TEST_FUNCTION(*this, "test_transaction", "cancel_deferred_transaction_success", {}); produce_block( fc::seconds(2) ); BOOST_CHECK(!trace); c.disconnect(); } produce_blocks(10); //cancel_deferred() return zero if no scheduled transaction found { CALL_TEST_FUNCTION(*this, "test_transaction", "cancel_deferred_transaction_not_found", {}); } produce_blocks(10); //repeated deferred transactions { vector<transaction_trace_ptr> traces; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->scheduled) { traces.push_back( t ); } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "repeat_deferred_transaction", fc::raw::pack( (uint32_t)5 ) ); produce_block(); c.disconnect(); BOOST_CHECK_EQUAL( traces.size(), 5 ); } produce_blocks(10); { // Trigger a tx which in turn sends a deferred tx with payer != receiver // Payer is alice in this case, this tx should fail since we don't have the authorization of alice dtt_action dtt_act1; dtt_act1.payer = N(alice).to_uint64_t(); BOOST_CHECK_THROW(CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act1)), action_validate_exception); // Send a tx which in turn sends a deferred tx with the deferred tx's receiver != this tx receiver // This will include the authorization of the receiver, and impose any related delay associated with the authority // We set the authorization delay to be 10 sec here, and since the deferred tx delay is set to be 5 sec, so this tx should fail dtt_action dtt_act2; dtt_act2.deferred_account = N(testapi2).to_uint64_t(); dtt_act2.permission_name = N(additional).to_uint64_t(); dtt_act2.delay_sec = 5; auto auth = authority(get_public_key(name("testapi"), name(dtt_act2.permission_name).to_string()), 10); auth.accounts.push_back( permission_level_weight{{N(testapi), config::eosio_code_name}, 1} ); push_action(config::system_account_name, updateauth::get_name(), name("testapi"), fc::mutable_variant_object() ("account", "testapi") ("permission", name(dtt_act2.permission_name)) ("parent", "active") ("auth", auth) ); push_action(config::system_account_name, linkauth::get_name(), name("testapi"), fc::mutable_variant_object() ("account", "testapi") ("code", name(dtt_act2.deferred_account)) ("type", name(dtt_act2.deferred_action)) ("requirement", name(dtt_act2.permission_name))); BOOST_CHECK_THROW(CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act2)), unsatisfied_authorization); // But if the deferred transaction has a sufficient delay, then it should work. dtt_act2.delay_sec = 10; CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act2)); // If the deferred tx receiver == this tx receiver, the authorization checking would originally be bypassed. // But not anymore. With the RESTRICT_ACTION_TO_SELF protocol feature activated, it should now objectively // fail because testapi@additional permission is not unilaterally satisfied by testapi@eosio.code. dtt_action dtt_act3; dtt_act3.deferred_account = N(testapi).to_uint64_t(); dtt_act3.permission_name = N(additional).to_uint64_t(); push_action(config::system_account_name, linkauth::get_name(), name("testapi"), fc::mutable_variant_object() ("account", "testapi") ("code", name(dtt_act3.deferred_account)) ("type", name(dtt_act3.deferred_action)) ("requirement", name(dtt_act3.permission_name))); BOOST_CHECK_THROW(CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act3)), unsatisfied_authorization); // But it should again work if the deferred transaction has a sufficient delay. dtt_act3.delay_sec = 10; CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act3)); // If we make testapi account to be priviledged account: // - the deferred transaction will work no matter who is the payer // - the deferred transaction will not care about the delay of the authorization push_action(config::system_account_name, N(setpriv), config::system_account_name, mutable_variant_object() ("account", "testapi") ("is_priv", 1)); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act1)); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act2)); } BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(more_deferred_transaction_tests) { try { fc::temp_directory tempdir; validating_tester chain( tempdir, true ); chain.execute_setup_policy( setup_policy::preactivate_feature_and_new_bios ); const auto& pfm = chain.control->get_protocol_feature_manager(); auto d = pfm.get_builtin_digest( builtin_protocol_feature_t::replace_deferred ); BOOST_REQUIRE( d ); chain.preactivate_protocol_features( {*d} ); chain.produce_block(); const auto& index = chain.control->db().get_index<generated_transaction_multi_index,by_id>(); auto print_deferred = [&index]() { for( const auto& gto : index ) { wlog("id = ${id}, trx_id = ${trx_id}", ("id", gto.id)("trx_id", gto.trx_id)); } }; const auto& contract_account = account_name("tester"); const auto& test_account = account_name("alice"); chain.create_accounts( {contract_account, test_account} ); chain.set_code( contract_account, contracts::deferred_test_wasm() ); chain.set_abi( contract_account, contracts::deferred_test_abi().data() ); chain.produce_block(); BOOST_REQUIRE_EQUAL(0, index.size()); chain.push_action( contract_account, N(delayedcall), test_account, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 0) ("contract", contract_account) ("payload", 42) ("delay_sec", 1000) ("replace_existing", false) ); BOOST_REQUIRE_EQUAL(1, index.size()); print_deferred(); signed_transaction trx; trx.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 0) ("contract", contract_account) ("payload", 13) ("delay_sec", 1000) ("replace_existing", true) ) ); trx.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 1) ("contract", contract_account) ("payload", 42) ("delay_sec", 1000) ("replace_existing", false) ) ); trx.actions.emplace_back( chain.get_action( contract_account, N(fail), vector<permission_level>{}, fc::mutable_variant_object() ) ); chain.set_transaction_headers(trx); trx.sign( chain.get_private_key( test_account, "active" ), chain.control->get_chain_id() ); BOOST_REQUIRE_EXCEPTION( chain.push_transaction( trx ), eosio_assert_message_exception, eosio_assert_message_is("fail") ); BOOST_REQUIRE_EQUAL(1, index.size()); print_deferred(); chain.produce_blocks(2); chain.push_action( contract_account, N(delayedcall), test_account, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 1) ("contract", contract_account) ("payload", 101) ("delay_sec", 1000) ("replace_existing", false) ); chain.push_action( contract_account, N(delayedcall), test_account, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 2) ("contract", contract_account) ("payload", 102) ("delay_sec", 1000) ("replace_existing", false) ); BOOST_REQUIRE_EQUAL(3, index.size()); print_deferred(); BOOST_REQUIRE_THROW( chain.push_action( contract_account, N(delayedcall), test_account, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 2) ("contract", contract_account) ("payload", 101) ("delay_sec", 1000) ("replace_existing", true) ), fc::exception ); BOOST_REQUIRE_EQUAL(3, index.size()); print_deferred(); signed_transaction trx2; trx2.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 1) ("contract", contract_account) ("payload", 100) ("delay_sec", 1000) ("replace_existing", true) ) ); trx2.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 2) ("contract", contract_account) ("payload", 101) ("delay_sec", 1000) ("replace_existing", true) ) ); trx2.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 1) ("contract", contract_account) ("payload", 102) ("delay_sec", 1000) ("replace_existing", true) ) ); trx2.actions.emplace_back( chain.get_action( contract_account, N(fail), vector<permission_level>{}, fc::mutable_variant_object() ) ); chain.set_transaction_headers(trx2); trx2.sign( chain.get_private_key( test_account, "active" ), chain.control->get_chain_id() ); BOOST_REQUIRE_EXCEPTION( chain.push_transaction( trx2 ), eosio_assert_message_exception, eosio_assert_message_is("fail") ); BOOST_REQUIRE_EQUAL(3, index.size()); print_deferred(); BOOST_REQUIRE_EQUAL( chain.validate(), true ); } FC_LOG_AND_RETHROW() } template <uint64_t NAME> struct setprod_act { static account_name get_account() { return N(config::system_account_name); } static action_name get_name() { return action_name(NAME); } }; /************************************************************************************* * chain_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(chain_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); vector<account_name> producers = { N(inita), N(initb), N(initc), N(initd), N(inite), N(initf), N(initg), N(inith), N(initi), N(initj), N(initk), N(initl), N(initm), N(initn), N(inito), N(initp), N(initq), N(initr), N(inits), N(initt), N(initu) }; create_accounts( producers ); set_producers (producers ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(100); vector<account_name> prods( control->active_producers().producers.size() ); for ( uint32_t i = 0; i < prods.size(); i++ ) { prods[i] = control->active_producers().producers[i].producer_name; } CALL_TEST_FUNCTION( *this, "test_chain", "test_activeprods", fc::raw::pack(prods) ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * db_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(db_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(testapi2) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_db_wasm() ); set_abi( N(testapi), contracts::test_api_db_abi().data() ); set_code( N(testapi2), contracts::test_api_db_wasm() ); set_abi( N(testapi2), contracts::test_api_db_abi().data() ); produce_blocks(1); push_action( N(testapi), N(pg), N(testapi), mutable_variant_object() ); // primary_i64_general push_action( N(testapi), N(pl), N(testapi), mutable_variant_object() ); // primary_i64_lowerbound push_action( N(testapi), N(pu), N(testapi), mutable_variant_object() ); // primary_i64_upperbound push_action( N(testapi), N(s1g), N(testapi), mutable_variant_object() ); // idx64_general push_action( N(testapi), N(s1l), N(testapi), mutable_variant_object() ); // idx64_lowerbound push_action( N(testapi), N(s1u), N(testapi), mutable_variant_object() ); // idx64_upperbound // Store value in primary table push_action( N(testapi), N(tia), N(testapi), mutable_variant_object() // test_invalid_access ("code", "testapi") ("val", 10) ("index", 0) ("store", true) ); // Attempt to change the value stored in the primary table under the code of N(testapi) BOOST_CHECK_EXCEPTION( push_action( N(testapi2), N(tia), N(testapi2), mutable_variant_object() ("code", "testapi") ("val", "20") ("index", 0) ("store", true) ), table_access_violation, fc_exception_message_is("db access violation") ); // Verify that the value has not changed. push_action( N(testapi), N(tia), N(testapi), mutable_variant_object() ("code", "testapi") ("val", 10) ("index", 0) ("store", false) ); // Store value in secondary table push_action( N(testapi), N(tia), N(testapi), mutable_variant_object() // test_invalid_access ("code", "testapi") ("val", 10) ("index", 1) ("store", true) ); // Attempt to change the value stored in the secondary table under the code of N(testapi) BOOST_CHECK_EXCEPTION( push_action( N(testapi2), N(tia), N(testapi2), mutable_variant_object() ("code", "testapi") ("val", "20") ("index", 1) ("store", true) ), table_access_violation, fc_exception_message_is("db access violation") ); // Verify that the value has not changed. push_action( N(testapi), N(tia), N(testapi), mutable_variant_object() ("code", "testapi") ("val", 10) ("index", 1) ("store", false) ); // idx_double_nan_create_fail BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnancreate), N(testapi), mutable_variant_object() ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); // idx_double_nan_modify_fail BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnanmodify), N(testapi), mutable_variant_object() ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); // idx_double_nan_lookup_fail BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnanlookup), N(testapi), mutable_variant_object() ("lookup_type", 0) // 0 for find ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnanlookup), N(testapi), mutable_variant_object() ("lookup_type", 1) // 1 for lower bound ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnanlookup), N(testapi), mutable_variant_object() ("lookup_type", 2) // 2 for upper bound ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); push_action( N(testapi), N(sk32align), N(testapi), mutable_variant_object() ); // misaligned_secondary_key256_tests BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * multi_index_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(multi_index_tests, TESTER) { try { produce_blocks(1); create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_multi_index_wasm() ); set_abi( N(testapi), contracts::test_api_multi_index_abi().data() ); produce_blocks(1); auto check_failure = [this]( action_name a, const char* expected_error_msg ) { BOOST_CHECK_EXCEPTION( push_action( N(testapi), a, N(testapi), {} ), eosio_assert_message_exception, eosio_assert_message_is( expected_error_msg ) ); }; push_action( N(testapi), N(s1g), N(testapi), {} ); // idx64_general push_action( N(testapi), N(s1store), N(testapi), {} ); // idx64_store_only push_action( N(testapi), N(s1check), N(testapi), {} ); // idx64_check_without_storing push_action( N(testapi), N(s2g), N(testapi), {} ); // idx128_general push_action( N(testapi), N(s2store), N(testapi), {} ); // idx128_store_only push_action( N(testapi), N(s2check), N(testapi), {} ); // idx128_check_without_storing push_action( N(testapi), N(s2autoinc), N(testapi), {} ); // idx128_autoincrement_test push_action( N(testapi), N(s2autoinc1), N(testapi), {} ); // idx128_autoincrement_test_part1 push_action( N(testapi), N(s2autoinc2), N(testapi), {} ); // idx128_autoincrement_test_part2 push_action( N(testapi), N(s3g), N(testapi), {} ); // idx256_general push_action( N(testapi), N(sdg), N(testapi), {} ); // idx_double_general push_action( N(testapi), N(sldg), N(testapi), {} ); // idx_long_double_general check_failure( N(s1pkend), "cannot increment end iterator" ); // idx64_pk_iterator_exceed_end check_failure( N(s1skend), "cannot increment end iterator" ); // idx64_sk_iterator_exceed_end check_failure( N(s1pkbegin), "cannot decrement iterator at beginning of table" ); // idx64_pk_iterator_exceed_begin check_failure( N(s1skbegin), "cannot decrement iterator at beginning of index" ); // idx64_sk_iterator_exceed_begin check_failure( N(s1pkref), "object passed to iterator_to is not in multi_index" ); // idx64_pass_pk_ref_to_other_table check_failure( N(s1skref), "object passed to iterator_to is not in multi_index" ); // idx64_pass_sk_ref_to_other_table check_failure( N(s1pkitrto), "object passed to iterator_to is not in multi_index" ); // idx64_pass_pk_end_itr_to_iterator_to check_failure( N(s1pkmodify), "cannot pass end iterator to modify" ); // idx64_pass_pk_end_itr_to_modify check_failure( N(s1pkerase), "cannot pass end iterator to erase" ); // idx64_pass_pk_end_itr_to_erase check_failure( N(s1skitrto), "object passed to iterator_to is not in multi_index" ); // idx64_pass_sk_end_itr_to_iterator_to check_failure( N(s1skmodify), "cannot pass end iterator to modify" ); // idx64_pass_sk_end_itr_to_modify check_failure( N(s1skerase), "cannot pass end iterator to erase" ); // idx64_pass_sk_end_itr_to_erase check_failure( N(s1modpk), "updater cannot change primary key when modifying an object" ); // idx64_modify_primary_key check_failure( N(s1exhaustpk), "next primary key in table is at autoincrement limit" ); // idx64_run_out_of_avl_pk check_failure( N(s1findfail1), "unable to find key" ); // idx64_require_find_fail check_failure( N(s1findfail2), "unable to find primary key in require_find" );// idx64_require_find_fail_with_msg check_failure( N(s1findfail3), "unable to find secondary key" ); // idx64_require_find_sk_fail check_failure( N(s1findfail4), "unable to find sec key" ); // idx64_require_find_sk_fail_with_msg push_action( N(testapi), N(s1skcache), N(testapi), {} ); // idx64_sk_cache_pk_lookup push_action( N(testapi), N(s1pkcache), N(testapi), {} ); // idx64_pk_cache_sk_lookup BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * crypto_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(crypto_tests, TESTER) { try { produce_block(); create_account(N(testapi) ); produce_block(); set_code(N(testapi), contracts::test_api_wasm() ); produce_block(); { signed_transaction trx; auto pl = vector<permission_level>{{N(testapi), config::active_name}}; action act(pl, test_api_action<TEST_METHOD("test_crypto", "test_recover_key")>{}); const auto priv_key = get_private_key(N(testapi), "active" ); const auto pub_key = priv_key.get_public_key(); auto hash = trx.sig_digest( control->get_chain_id() ); auto sig = priv_key.sign(hash); auto pk = fc::raw::pack( pub_key ); auto sigs = fc::raw::pack( sig ); vector<char> payload(8192); datastream<char*> payload_ds(payload.data(), payload.size()); fc::raw::pack(payload_ds, hash, (uint32_t)pk.size(), (uint32_t)sigs.size() ); payload_ds.write(pk.data(), pk.size() ); payload_ds.write(sigs.data(), sigs.size()); payload.resize(payload_ds.tellp()); //No Error Here CALL_TEST_FUNCTION( *this, "test_crypto", "test_recover_key", payload ); // Error Here CALL_TEST_FUNCTION( *this, "test_crypto", "test_recover_key_assert_true", payload ); payload[payload.size()-1] = 0; BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_crypto", "test_recover_key_assert_false", payload ), crypto_api_exception, fc_exception_message_is("Error expected key different than recovered key") ); } { signed_transaction trx; auto pl = vector<permission_level>{{N(testapi), config::active_name}}; action act(pl, test_api_action<TEST_METHOD("test_crypto", "test_recover_key_partial")>{}); // construct a mock WebAuthN pubkey and signature, as it is the only type that would be variable-sized const auto priv_key = get_private_key<mock::webauthn_private_key>(N(testapi), "active" ); const auto pub_key = priv_key.get_public_key(); auto hash = trx.sig_digest( control->get_chain_id() ); auto sig = priv_key.sign(hash); auto pk = fc::raw::pack( pub_key ); auto sigs = fc::raw::pack( sig ); vector<char> payload(8192); datastream<char*> payload_ds(payload.data(), payload.size()); fc::raw::pack(payload_ds, hash, (uint32_t)pk.size(), (uint32_t)sigs.size() ); payload_ds.write(pk.data(), pk.size() ); payload_ds.write(sigs.data(), sigs.size()); payload.resize(payload_ds.tellp()); //No Error Here CALL_TEST_FUNCTION( *this, "test_crypto", "test_recover_key_partial", payload ); } CALL_TEST_FUNCTION( *this, "test_crypto", "test_sha1", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "test_sha256", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "test_sha512", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "test_ripemd160", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "sha1_no_data", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "sha256_no_data", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "sha512_no_data", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "ripemd160_no_data", {} ); CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION( *this, "test_crypto", "assert_sha256_false", {}, crypto_api_exception, "hash mismatch" ); CALL_TEST_FUNCTION( *this, "test_crypto", "assert_sha256_true", {} ); CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION( *this, "test_crypto", "assert_sha1_false", {}, crypto_api_exception, "hash mismatch" ); CALL_TEST_FUNCTION( *this, "test_crypto", "assert_sha1_true", {} ); CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION( *this, "test_crypto", "assert_sha512_false", {}, crypto_api_exception, "hash mismatch" ); CALL_TEST_FUNCTION( *this, "test_crypto", "assert_sha512_true", {} ); CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION( *this, "test_crypto", "assert_ripemd160_false", {}, crypto_api_exception, "hash mismatch" ); CALL_TEST_FUNCTION( *this, "test_crypto", "assert_ripemd160_true", {} ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * print_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(print_tests, TESTER) { try { produce_blocks(2); create_account(N(testapi) ); produce_blocks(1000); set_code(N(testapi), contracts::test_api_wasm() ); produce_blocks(1000); string captured = ""; // test prints auto tx1_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_prints", {} ); auto tx1_act_cnsl = tx1_trace->action_traces.front().console; BOOST_CHECK_EQUAL(tx1_act_cnsl == "abcefg", true); // test prints_l auto tx2_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_prints_l", {} ); auto tx2_act_cnsl = tx2_trace->action_traces.front().console; BOOST_CHECK_EQUAL(tx2_act_cnsl == "abatest", true); // test printi auto tx3_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printi", {} ); auto tx3_act_cnsl = tx3_trace->action_traces.front().console; BOOST_CHECK_EQUAL( tx3_act_cnsl.substr(0,1), I64Str(0) ); BOOST_CHECK_EQUAL( tx3_act_cnsl.substr(1,6), I64Str(556644) ); BOOST_CHECK_EQUAL( tx3_act_cnsl.substr(7, std::string::npos), I64Str(-1) ); // test printui auto tx4_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printui", {} ); auto tx4_act_cnsl = tx4_trace->action_traces.front().console; BOOST_CHECK_EQUAL( tx4_act_cnsl.substr(0,1), U64Str(0) ); BOOST_CHECK_EQUAL( tx4_act_cnsl.substr(1,6), U64Str(556644) ); BOOST_CHECK_EQUAL( tx4_act_cnsl.substr(7, std::string::npos), U64Str(-1) ); // "18446744073709551615" // test printn auto tx5_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printn", {} ); auto tx5_act_cnsl = tx5_trace->action_traces.front().console; BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(0,1), "1" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(1,1), "5" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(2,1), "a" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(3,1), "z" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(4,3), "abc" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(7,3), "123" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(10,7), "abc.123" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(17,7), "123.abc" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(24,13), "12345abcdefgj" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(37,13), "ijklmnopqrstj" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(50,13), "vwxyz.12345aj" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(63, 13), "111111111111j" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(76, 13), "555555555555j" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(89, 13), "aaaaaaaaaaaaj" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(102,13), "zzzzzzzzzzzzj" ); // test printi128 auto tx6_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printi128", {} ); auto tx6_act_cnsl = tx6_trace->action_traces.front().console; size_t start = 0; size_t end = tx6_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx6_act_cnsl.substr(start, end-start), U128Str(1) ); start = end + 1; end = tx6_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx6_act_cnsl.substr(start, end-start), U128Str(0) ); start = end + 1; end = tx6_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx6_act_cnsl.substr(start, end-start), "-" + U128Str(static_cast<unsigned __int128>(std::numeric_limits<__int128>::lowest())) ); start = end + 1; end = tx6_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx6_act_cnsl.substr(start, end-start), "-" + U128Str(87654323456) ); // test printui128 auto tx7_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printui128", {} ); auto tx7_act_cnsl = tx7_trace->action_traces.front().console; start = 0; end = tx7_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx7_act_cnsl.substr(start, end-start), U128Str(std::numeric_limits<unsigned __int128>::max()) ); start = end + 1; end = tx7_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx7_act_cnsl.substr(start, end-start), U128Str(0) ); start = end + 1; end = tx7_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx7_act_cnsl.substr(start, end-start), U128Str(87654323456) ); // test printsf auto tx8_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printsf", {} ); auto tx8_act_cnsl = tx8_trace->action_traces.front().console; start = 0; end = tx8_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx8_act_cnsl.substr(start, end-start), "5.000000e-01" ); start = end + 1; end = tx8_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx8_act_cnsl.substr(start, end-start), "-3.750000e+00" ); start = end + 1; end = tx8_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx8_act_cnsl.substr(start, end-start), "6.666667e-07" ); // test printdf auto tx9_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printdf", {} ); auto tx9_act_cnsl = tx9_trace->action_traces.front().console; start = 0; end = tx9_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx9_act_cnsl.substr(start, end-start), "5.000000000000000e-01" ); start = end + 1; end = tx9_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx9_act_cnsl.substr(start, end-start), "-3.750000000000000e+00" ); start = end + 1; end = tx9_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx9_act_cnsl.substr(start, end-start), "6.666666666666666e-07" ); // test printqf #ifdef __x86_64__ std::string expect1 = "5.000000000000000000e-01"; std::string expect2 = "-3.750000000000000000e+00"; std::string expect3 = "6.666666666666666667e-07"; #else std::string expect1 = "5.000000000000000e-01"; std::string expect2 = "-3.750000000000000e+00"; std::string expect3 = "6.666666666666667e-07"; #endif auto tx10_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printqf", {} ); auto tx10_act_cnsl = tx10_trace->action_traces.front().console; start = 0; end = tx10_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx10_act_cnsl.substr(start, end-start), expect1 ); start = end + 1; end = tx10_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx10_act_cnsl.substr(start, end-start), expect2 ); start = end + 1; end = tx10_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx10_act_cnsl.substr(start, end-start), expect3 ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * types_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(types_tests, TESTER) { try { produce_blocks(1000); create_account( N(testapi) ); produce_blocks(1000); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1000); CALL_TEST_FUNCTION( *this, "test_types", "types_size", {}); CALL_TEST_FUNCTION( *this, "test_types", "char_to_symbol", {}); CALL_TEST_FUNCTION( *this, "test_types", "string_to_name", {}); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * permission_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(permission_tests, TESTER) { try { produce_blocks(1); create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); auto get_result_int64 = [&]() -> int64_t { const auto& db = control->db(); const auto* t_id = db.find<table_id_object, by_code_scope_table>(boost::make_tuple(N(testapi), N(testapi), N(testapi))); FC_ASSERT(t_id != 0, "Table id not found"); const auto& idx = db.get_index<key_value_index, by_scope_primary>(); auto itr = idx.lower_bound(boost::make_tuple(t_id->id)); FC_ASSERT( itr != idx.end() && itr->t_id == t_id->id, "lower_bound failed"); FC_ASSERT( 0 != itr->value.size(), "unexpected result size"); return *reinterpret_cast<const int64_t *>(itr->value.data()); }; CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(active), .pubkeys = { get_public_key(N(testapi), "active") } }) ); BOOST_CHECK_EQUAL( int64_t(1), get_result_int64() ); CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(active), .pubkeys = { public_key_type(string("EOS7GfRtyDWWgxV88a5TRaYY59XmHptyfjsFmHHfioGNJtPjpSmGX")) } }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(active), .pubkeys = { get_public_key(N(testapi), "active"), public_key_type(string("EOS7GfRtyDWWgxV88a5TRaYY59XmHptyfjsFmHHfioGNJtPjpSmGX")) } }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); // Failure due to irrelevant signatures CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(noname), .permission = N(active), .pubkeys = { get_public_key(N(testapi), "active") } }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(active), .pubkeys = {} }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(noname), .pubkeys = { get_public_key(N(testapi), "active") } }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); } FC_LOG_AND_RETHROW() } #if 0 /************************************************************************************* * privileged_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(privileged_tests, tester) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(acc1) ); produce_blocks(100); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); { signed_transaction trx; auto pl = vector<permission_level>{{config::system_account_name, config::active_name}}; action act(pl, test_chain_action<N(setprods)>()); vector<producer_key> prod_keys = { { N(inita), get_public_key( N(inita), "active" ) }, { N(initb), get_public_key( N(initb), "active" ) }, { N(initc), get_public_key( N(initc), "active" ) }, { N(initd), get_public_key( N(initd), "active" ) }, { N(inite), get_public_key( N(inite), "active" ) }, { N(initf), get_public_key( N(initf), "active" ) }, { N(initg), get_public_key( N(initg), "active" ) }, { N(inith), get_public_key( N(inith), "active" ) }, { N(initi), get_public_key( N(initi), "active" ) }, { N(initj), get_public_key( N(initj), "active" ) }, { N(initk), get_public_key( N(initk), "active" ) }, { N(initl), get_public_key( N(initl), "active" ) }, { N(initm), get_public_key( N(initm), "active" ) }, { N(initn), get_public_key( N(initn), "active" ) }, { N(inito), get_public_key( N(inito), "active" ) }, { N(initp), get_public_key( N(initp), "active" ) }, { N(initq), get_public_key( N(initq), "active" ) }, { N(initr), get_public_key( N(initr), "active" ) }, { N(inits), get_public_key( N(inits), "active" ) }, { N(initt), get_public_key( N(initt), "active" ) }, { N(initu), get_public_key( N(initu), "active" ) } }; vector<char> data = fc::raw::pack(uint32_t(0)); vector<char> keys = fc::raw::pack(prod_keys); data.insert( data.end(), keys.begin(), keys.end() ); act.data = data; trx.actions.push_back(act); set_tapos(trx); auto sigs = trx.sign(get_private_key(config::system_account_name, "active"), control->get_chain_id()); trx.get_signature_keys(control->get_chain_id() ); auto res = push_transaction(trx); BOOST_CHECK_EQUAL(res.status, transaction_receipt::executed); } CALL_TEST_FUNCTION( *this, "test_privileged", "test_is_privileged", {} ); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_privileged", "test_is_privileged", {} ), transaction_exception, [](const fc::exception& e) { return expect_assert_message(e, "context.privileged: testapi does not have permission to call this API"); } ); } FC_LOG_AND_RETHROW() } #endif /************************************************************************************* * real_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(datastream_tests, TESTER) { try { produce_blocks(1000); create_account(N(testapi) ); produce_blocks(1000); set_code(N(testapi), contracts::test_api_wasm() ); produce_blocks(1000); CALL_TEST_FUNCTION( *this, "test_datastream", "test_basic", {} ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * permission_usage_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(permission_usage_tests, TESTER) { try { produce_block(); create_accounts( {N(testapi), N(alice), N(bob)} ); produce_block(); set_code(N(testapi), contracts::test_api_wasm() ); produce_block(); push_reqauth( N(alice), {{N(alice), config::active_name}}, {get_private_key(N(alice), "active")} ); CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(alice), config::active_name, control->pending_block_time() }) ); // Fails because the last used time is updated after the transaction executes. BOOST_CHECK_THROW( CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(testapi), config::active_name, control->head_block_time() + fc::milliseconds(config::block_interval_ms) }) ), eosio_assert_message_exception ); produce_blocks(5); set_authority( N(bob), N(perm1), authority( get_private_key(N(bob), "perm1").get_public_key() ) ); push_action(config::system_account_name, linkauth::get_name(), N(bob), fc::mutable_variant_object() ("account", "bob") ("code", "eosio") ("type", "reqauth") ("requirement", "perm1") ); auto permission_creation_time = control->pending_block_time(); produce_blocks(5); CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(bob), N(perm1), permission_creation_time }) ); produce_blocks(5); push_reqauth( N(bob), {{N(bob), N(perm1)}}, {get_private_key(N(bob), "perm1")} ); auto perm1_last_used_time = control->pending_block_time(); CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(bob), config::active_name, permission_creation_time }) ); BOOST_CHECK_THROW( CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(bob), N(perm1), permission_creation_time }) ), eosio_assert_message_exception ); CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(bob), N(perm1), perm1_last_used_time }) ); produce_block(); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * account_creation_time_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(account_creation_time_tests, TESTER) { try { produce_block(); create_account( N(testapi) ); produce_block(); set_code(N(testapi), contracts::test_api_wasm() ); produce_block(); create_account( N(alice) ); auto alice_creation_time = control->pending_block_time(); produce_blocks(10); CALL_TEST_FUNCTION( *this, "test_permission", "test_account_creation_time", fc::raw::pack(test_permission_last_used_action{ N(alice), config::active_name, alice_creation_time }) ); produce_block(); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * extended_symbol_api_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(extended_symbol_api_tests, TESTER) { try { name n0{"1"}; name n1{"5"}; name n2{"a"}; name n3{"z"}; name n4{"111111111111j"}; name n5{"555555555555j"}; name n6{"zzzzzzzzzzzzj"}; symbol s0{4, ""}; symbol s1{5, "Z"}; symbol s2{10, "AAAAA"}; symbol s3{10, "ZZZZZ"}; // Test comparison operators BOOST_REQUIRE( (extended_symbol{s0, n0} == extended_symbol{s0, n0}) ); BOOST_REQUIRE( (extended_symbol{s1, n3} == extended_symbol{s1, n3}) ); BOOST_REQUIRE( (extended_symbol{s2, n4} == extended_symbol{s2, n4}) ); BOOST_REQUIRE( (extended_symbol{s3, n6} == extended_symbol{s3, n6}) ); BOOST_REQUIRE( (extended_symbol{s0, n0} != extended_symbol{s1, n0}) ); BOOST_REQUIRE( (extended_symbol{s0, n0} != extended_symbol{s0, n1}) ); BOOST_REQUIRE( (extended_symbol{s1, n1} != extended_symbol{s2, n2}) ); BOOST_REQUIRE( (extended_symbol{s0, n0} < extended_symbol{s1, n0}) ); BOOST_REQUIRE( (extended_symbol{s0, n0} < extended_symbol{s0, n1}) ); BOOST_REQUIRE( (extended_symbol{s0, n5} < extended_symbol{s0, n3}) ); BOOST_REQUIRE( (extended_symbol{s2, n0} < extended_symbol{s3, n0}) ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * eosio_assert_code_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(eosio_assert_code_tests, TESTER) { try { produce_block(); create_account( N(testapi) ); produce_block(); set_code(N(testapi), contracts::test_api_wasm() ); const char* abi_string = R"=====( { "version": "eosio::abi/1.0", "types": [], "structs": [], "actions": [], "tables": [], "ricardian_clauses": [], "error_messages": [ {"error_code": 1, "error_msg": "standard error message" }, {"error_code": 42, "error_msg": "The answer to life, the universe, and everything."} ] "abi_extensions": [] } )====="; set_abi( N(testapi), abi_string ); auto var = fc::json::from_string(abi_string); abi_serializer abis(var.as<abi_def>(), abi_serializer::create_yield_function( abi_serializer_max_time )); produce_blocks(10); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_action", "test_assert_code", fc::raw::pack((uint64_t)42) ), eosio_assert_code_exception, eosio_assert_code_is(42) ); auto trace = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_assert_code", fc::raw::pack((uint64_t)42) ); BOOST_REQUIRE( trace ); BOOST_REQUIRE( trace->except ); BOOST_REQUIRE( trace->error_code ); BOOST_REQUIRE_EQUAL( *trace->error_code, 42 ); BOOST_REQUIRE_EQUAL( trace->action_traces.size(), 1 ); BOOST_REQUIRE( trace->action_traces[0].except ); BOOST_REQUIRE( trace->action_traces[0].error_code ); BOOST_REQUIRE_EQUAL( *trace->action_traces[0].error_code, 42 ); produce_block(); auto omsg1 = abis.get_error_message(1); BOOST_REQUIRE_EQUAL( omsg1.valid(), true ); BOOST_CHECK_EQUAL( *omsg1, "standard error message" ); auto omsg2 = abis.get_error_message(2); BOOST_CHECK_EQUAL( omsg2.valid(), false ); auto omsg3 = abis.get_error_message(42); BOOST_REQUIRE_EQUAL( omsg3.valid(), true ); BOOST_CHECK_EQUAL( *omsg3, "The answer to life, the universe, and everything." ); produce_block(); auto trace2 = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_assert_code", fc::raw::pack( static_cast<uint64_t>(system_error_code::generic_system_error) ) ); BOOST_REQUIRE( trace2 ); BOOST_REQUIRE( trace2->except ); BOOST_REQUIRE( trace2->error_code ); BOOST_REQUIRE_EQUAL( *trace2->error_code, static_cast<uint64_t>(system_error_code::contract_restricted_error_code) ); BOOST_REQUIRE_EQUAL( trace2->action_traces.size(), 1 ); BOOST_REQUIRE( trace2->action_traces[0].except ); BOOST_REQUIRE( trace2->action_traces[0].error_code ); BOOST_REQUIRE_EQUAL( *trace2->action_traces[0].error_code, static_cast<uint64_t>(system_error_code::contract_restricted_error_code) ); produce_block(); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* + * action_ordinal_test test cases + *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_ordinal_test, TESTER) { try { produce_blocks(1); create_account(N(testapi) ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(bob) ); set_code( N(bob), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(charlie) ); set_code( N(charlie), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(david) ); set_code( N(david), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(erin) ); set_code( N(erin), contracts::test_api_wasm() ); produce_blocks(1); // prove act digest auto pad = [](const digest_type& expected_act_digest, const action& act, const vector<char>& act_output) { std::vector<char> buf1; buf1.resize(64); datastream<char*> ds(buf1.data(), buf1.size()); { std::vector<char> buf2; const action_base* act_base = &act; buf2.resize(fc::raw::pack_size(*act_base)); datastream<char*> ds2(buf2.data(), buf2.size()); fc::raw::pack(ds2, *act_base); fc::raw::pack(ds, sha256::hash(buf2.data(), buf2.size())); } { std::vector<char> buf2; buf2.resize(fc::raw::pack_size(act.data) + fc::raw::pack_size(act_output)); datastream<char*> ds2(buf2.data(), buf2.size()); fc::raw::pack(ds2, act.data); fc::raw::pack(ds2, act_output); fc::raw::pack(ds, sha256::hash(buf2.data(), buf2.size())); } digest_type computed_act_digest = sha256::hash(buf1.data(), ds.tellp()); return expected_act_digest == computed_act_digest; }; transaction_trace_ptr txn_trace = CALL_TEST_FUNCTION_SCOPE( *this, "test_action", "test_action_ordinal1", {}, vector<account_name>{ N(testapi)}); BOOST_REQUIRE_EQUAL( validate(), true ); BOOST_REQUIRE_EQUAL( txn_trace != nullptr, true); BOOST_REQUIRE_EQUAL( txn_trace->action_traces.size(), 11); auto &atrace = txn_trace->action_traces; BOOST_REQUIRE_EQUAL((int)atrace[0].action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[0].creator_action_ordinal, 0); BOOST_REQUIRE_EQUAL((int)atrace[0].closest_unnotified_ancestor_action_ordinal, 0); BOOST_REQUIRE_EQUAL(atrace[0].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[0].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<unsigned_int>(atrace[0].return_value), unsigned_int(1) ); BOOST_REQUIRE(pad(atrace[0].receipt->act_digest, atrace[0].act, atrace[0].return_value)); int start_gseq = atrace[0].receipt->global_sequence; BOOST_REQUIRE_EQUAL((int)atrace[1].action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[1].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[1].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[1].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[1].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[1].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[1].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[1].return_value), "bob" ); BOOST_REQUIRE(pad(atrace[1].receipt->act_digest, atrace[1].act, atrace[1].return_value)); BOOST_REQUIRE_EQUAL(atrace[1].receipt->global_sequence, start_gseq + 1); BOOST_REQUIRE_EQUAL((int)atrace[2].action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[2].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[2].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[2].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[2].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<name>(atrace[2].return_value), name("five") ); BOOST_REQUIRE(pad(atrace[2].receipt->act_digest, atrace[2].act, atrace[2].return_value)); BOOST_REQUIRE_EQUAL(atrace[2].receipt->global_sequence, start_gseq + 4); BOOST_REQUIRE_EQUAL((int)atrace[3].action_ordinal, 4); BOOST_REQUIRE_EQUAL((int)atrace[3].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[3].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[3].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.name, TEST_METHOD("test_action", "test_action_ordinal3")); BOOST_REQUIRE_EQUAL(atrace[3].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<unsigned_int>(atrace[3].return_value), unsigned_int(9) ); BOOST_REQUIRE(pad(atrace[3].receipt->act_digest, atrace[3].act, atrace[3].return_value)); BOOST_REQUIRE_EQUAL(atrace[3].receipt->global_sequence, start_gseq + 8); BOOST_REQUIRE_EQUAL((int)atrace[4].action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[4].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[4].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[4].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[4].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[4].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[4].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[4].return_value), "charlie" ); BOOST_REQUIRE(pad(atrace[4].receipt->act_digest, atrace[4].act, atrace[4].return_value)); BOOST_REQUIRE_EQUAL(atrace[4].receipt->global_sequence, start_gseq + 2); BOOST_REQUIRE_EQUAL((int)atrace[5].action_ordinal, 6); BOOST_REQUIRE_EQUAL((int)atrace[5].creator_action_ordinal, 2); BOOST_REQUIRE_EQUAL((int)atrace[5].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[5].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.account, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.name, TEST_METHOD("test_action", "test_action_ordinal_foo")); BOOST_REQUIRE_EQUAL(atrace[5].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<double>(atrace[5].return_value), 13.23 ); BOOST_REQUIRE(pad(atrace[5].receipt->act_digest, atrace[5].act, atrace[5].return_value)); BOOST_REQUIRE_EQUAL(atrace[5].receipt->global_sequence, start_gseq + 9); BOOST_REQUIRE_EQUAL((int)atrace[6].action_ordinal, 7); BOOST_REQUIRE_EQUAL((int)atrace[6].creator_action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[6].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[6].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[6].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[6].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[6].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[6].return_value), "david" ); BOOST_REQUIRE(pad(atrace[6].receipt->act_digest, atrace[6].act, atrace[6].return_value)); BOOST_REQUIRE_EQUAL(atrace[6].receipt->global_sequence, start_gseq + 3); BOOST_REQUIRE_EQUAL((int)atrace[7].action_ordinal, 8); BOOST_REQUIRE_EQUAL((int)atrace[7].creator_action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[7].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[7].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.account, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.name, TEST_METHOD("test_action", "test_action_ordinal_bar")); BOOST_REQUIRE_EQUAL(atrace[7].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<float>(atrace[7].return_value), 11.42f ); BOOST_REQUIRE(pad(atrace[7].receipt->act_digest, atrace[7].act, atrace[7].return_value)); BOOST_REQUIRE_EQUAL(atrace[7].receipt->global_sequence, start_gseq + 10); BOOST_REQUIRE_EQUAL((int)atrace[8].action_ordinal, 9); BOOST_REQUIRE_EQUAL((int)atrace[8].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[8].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[8].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[8].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[8].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[8].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<bool>(atrace[8].return_value), true ); BOOST_REQUIRE(pad(atrace[8].receipt->act_digest, atrace[8].act, atrace[8].return_value)); BOOST_REQUIRE_EQUAL(atrace[8].receipt->global_sequence, start_gseq + 5); BOOST_REQUIRE_EQUAL((int)atrace[9].action_ordinal, 10); BOOST_REQUIRE_EQUAL((int)atrace[9].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[9].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[9].receiver, N(erin)); BOOST_REQUIRE_EQUAL(atrace[9].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[9].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[9].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<signed_int>(atrace[9].return_value), signed_int(7) ); BOOST_REQUIRE(pad(atrace[9].receipt->act_digest, atrace[9].act, atrace[9].return_value)); BOOST_REQUIRE_EQUAL(atrace[9].receipt->global_sequence, start_gseq + 6); BOOST_REQUIRE_EQUAL((int)atrace[10].action_ordinal, 11); BOOST_REQUIRE_EQUAL((int)atrace[10].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[10].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[10].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[10].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[10].act.name, TEST_METHOD("test_action", "test_action_ordinal4")); BOOST_REQUIRE_EQUAL(atrace[10].receipt.valid(), true); BOOST_REQUIRE_EQUAL(atrace[10].return_value.size(), 0 ); BOOST_REQUIRE_EQUAL(atrace[10].receipt->global_sequence, start_gseq + 7); } FC_LOG_AND_RETHROW() } /************************************************************************************* + * action_ordinal_failtest1 test cases + *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_ordinal_failtest1, TESTER) { try { produce_blocks(1); create_account(N(testapi) ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(bob) ); set_code( N(bob), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(charlie) ); set_code( N(charlie), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(david) ); set_code( N(david), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(erin) ); set_code( N(erin), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(fail1) ); // <- make first action fails in the middle produce_blocks(1); transaction_trace_ptr txn_trace = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_action_ordinal1", {}); BOOST_REQUIRE_EQUAL( validate(), true ); BOOST_REQUIRE_EQUAL( txn_trace != nullptr, true); BOOST_REQUIRE_EQUAL( txn_trace->action_traces.size(), 3); auto &atrace = txn_trace->action_traces; // fails here after creating one notify action and one inline action BOOST_REQUIRE_EQUAL((int)atrace[0].action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[0].creator_action_ordinal, 0); BOOST_REQUIRE_EQUAL((int)atrace[0].closest_unnotified_ancestor_action_ordinal, 0); BOOST_REQUIRE_EQUAL(atrace[0].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[0].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[0].except.valid(), true); BOOST_REQUIRE_EQUAL(atrace[0].except->code(), 3050003); // not executed BOOST_REQUIRE_EQUAL((int)atrace[1].action_ordinal, 2); BOOST_REQUIRE_EQUAL((int)atrace[1].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[1].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[1].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[1].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[1].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[1].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[1].except.valid(), false); // not executed BOOST_REQUIRE_EQUAL((int)atrace[2].action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[2].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[2].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[2].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[2].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[2].except.valid(), false); } FC_LOG_AND_RETHROW() } /************************************************************************************* + * action_ordinal_failtest2 test cases + *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_ordinal_failtest2, TESTER) { try { produce_blocks(1); create_account(N(testapi) ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(bob) ); set_code( N(bob), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(charlie) ); set_code( N(charlie), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(david) ); set_code( N(david), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(erin) ); set_code( N(erin), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(fail3) ); // <- make action 3 fails in the middle produce_blocks(1); transaction_trace_ptr txn_trace = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_action_ordinal1", {}); BOOST_REQUIRE_EQUAL( validate(), true ); BOOST_REQUIRE_EQUAL( txn_trace != nullptr, true); BOOST_REQUIRE_EQUAL( txn_trace->action_traces.size(), 8); auto &atrace = txn_trace->action_traces; // executed BOOST_REQUIRE_EQUAL((int)atrace[0].action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[0].creator_action_ordinal, 0); BOOST_REQUIRE_EQUAL((int)atrace[0].closest_unnotified_ancestor_action_ordinal, 0); BOOST_REQUIRE_EQUAL(atrace[0].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[0].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<unsigned_int>(atrace[0].return_value), unsigned_int(1) ); BOOST_REQUIRE_EQUAL(atrace[0].except.valid(), false); int start_gseq = atrace[0].receipt->global_sequence; // executed BOOST_REQUIRE_EQUAL((int)atrace[1].action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[1].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[1].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[1].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[1].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[1].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[1].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[1].return_value), "bob" ); BOOST_REQUIRE_EQUAL(atrace[1].receipt->global_sequence, start_gseq + 1); // not executed BOOST_REQUIRE_EQUAL((int)atrace[2].action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[2].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[2].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[2].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[2].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[2].except.valid(), false); // not executed BOOST_REQUIRE_EQUAL((int)atrace[3].action_ordinal, 4); BOOST_REQUIRE_EQUAL((int)atrace[3].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[3].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[3].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.name, TEST_METHOD("test_action", "test_action_ordinal3")); BOOST_REQUIRE_EQUAL(atrace[3].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[3].except.valid(), false); // hey exception is here BOOST_REQUIRE_EQUAL((int)atrace[4].action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[4].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[4].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[4].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[4].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[4].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[4].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[4].except.valid(), true); BOOST_REQUIRE_EQUAL(atrace[4].except->code(), 3050003); // not executed BOOST_REQUIRE_EQUAL((int)atrace[5].action_ordinal, 6); BOOST_REQUIRE_EQUAL((int)atrace[5].creator_action_ordinal, 2); BOOST_REQUIRE_EQUAL((int)atrace[5].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[5].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.account, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.name, TEST_METHOD("test_action", "test_action_ordinal_foo")); BOOST_REQUIRE_EQUAL(atrace[5].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[5].except.valid(), false); // not executed BOOST_REQUIRE_EQUAL((int)atrace[6].action_ordinal, 7); BOOST_REQUIRE_EQUAL((int)atrace[6].creator_action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[6].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[6].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[6].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[6].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[6].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[6].except.valid(), false); // not executed BOOST_REQUIRE_EQUAL((int)atrace[7].action_ordinal, 8); BOOST_REQUIRE_EQUAL((int)atrace[7].creator_action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[7].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[7].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.account, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.name, TEST_METHOD("test_action", "test_action_ordinal_bar")); BOOST_REQUIRE_EQUAL(atrace[7].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[7].except.valid(), false); } FC_LOG_AND_RETHROW() } /************************************************************************************* + * action_ordinal_failtest3 test cases + *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_ordinal_failtest3, TESTER) { try { produce_blocks(1); create_account(N(testapi) ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(bob) ); set_code( N(bob), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(charlie) ); set_code( N(charlie), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(david) ); set_code( N(david), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(erin) ); set_code( N(erin), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(failnine) ); // <- make action 9 fails in the middle produce_blocks(1); transaction_trace_ptr txn_trace = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_action_ordinal1", {}); BOOST_REQUIRE_EQUAL( validate(), true ); BOOST_REQUIRE_EQUAL( txn_trace != nullptr, true); BOOST_REQUIRE_EQUAL( txn_trace->action_traces.size(), 11); auto &atrace = txn_trace->action_traces; // executed BOOST_REQUIRE_EQUAL((int)atrace[0].action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[0].creator_action_ordinal, 0); BOOST_REQUIRE_EQUAL((int)atrace[0].closest_unnotified_ancestor_action_ordinal, 0); BOOST_REQUIRE_EQUAL(atrace[0].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[0].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<unsigned_int>(atrace[0].return_value), unsigned_int(1) ); BOOST_REQUIRE_EQUAL(atrace[0].except.valid(), false); int start_gseq = atrace[0].receipt->global_sequence; // executed BOOST_REQUIRE_EQUAL((int)atrace[1].action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[1].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[1].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[1].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[1].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[1].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[1].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[1].return_value), "bob" ); BOOST_REQUIRE_EQUAL(atrace[1].receipt->global_sequence, start_gseq + 1); // executed BOOST_REQUIRE_EQUAL((int)atrace[2].action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[2].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[2].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[2].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[2].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<name>(atrace[2].return_value), name("five") ); BOOST_REQUIRE_EQUAL(atrace[2].receipt->global_sequence, start_gseq + 4); // fails here BOOST_REQUIRE_EQUAL((int)atrace[3].action_ordinal, 4); BOOST_REQUIRE_EQUAL((int)atrace[3].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[3].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[3].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.name, TEST_METHOD("test_action", "test_action_ordinal3")); BOOST_REQUIRE_EQUAL(atrace[3].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[3].except.valid(), true); BOOST_REQUIRE_EQUAL(atrace[3].except->code(), 3050003); // executed BOOST_REQUIRE_EQUAL((int)atrace[4].action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[4].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[4].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[4].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[4].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[4].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[4].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[4].return_value), "charlie" ); BOOST_REQUIRE_EQUAL(atrace[4].receipt->global_sequence, start_gseq + 2); // not executed BOOST_REQUIRE_EQUAL((int)atrace[5].action_ordinal, 6); BOOST_REQUIRE_EQUAL((int)atrace[5].creator_action_ordinal, 2); BOOST_REQUIRE_EQUAL((int)atrace[5].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[5].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.account, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.name, TEST_METHOD("test_action", "test_action_ordinal_foo")); BOOST_REQUIRE_EQUAL(atrace[5].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[5].except.valid(), false); // executed BOOST_REQUIRE_EQUAL((int)atrace[6].action_ordinal, 7); BOOST_REQUIRE_EQUAL((int)atrace[6].creator_action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[6].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[6].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[6].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[6].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[6].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[6].return_value), "david" ); BOOST_REQUIRE_EQUAL(atrace[6].receipt->global_sequence, start_gseq + 3); // not executed BOOST_REQUIRE_EQUAL((int)atrace[7].action_ordinal, 8); BOOST_REQUIRE_EQUAL((int)atrace[7].creator_action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[7].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[7].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.account, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.name, TEST_METHOD("test_action", "test_action_ordinal_bar")); BOOST_REQUIRE_EQUAL(atrace[7].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[7].except.valid(), false); // executed BOOST_REQUIRE_EQUAL((int)atrace[8].action_ordinal, 9); BOOST_REQUIRE_EQUAL((int)atrace[8].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[8].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[8].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[8].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[8].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[8].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<bool>(atrace[8].return_value), true ); BOOST_REQUIRE_EQUAL(atrace[8].receipt->global_sequence, start_gseq + 5); // executed BOOST_REQUIRE_EQUAL((int)atrace[9].action_ordinal, 10); BOOST_REQUIRE_EQUAL((int)atrace[9].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[9].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[9].receiver, N(erin)); BOOST_REQUIRE_EQUAL(atrace[9].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[9].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[9].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<signed_int>(atrace[9].return_value), signed_int(7) ); BOOST_REQUIRE_EQUAL(atrace[9].receipt->global_sequence, start_gseq + 6); // executed BOOST_REQUIRE_EQUAL((int)atrace[10].action_ordinal, 11); BOOST_REQUIRE_EQUAL((int)atrace[10].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[10].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[10].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[10].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[10].act.name, TEST_METHOD("test_action", "test_action_ordinal4")); BOOST_REQUIRE_EQUAL(atrace[10].receipt.valid(), true); BOOST_REQUIRE_EQUAL(atrace[10].return_value.size(), 0 ); BOOST_REQUIRE_EQUAL(atrace[10].receipt->global_sequence, start_gseq + 7); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END() Add test case that triggers memory leak in reference_proxy. #include <algorithm> #include <random> #include <iostream> #include <vector> #include <iterator> #include <numeric> #include <string> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" #include <boost/test/unit_test.hpp> #pragma GCC diagnostic pop #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <boost/algorithm/string/predicate.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/account_object.hpp> #include <eosio/chain/contract_table_objects.hpp> #include <eosio/chain/block_summary_object.hpp> #include <eosio/chain/global_property_object.hpp> #include <eosio/chain/generated_transaction_object.hpp> #include <eosio/chain/resource_limits.hpp> #include <fc/crypto/digest.hpp> #include <fc/exception/exception.hpp> #include <fc/variant_object.hpp> #include <Inline/BasicTypes.h> #include <Runtime/Runtime.h> #include <contracts.hpp> #define DUMMY_ACTION_DEFAULT_A 0x45 #define DUMMY_ACTION_DEFAULT_B 0xab11cd1244556677 #define DUMMY_ACTION_DEFAULT_C 0x7451ae12 static constexpr unsigned int DJBH(const char* cp) { unsigned int hash = 5381; while (*cp) hash = 33 * hash ^ (unsigned char) *cp++; return hash; } static constexpr unsigned long long WASM_TEST_ACTION(const char* cls, const char* method) { return static_cast<unsigned long long>(DJBH(cls)) << 32 | static_cast<unsigned long long>(DJBH(method)); } struct dummy_action { static eosio::chain::name get_name() { return N(dummyaction); } static eosio::chain::name get_account() { return N(testapi); } char a; //1 uint64_t b; //8 int32_t c; //4 }; struct u128_action { unsigned __int128 values[3]; //16*3 }; struct cf_action { static eosio::chain::name get_name() { return N(cfaction); } static eosio::chain::name get_account() { return N(testapi); } uint32_t payload = 100; uint32_t cfd_idx = 0; // context free data index }; // Deferred Transaction Trigger Action struct dtt_action { static uint64_t get_name() { return WASM_TEST_ACTION("test_transaction", "send_deferred_tx_with_dtt_action"); } static uint64_t get_account() { return N(testapi).to_uint64_t(); } uint64_t payer = N(testapi).to_uint64_t(); uint64_t deferred_account = N(testapi).to_uint64_t(); uint64_t deferred_action = WASM_TEST_ACTION("test_transaction", "deferred_print"); uint64_t permission_name = N(active).to_uint64_t(); uint32_t delay_sec = 2; }; struct invalid_access_action { uint64_t code; uint64_t val; uint32_t index; bool store; }; FC_REFLECT( dummy_action, (a)(b)(c) ) FC_REFLECT( u128_action, (values) ) FC_REFLECT( cf_action, (payload)(cfd_idx) ) FC_REFLECT( dtt_action, (payer)(deferred_account)(deferred_action)(permission_name)(delay_sec) ) FC_REFLECT( invalid_access_action, (code)(val)(index)(store) ) #ifdef NON_VALIDATING_TEST #define TESTER tester #else #define TESTER validating_tester #endif using namespace eosio; using namespace eosio::testing; using namespace chain; using namespace fc; namespace bio = boost::iostreams; template<uint64_t NAME> struct test_api_action { static account_name get_account() { return N(testapi); } static action_name get_name() { return action_name(NAME); } }; FC_REFLECT_TEMPLATE((uint64_t T), test_api_action<T>, BOOST_PP_SEQ_NIL) template<uint64_t NAME> struct test_chain_action { static account_name get_account() { return account_name(config::system_account_name); } static action_name get_name() { return action_name(NAME); } }; FC_REFLECT_TEMPLATE((uint64_t T), test_chain_action<T>, BOOST_PP_SEQ_NIL) struct check_auth { account_name account; permission_name permission; vector<public_key_type> pubkeys; }; FC_REFLECT(check_auth, (account)(permission)(pubkeys) ) struct test_permission_last_used_action { account_name account; permission_name permission; fc::time_point last_used_time; }; FC_REFLECT( test_permission_last_used_action, (account)(permission)(last_used_time) ) constexpr uint64_t TEST_METHOD(const char* CLASS, const char *METHOD) { return ( (uint64_t(DJBH(CLASS))<<32) | uint32_t(DJBH(METHOD)) ); } string I64Str(int64_t i) { std::stringstream ss; ss << i; return ss.str(); } string U64Str(uint64_t i) { std::stringstream ss; ss << i; return ss.str(); } string U128Str(unsigned __int128 i) { return fc::variant(fc::uint128_t(i)).get_string(); } template <typename T> transaction_trace_ptr CallAction(TESTER& test, T ac, const vector<account_name>& scope = {N(testapi)}) { signed_transaction trx; auto pl = vector<permission_level>{{scope[0], config::active_name}}; if (scope.size() > 1) for (size_t i = 1; i < scope.size(); i++) pl.push_back({scope[i], config::active_name}); action act(pl, ac); trx.actions.push_back(act); test.set_transaction_headers(trx); auto sigs = trx.sign(test.get_private_key(scope[0], "active"), test.control->get_chain_id()); flat_set<public_key_type> keys; trx.get_signature_keys(test.control->get_chain_id(), fc::time_point::maximum(), keys); auto res = test.push_transaction(trx); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); test.produce_block(); return res; } template <typename T> transaction_trace_ptr CallFunction(TESTER& test, T ac, const vector<char>& data, const vector<account_name>& scope = {N(testapi)}, bool no_throw = false) { { signed_transaction trx; auto pl = vector<permission_level>{{scope[0], config::active_name}}; if (scope.size() > 1) for (unsigned int i=1; i < scope.size(); i++) pl.push_back({scope[i], config::active_name}); action act(pl, ac); act.data = data; act.authorization = {{N(testapi), config::active_name}}; trx.actions.push_back(act); test.set_transaction_headers(trx, test.DEFAULT_EXPIRATION_DELTA); auto sigs = trx.sign(test.get_private_key(scope[0], "active"), test.control->get_chain_id()); flat_set<public_key_type> keys; trx.get_signature_keys(test.control->get_chain_id(), fc::time_point::maximum(), keys); auto res = test.push_transaction(trx, fc::time_point::maximum(), TESTER::DEFAULT_BILLED_CPU_TIME_US, no_throw); if (!no_throw) { BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); } test.produce_block(); return res; } } #define CALL_TEST_FUNCTION(_TESTER, CLS, MTH, DATA) CallFunction(_TESTER, test_api_action<TEST_METHOD(CLS, MTH)>{}, DATA) #define CALL_TEST_FUNCTION_SYSTEM(_TESTER, CLS, MTH, DATA) CallFunction(_TESTER, test_chain_action<TEST_METHOD(CLS, MTH)>{}, DATA, {config::system_account_name} ) #define CALL_TEST_FUNCTION_SCOPE(_TESTER, CLS, MTH, DATA, ACCOUNT) CallFunction(_TESTER, test_api_action<TEST_METHOD(CLS, MTH)>{}, DATA, ACCOUNT) #define CALL_TEST_FUNCTION_NO_THROW(_TESTER, CLS, MTH, DATA) CallFunction(_TESTER, test_api_action<TEST_METHOD(CLS, MTH)>{}, DATA, {N(testapi)}, true) #define CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION(_TESTER, CLS, MTH, DATA, EXC, EXC_MESSAGE) \ BOOST_CHECK_EXCEPTION( \ CALL_TEST_FUNCTION( _TESTER, CLS, MTH, DATA), \ EXC, \ [](const EXC& e) { \ return expect_assert_message(e, EXC_MESSAGE); \ } \ ); bool is_access_violation(fc::unhandled_exception const & e) { try { std::rethrow_exception(e.get_inner_exception()); } catch (const eosio::chain::wasm_execution_error& e) { return true; } catch (...) { } return false; } bool is_access_violation(const Runtime::Exception& e) { return true; } bool is_assert_exception(fc::assert_exception const & e) { return true; } bool is_page_memory_error(page_memory_error const &e) { return true; } bool is_unsatisfied_authorization(unsatisfied_authorization const & e) { return true;} bool is_wasm_execution_error(eosio::chain::wasm_execution_error const& e) {return true;} bool is_tx_net_usage_exceeded(const tx_net_usage_exceeded& e) { return true; } bool is_block_net_usage_exceeded(const tx_cpu_usage_exceeded& e) { return true; } bool is_tx_cpu_usage_exceeded(const tx_cpu_usage_exceeded& e) { return true; } bool is_block_cpu_usage_exceeded(const tx_cpu_usage_exceeded& e) { return true; } bool is_deadline_exception(const deadline_exception& e) { return true; } /* * register test suite `api_tests` */ BOOST_AUTO_TEST_SUITE(api_tests) /* * Print capturing stuff */ std::vector<std::string> capture; struct MySink : public bio::sink { std::streamsize write(const char* s, std::streamsize n) { std::string tmp; tmp.assign(s, n); capture.push_back(tmp); std::cout << "stream : [" << tmp << "]" << std::endl; return n; } }; uint32_t last_fnc_err = 0; BOOST_FIXTURE_TEST_CASE(action_receipt_tests, TESTER) { try { produce_blocks(2); create_account( N(test) ); set_code( N(test), contracts::payloadless_wasm() ); produce_blocks(1); auto call_doit_and_check = [&]( account_name contract, account_name signer, auto&& checker ) { signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{signer, config::active_name}}, contract, N(doit), bytes{} ); this->set_transaction_headers( trx, this->DEFAULT_EXPIRATION_DELTA ); trx.sign( this->get_private_key(signer, "active"), control->get_chain_id() ); auto res = this->push_transaction(trx); checker( res ); }; auto call_provereset_and_check = [&]( account_name contract, account_name signer, auto&& checker ) { signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{signer, config::active_name}}, contract, N(provereset), bytes{} ); this->set_transaction_headers( trx, this->DEFAULT_EXPIRATION_DELTA ); trx.sign( this->get_private_key(signer, "active"), control->get_chain_id() ); auto res = this->push_transaction(trx); checker( res ); }; auto result = push_reqauth( config::system_account_name, "active" ); BOOST_REQUIRE_EQUAL( result->receipt->status, transaction_receipt::executed ); BOOST_REQUIRE( result->action_traces[0].receipt->auth_sequence.find( config::system_account_name ) != result->action_traces[0].receipt->auth_sequence.end() ); auto base_global_sequence_num = result->action_traces[0].receipt->global_sequence; auto base_system_recv_seq_num = result->action_traces[0].receipt->recv_sequence; auto base_system_auth_seq_num = result->action_traces[0].receipt->auth_sequence[config::system_account_name]; auto base_system_code_seq_num = result->action_traces[0].receipt->code_sequence.value; auto base_system_abi_seq_num = result->action_traces[0].receipt->abi_sequence.value; uint64_t base_test_recv_seq_num = 0; uint64_t base_test_auth_seq_num = 0; call_doit_and_check( N(test), N(test), [&]( const transaction_trace_ptr& res ) { BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->global_sequence, base_global_sequence_num + 1 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->code_sequence.value, 1 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->abi_sequence.value, 0 ); base_test_recv_seq_num = res->action_traces[0].receipt->recv_sequence; BOOST_CHECK( base_test_recv_seq_num > 0 ); base_test_recv_seq_num--; const auto& m = res->action_traces[0].receipt->auth_sequence; BOOST_CHECK_EQUAL( m.size(), 1 ); BOOST_CHECK_EQUAL( m.begin()->first.to_string(), "test" ); base_test_auth_seq_num = m.begin()->second; BOOST_CHECK( base_test_auth_seq_num > 0 ); --base_test_auth_seq_num; } ); set_code( N(test), contracts::asserter_wasm() ); set_code( config::system_account_name, contracts::payloadless_wasm() ); call_provereset_and_check( N(test), N(test), [&]( const transaction_trace_ptr& res ) { BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->global_sequence, base_global_sequence_num + 4 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->recv_sequence, base_test_recv_seq_num + 2 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->code_sequence.value, 2 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->abi_sequence.value, 0 ); const auto& m = res->action_traces[0].receipt->auth_sequence; BOOST_CHECK_EQUAL( m.size(), 1 ); BOOST_CHECK_EQUAL( m.begin()->first.to_string(), "test" ); BOOST_CHECK_EQUAL( m.begin()->second, base_test_auth_seq_num + 3 ); } ); produce_blocks(1); // Added to avoid the last doit transaction from being considered a duplicate. // Adding a block also retires an onblock action which increments both the global sequence number // and the recv and auth sequences numbers for the system account. call_doit_and_check( config::system_account_name, N(test), [&]( const transaction_trace_ptr& res ) { BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->global_sequence, base_global_sequence_num + 6 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->recv_sequence, base_system_recv_seq_num + 4 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->code_sequence.value, base_system_code_seq_num + 1 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->abi_sequence.value, base_system_abi_seq_num ); const auto& m = res->action_traces[0].receipt->auth_sequence; BOOST_CHECK_EQUAL( m.size(), 1 ); BOOST_CHECK_EQUAL( m.begin()->first.to_string(), "test" ); BOOST_CHECK_EQUAL( m.begin()->second, base_test_auth_seq_num + 4 ); } ); set_code( config::system_account_name, contracts::eosio_bios_wasm() ); set_code( N(test), contracts::eosio_bios_wasm() ); set_abi( N(test), contracts::eosio_bios_abi().data() ); set_code( N(test), contracts::payloadless_wasm() ); call_doit_and_check( N(test), N(test), [&]( const transaction_trace_ptr& res ) { BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->global_sequence, base_global_sequence_num + 11 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->recv_sequence, base_test_recv_seq_num + 3 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->code_sequence.value, 4 ); BOOST_CHECK_EQUAL( res->action_traces[0].receipt->abi_sequence.value, 1 ); const auto& m = res->action_traces[0].receipt->auth_sequence; BOOST_CHECK_EQUAL( m.size(), 1 ); BOOST_CHECK_EQUAL( m.begin()->first.to_string(), "test" ); BOOST_CHECK_EQUAL( m.begin()->second, base_test_auth_seq_num + 8 ); } ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * action_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(acc1) ); create_account( N(acc2) ); create_account( N(acc3) ); create_account( N(acc4) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); // test assert_true CALL_TEST_FUNCTION( *this, "test_action", "assert_true", {}); //test assert_false BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_action", "assert_false", {} ), eosio_assert_message_exception, eosio_assert_message_is("test_action::assert_false") ); // test read_action_normal dummy_action dummy13{DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C}; CALL_TEST_FUNCTION( *this, "test_action", "read_action_normal", fc::raw::pack(dummy13)); // test read_action_to_0 std::vector<char> raw_bytes((1<<16)); CALL_TEST_FUNCTION( *this, "test_action", "read_action_to_0", raw_bytes ); // test read_action_to_0 raw_bytes.resize((1<<16)+1); BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "read_action_to_0", raw_bytes), eosio::chain::wasm_execution_error, [](const eosio::chain::wasm_execution_error& e) { return expect_assert_message(e, "access violation"); } ); // test read_action_to_64k raw_bytes.resize(1); CALL_TEST_FUNCTION( *this, "test_action", "read_action_to_64k", raw_bytes ); // test read_action_to_64k raw_bytes.resize(3); BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "read_action_to_64k", raw_bytes ), eosio::chain::wasm_execution_error, [](const eosio::chain::wasm_execution_error& e) { return expect_assert_message(e, "access violation"); } ); // test require_notice auto scope = std::vector<account_name>{N(testapi)}; auto test_require_notice = [this](auto& test, std::vector<char>& data, std::vector<account_name>& scope){ signed_transaction trx; auto tm = test_api_action<TEST_METHOD("test_action", "require_notice")>{}; action act(std::vector<permission_level>{{N(testapi), config::active_name}}, tm); vector<char>& dest = *(vector<char> *)(&act.data); std::copy(data.begin(), data.end(), std::back_inserter(dest)); trx.actions.push_back(act); test.set_transaction_headers(trx); trx.sign(test.get_private_key(N(inita), "active"), control->get_chain_id()); auto res = test.push_transaction(trx); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); }; BOOST_CHECK_EXCEPTION(test_require_notice(*this, raw_bytes, scope), unsatisfied_authorization, [](const unsatisfied_authorization& e) { return expect_assert_message(e, "transaction declares authority"); } ); // test require_auth BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "require_auth", {}), missing_auth_exception, [](const missing_auth_exception& e) { return expect_assert_message(e, "missing authority of"); } ); // test require_auth auto a3only = std::vector<permission_level>{{N(acc3), config::active_name}}; BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "require_auth", fc::raw::pack(a3only)), missing_auth_exception, [](const missing_auth_exception& e) { return expect_assert_message(e, "missing authority of"); } ); // test require_auth auto a4only = std::vector<permission_level>{{N(acc4), config::active_name}}; BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "require_auth", fc::raw::pack(a4only)), missing_auth_exception, [](const missing_auth_exception& e) { return expect_assert_message(e, "missing authority of"); } ); // test require_auth auto a3a4 = std::vector<permission_level>{{N(acc3), config::active_name}, {N(acc4), config::active_name}}; auto a3a4_scope = std::vector<account_name>{N(acc3), N(acc4)}; { signed_transaction trx; auto tm = test_api_action<TEST_METHOD("test_action", "require_auth")>{}; auto pl = a3a4; if (a3a4_scope.size() > 1) for (unsigned int i=1; i < a3a4_scope.size(); i++) pl.push_back({a3a4_scope[i], config::active_name}); action act(pl, tm); auto dat = fc::raw::pack(a3a4); vector<char>& dest = *(vector<char> *)(&act.data); std::copy(dat.begin(), dat.end(), std::back_inserter(dest)); act.authorization = {{N(testapi), config::active_name}, {N(acc3), config::active_name}, {N(acc4), config::active_name}}; trx.actions.push_back(act); set_transaction_headers(trx); trx.sign(get_private_key(N(testapi), "active"), control->get_chain_id()); trx.sign(get_private_key(N(acc3), "active"), control->get_chain_id()); trx.sign(get_private_key(N(acc4), "active"), control->get_chain_id()); auto res = push_transaction(trx); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); } uint64_t now = static_cast<uint64_t>( control->head_block_time().time_since_epoch().count() ); now += config::block_interval_us; CALL_TEST_FUNCTION( *this, "test_action", "test_current_time", fc::raw::pack(now)); // test current_time produce_block(); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_action", "test_current_time", fc::raw::pack(now) ), eosio_assert_message_exception, eosio_assert_message_is("tmp == current_time()") ); // test test_current_receiver CALL_TEST_FUNCTION( *this, "test_action", "test_current_receiver", fc::raw::pack(N(testapi))); // test send_action_sender CALL_TEST_FUNCTION( *this, "test_transaction", "send_action_sender", fc::raw::pack(N(testapi))); produce_block(); // test_publication_time uint64_t pub_time = static_cast<uint64_t>( control->head_block_time().time_since_epoch().count() ); pub_time += config::block_interval_us; CALL_TEST_FUNCTION( *this, "test_action", "test_publication_time", fc::raw::pack(pub_time) ); // test test_abort BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION( *this, "test_action", "test_abort", {} ), abort_called, [](const fc::exception& e) { return expect_assert_message(e, "abort() called"); } ); dummy_action da = { DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C }; CallAction(*this, da); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } // test require_recipient loop (doesn't cause infinite loop) BOOST_FIXTURE_TEST_CASE(require_notice_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(acc5) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); set_code( N(acc5), contracts::test_api_wasm() ); produce_blocks(1); // test require_notice signed_transaction trx; auto tm = test_api_action<TEST_METHOD( "test_action", "require_notice_tests" )>{}; action act( std::vector<permission_level>{{N( testapi ), config::active_name}}, tm ); trx.actions.push_back( act ); set_transaction_headers( trx ); trx.sign( get_private_key( N( testapi ), "active" ), control->get_chain_id() ); auto res = push_transaction( trx ); BOOST_CHECK_EQUAL( res->receipt->status, transaction_receipt::executed ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(ram_billing_in_notify_tests) { try { fc::temp_directory tempdir; validating_tester chain( tempdir, true ); chain.execute_setup_policy( setup_policy::preactivate_feature_and_new_bios ); const auto& pfm = chain.control->get_protocol_feature_manager(); const auto& d = pfm.get_builtin_digest(builtin_protocol_feature_t::action_return_value); // testapi requires this BOOST_REQUIRE(d); chain.preactivate_protocol_features( {*d} ); chain.produce_blocks(2); chain.create_account( N(testapi) ); chain.create_account( N(testapi2) ); chain.produce_blocks(10); chain.set_code( N(testapi), contracts::test_api_wasm() ); chain.produce_blocks(1); chain.set_code( N(testapi2), contracts::test_api_wasm() ); chain.produce_blocks(1); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( chain, "test_action", "test_ram_billing_in_notify", fc::raw::pack( ((unsigned __int128)N(testapi2).to_uint64_t() << 64) | N(testapi).to_uint64_t() ) ), subjective_block_production_exception, fc_exception_message_is("Cannot charge RAM to other accounts during notify.") ); CALL_TEST_FUNCTION( chain, "test_action", "test_ram_billing_in_notify", fc::raw::pack( ((unsigned __int128)N(testapi2).to_uint64_t() << 64) | 0 ) ); CALL_TEST_FUNCTION( chain, "test_action", "test_ram_billing_in_notify", fc::raw::pack( ((unsigned __int128)N(testapi2).to_uint64_t() << 64) | N(testapi2).to_uint64_t() ) ); BOOST_REQUIRE_EQUAL( chain.validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * context free action tests *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(cf_action_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(dummy) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); cf_action cfa; signed_transaction trx; set_transaction_headers(trx); // need at least one normal action BOOST_CHECK_EXCEPTION(push_transaction(trx), tx_no_auths, [](const fc::assert_exception& e) { return expect_assert_message(e, "transaction must have at least one authorization"); } ); action act({}, cfa); trx.context_free_actions.push_back(act); trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(100)); // verify payload matches context free data trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(200)); set_transaction_headers(trx); BOOST_CHECK_EXCEPTION(push_transaction(trx), tx_no_auths, [](const fc::exception& e) { return expect_assert_message(e, "transaction must have at least one authorization"); } ); trx.signatures.clear(); // add a normal action along with cfa dummy_action da = { DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C }; auto pl = vector<permission_level>{{N(testapi), config::active_name}}; action act1(pl, da); trx.actions.push_back(act1); set_transaction_headers(trx); // run normal passing case auto sigs = trx.sign(get_private_key(N(testapi), "active"), control->get_chain_id()); auto res = push_transaction(trx); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); // attempt to access context free api in non context free action da = { DUMMY_ACTION_DEFAULT_A, 200, DUMMY_ACTION_DEFAULT_C }; action act2(pl, da); trx.signatures.clear(); trx.actions.clear(); trx.actions.push_back(act2); set_transaction_headers(trx); // run (dummy_action.b = 200) case looking for invalid use of context_free api sigs = trx.sign(get_private_key(N(testapi), "active"), control->get_chain_id()); BOOST_CHECK_EXCEPTION(push_transaction(trx), unaccessible_api, [](const fc::exception& e) { return expect_assert_message(e, "this API may only be called from context_free apply"); } ); { // back to normal action action act1(pl, da); signed_transaction trx; trx.context_free_actions.push_back(act); trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(100)); // verify payload matches context free data trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(200)); trx.actions.push_back(act1); // attempt to access non context free api for (uint32_t i = 200; i <= 212; ++i) { trx.context_free_actions.clear(); trx.context_free_data.clear(); cfa.payload = i; cfa.cfd_idx = 1; action cfa_act({}, cfa); trx.context_free_actions.emplace_back(cfa_act); trx.signatures.clear(); set_transaction_headers(trx); sigs = trx.sign(get_private_key(N(testapi), "active"), control->get_chain_id()); BOOST_CHECK_EXCEPTION(push_transaction(trx), unaccessible_api, [](const fc::exception& e) { return expect_assert_message(e, "only context free api's can be used in this context" ); } ); } } produce_block(); // test send context free action auto ttrace = CALL_TEST_FUNCTION( *this, "test_transaction", "send_cf_action", {} ); BOOST_REQUIRE_EQUAL(ttrace->action_traces.size(), 2); BOOST_CHECK_EQUAL((int)(ttrace->action_traces[1].creator_action_ordinal), 1); BOOST_CHECK_EQUAL(ttrace->action_traces[1].receiver, account_name("dummy")); BOOST_CHECK_EQUAL(ttrace->action_traces[1].act.account, account_name("dummy")); BOOST_CHECK_EQUAL(ttrace->action_traces[1].act.name, account_name("event1")); BOOST_CHECK_EQUAL(ttrace->action_traces[1].act.authorization.size(), 0); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_transaction", "send_cf_action_fail", {} ), eosio_assert_message_exception, eosio_assert_message_is("context free actions cannot have authorizations") ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(cfa_tx_signature, TESTER) try { action cfa({}, cf_action()); signed_transaction tx1; tx1.context_free_data.emplace_back(fc::raw::pack<uint32_t>(100)); tx1.context_free_actions.push_back(cfa); set_transaction_headers(tx1); signed_transaction tx2; tx2.context_free_data.emplace_back(fc::raw::pack<uint32_t>(200)); tx2.context_free_actions.push_back(cfa); set_transaction_headers(tx2); const private_key_type& priv_key = get_private_key(name("dummy"), "active"); BOOST_TEST(tx1.sign(priv_key, control->get_chain_id()).to_string() != tx2.sign(priv_key, control->get_chain_id()).to_string()); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE(cfa_stateful_api, TESTER) try { create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); account_name a = N(testapi2); account_name creator = config::system_account_name; signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{creator,config::active_name}}, newaccount{ .creator = creator, .name = a, .owner = authority( get_public_key( a, "owner" ) ), .active = authority( get_public_key( a, "active" ) ) }); action act({}, test_api_action<TEST_METHOD("test_transaction", "stateful_api")>{}); trx.context_free_actions.push_back(act); set_transaction_headers(trx); trx.sign( get_private_key( creator, "active" ), control->get_chain_id() ); BOOST_CHECK_EXCEPTION(push_transaction( trx ), fc::exception, [&](const fc::exception &e) { return expect_assert_message(e, "only context free api's can be used in this context"); }); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE(deferred_cfa_failed, TESTER) try { create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); account_name a = N(testapi2); account_name creator = config::system_account_name; signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{creator,config::active_name}}, newaccount{ .creator = creator, .name = a, .owner = authority( get_public_key( a, "owner" ) ), .active = authority( get_public_key( a, "active" ) ) }); action act({}, test_api_action<TEST_METHOD("test_transaction", "stateful_api")>{}); trx.context_free_actions.push_back(act); set_transaction_headers(trx, 10, 2); trx.sign( get_private_key( creator, "active" ), control->get_chain_id() ); BOOST_CHECK_EXCEPTION(push_transaction( trx ), fc::exception, [&](const fc::exception &e) { return expect_assert_message(e, "only context free api's can be used in this context"); }); produce_blocks(10); // CFA failed, testapi2 not created create_account( N(testapi2) ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() BOOST_FIXTURE_TEST_CASE(deferred_cfa_success, TESTER) try { create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); account_name a = N(testapi2); account_name creator = config::system_account_name; signed_transaction trx; trx.actions.emplace_back( vector<permission_level>{{creator,config::active_name}}, newaccount{ .creator = creator, .name = a, .owner = authority( get_public_key( a, "owner" ) ), .active = authority( get_public_key( a, "active" ) ) }); action act({}, test_api_action<TEST_METHOD("test_transaction", "context_free_api")>{}); trx.context_free_actions.push_back(act); set_transaction_headers(trx, 10, 2); trx.sign( get_private_key( creator, "active" ), control->get_chain_id() ); auto trace = push_transaction( trx ); BOOST_REQUIRE(trace != nullptr); if (trace) { BOOST_REQUIRE_EQUAL(transaction_receipt_header::status_enum::delayed, trace->receipt->status); BOOST_REQUIRE_EQUAL(1, trace->action_traces.size()); } produce_blocks(10); // CFA success, testapi2 created BOOST_CHECK_EXCEPTION(create_account( N(testapi2) ), fc::exception, [&](const fc::exception &e) { return expect_assert_message(e, "Cannot create account named testapi2, as that name is already taken"); }); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() BOOST_AUTO_TEST_CASE(light_validation_skip_cfa) try { tester chain(setup_policy::full); std::vector<signed_block_ptr> blocks; blocks.push_back(chain.produce_block()); chain.create_account( N(testapi) ); chain.create_account( N(dummy) ); blocks.push_back(chain.produce_block()); chain.set_code( N(testapi), contracts::test_api_wasm() ); blocks.push_back(chain.produce_block()); cf_action cfa; signed_transaction trx; action act({}, cfa); trx.context_free_actions.push_back(act); trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(100)); // verify payload matches context free data trx.context_free_data.emplace_back(fc::raw::pack<uint32_t>(200)); // add a normal action along with cfa dummy_action da = { DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C }; action act1(vector<permission_level>{{N(testapi), config::active_name}}, da); trx.actions.push_back(act1); chain.set_transaction_headers(trx); // run normal passing case auto sigs = trx.sign(chain.get_private_key(N(testapi), "active"), chain.control->get_chain_id()); auto trace = chain.push_transaction(trx); blocks.push_back(chain.produce_block()); BOOST_REQUIRE(trace->receipt); BOOST_CHECK_EQUAL(trace->receipt->status, transaction_receipt::executed); BOOST_CHECK_EQUAL(2, trace->action_traces.size()); BOOST_CHECK(trace->action_traces.at(0).context_free); // cfa BOOST_CHECK_EQUAL("test\n", trace->action_traces.at(0).console); // cfa executed BOOST_CHECK(!trace->action_traces.at(1).context_free); // non-cfa BOOST_CHECK_EQUAL("", trace->action_traces.at(1).console); fc::temp_directory tempdir; auto conf_genesis = tester::default_config( tempdir ); auto& cfg = conf_genesis.first; cfg.trusted_producers = { N(eosio) }; // light validation tester other( conf_genesis.first, conf_genesis.second ); other.execute_setup_policy( setup_policy::full ); transaction_trace_ptr other_trace; auto cc = other.control->applied_transaction.connect( [&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if( t && t->id == trace->id ) { other_trace = t; } } ); for (auto& new_block : blocks) { other.push_block(new_block); } blocks.clear(); BOOST_REQUIRE(other_trace); BOOST_REQUIRE(other_trace->receipt); BOOST_CHECK_EQUAL(other_trace->receipt->status, transaction_receipt::executed); BOOST_CHECK(*trace->receipt == *other_trace->receipt); BOOST_CHECK_EQUAL(2, other_trace->action_traces.size()); BOOST_CHECK(other_trace->action_traces.at(0).context_free); // cfa BOOST_CHECK_EQUAL("", other_trace->action_traces.at(0).console); // cfa not executed for light validation (trusted producer) BOOST_CHECK_EQUAL(trace->action_traces.at(0).receipt->global_sequence, other_trace->action_traces.at(0).receipt->global_sequence); BOOST_CHECK_EQUAL(trace->action_traces.at(0).receipt->digest(), other_trace->action_traces.at(0).receipt->digest()); BOOST_CHECK(!other_trace->action_traces.at(1).context_free); // non-cfa BOOST_CHECK_EQUAL("", other_trace->action_traces.at(1).console); BOOST_CHECK_EQUAL(trace->action_traces.at(1).receipt->global_sequence, other_trace->action_traces.at(1).receipt->global_sequence); BOOST_CHECK_EQUAL(trace->action_traces.at(1).receipt->digest(), other_trace->action_traces.at(1).receipt->digest()); other.close(); } FC_LOG_AND_RETHROW() /************************************************************************************* * checktime_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(checktime_pass_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); // test checktime_pass CALL_TEST_FUNCTION( *this, "test_checktime", "checktime_pass", {}); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } template<class T> void call_test(TESTER& test, T ac, uint32_t billed_cpu_time_us , uint32_t max_cpu_usage_ms = 200, std::vector<char> payload = {} ) { signed_transaction trx; auto pl = vector<permission_level>{{N(testapi), config::active_name}}; action act(pl, ac); act.data = payload; trx.actions.push_back(act); test.set_transaction_headers(trx); auto sigs = trx.sign(test.get_private_key(N(testapi), "active"), test.control->get_chain_id()); flat_set<public_key_type> keys; trx.get_signature_keys(test.control->get_chain_id(), fc::time_point::maximum(), keys); auto res = test.push_transaction( trx, fc::time_point::now() + fc::milliseconds(max_cpu_usage_ms), billed_cpu_time_us ); BOOST_CHECK_EQUAL(res->receipt->status, transaction_receipt::executed); test.produce_block(); }; BOOST_AUTO_TEST_CASE(checktime_fail_tests) { try { TESTER t; t.produce_blocks(2); ilog( "create account" ); t.create_account( N(testapi) ); ilog( "set code" ); t.set_code( N(testapi), contracts::test_api_wasm() ); ilog( "produce block" ); t.produce_blocks(1); int64_t x; int64_t net; int64_t cpu; t.control->get_resource_limits_manager().get_account_limits( N(testapi), x, net, cpu ); wdump((net)(cpu)); #warning TODO call the contract before testing to cache it, and validate that it was cached BOOST_CHECK_EXCEPTION( call_test( t, test_api_action<TEST_METHOD("test_checktime", "checktime_failure")>{}, 5000, 200, fc::raw::pack(10000000000000000000ULL) ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( t, test_api_action<TEST_METHOD("test_checktime", "checktime_failure")>{}, 0, 200, fc::raw::pack(10000000000000000000ULL) ), tx_cpu_usage_exceeded, is_tx_cpu_usage_exceeded ); uint32_t time_left_in_block_us = config::default_max_block_cpu_usage - config::default_min_transaction_cpu_usage; std::string dummy_string = "nonce"; uint32_t increment = config::default_max_transaction_cpu_usage / 3; for( auto i = 0; time_left_in_block_us > 2*increment; ++i ) { t.push_dummy( N(testapi), dummy_string + std::to_string(i), increment ); time_left_in_block_us -= increment; } BOOST_CHECK_EXCEPTION( call_test( t, test_api_action<TEST_METHOD("test_checktime", "checktime_failure")>{}, 0, 200, fc::raw::pack(10000000000000000000ULL) ), block_cpu_usage_exceeded, is_block_cpu_usage_exceeded ); BOOST_REQUIRE_EQUAL( t.validate(), true ); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(checktime_intrinsic, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); produce_blocks(10); std::stringstream ss; ss << R"CONTRACT( (module (type $FUNCSIG$vij (func (param i32 i64))) (type $FUNCSIG$j (func (result i64))) (type $FUNCSIG$vjj (func (param i64 i64))) (type $FUNCSIG$vii (func (param i32 i32))) (type $FUNCSIG$i (func (result i32))) (type $FUNCSIG$iii (func (param i32 i32) (result i32))) (type $FUNCSIG$iiii (func (param i32 i32 i32) (result i32))) (type $FUNCSIG$vi (func (param i32))) (type $FUNCSIG$v (func )) (type $_1 (func (param i64 i64 i64))) (export "apply" (func $apply)) (import "env" "memmove" (func $memmove (param i32 i32 i32) (result i32))) (import "env" "printui" (func $printui (param i64))) (memory $0 1) (func $apply (type $_1) (param $0 i64) (param $1 i64) (param $2 i64) (drop (grow_memory (i32.const 527))) (call $printui (i64.const 11)) )CONTRACT"; for(unsigned int i = 0; i < 5000; ++i) { ss << R"CONTRACT( (drop (call $memmove (i32.const 1) (i32.const 9) (i32.const 33554432) )) )CONTRACT"; } ss<< "))"; set_code( N(testapi), ss.str().c_str() ); produce_blocks(1); //initialize cache BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("doesn't matter", "doesn't matter")>{}, 5000, 10 ), deadline_exception, is_deadline_exception ); #warning TODO validate that the contract was successfully cached //it will always call BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("doesn't matter", "doesn't matter")>{}, 5000, 10 ), deadline_exception, is_deadline_exception ); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(checktime_hashing_fail, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); //hit deadline exception, but cache the contract BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_sha1_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); #warning TODO validate that the contract was successfully cached //the contract should be cached, now we should get deadline_exception because of calls to checktime() from hashing function BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_sha1_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_assert_sha1_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_sha256_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_assert_sha256_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_sha512_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_assert_sha512_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_ripemd160_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_CHECK_EXCEPTION( call_test( *this, test_api_action<TEST_METHOD("test_checktime", "checktime_assert_ripemd160_failure")>{}, 5000, 3 ), deadline_exception, is_deadline_exception ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * transaction_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(transaction_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); produce_blocks(100); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); // test for zero auth { signed_transaction trx; auto tm = test_api_action<TEST_METHOD("test_action", "require_auth")>{}; action act({}, tm); trx.actions.push_back(act); set_transaction_headers(trx); BOOST_CHECK_EXCEPTION(push_transaction(trx), transaction_exception, [](const fc::exception& e) { return expect_assert_message(e, "transaction must have at least one authorization"); } ); } // test send_action CALL_TEST_FUNCTION(*this, "test_transaction", "send_action", {}); // test send_action_empty CALL_TEST_FUNCTION(*this, "test_transaction", "send_action_empty", {}); // test send_action_large BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION(*this, "test_transaction", "send_action_large", {}), inline_action_too_big, [](const fc::exception& e) { return expect_assert_message(e, "inline action too big"); } ); // test send_action_inline_fail BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION(*this, "test_transaction", "send_action_inline_fail", {}), eosio_assert_message_exception, eosio_assert_message_is("test_action::assert_false") ); // test send_transaction CALL_TEST_FUNCTION(*this, "test_transaction", "send_transaction", {}); // test send_transaction_empty BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION(*this, "test_transaction", "send_transaction_empty", {}), tx_no_auths, [](const fc::exception& e) { return expect_assert_message(e, "transaction must have at least one authorization"); } ); { produce_blocks(10); transaction_trace_ptr trace; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->receipt && t->receipt->status != transaction_receipt::executed) { trace = t; } } ); block_state_ptr bsp; auto c2 = control->accepted_block.connect([&](const block_state_ptr& b) { bsp = b; }); // test error handling on deferred transaction failure auto test_trace = CALL_TEST_FUNCTION(*this, "test_transaction", "send_transaction_trigger_error_handler", {}); BOOST_REQUIRE(trace); BOOST_CHECK_EQUAL(trace->receipt->status, transaction_receipt::soft_fail); std::set<transaction_id_type> block_ids; for( const auto& receipt : bsp->block->transactions ) { transaction_id_type id; if( receipt.trx.contains<packed_transaction>() ) { const auto& pt = receipt.trx.get<packed_transaction>(); id = pt.id(); } else { id = receipt.trx.get<transaction_id_type>(); } block_ids.insert( id ); } BOOST_CHECK_EQUAL(2, block_ids.size() ); // originating trx and deferred BOOST_CHECK_EQUAL(1, block_ids.count( test_trace->id ) ); // originating BOOST_CHECK( !test_trace->failed_dtrx_trace ); BOOST_CHECK_EQUAL(0, block_ids.count( trace->id ) ); // onerror id, not in block BOOST_CHECK_EQUAL(1, block_ids.count( trace->failed_dtrx_trace->id ) ); // deferred id since trace moved to failed_dtrx_trace BOOST_CHECK( trace->action_traces.at(0).act.name == N(onerror) ); c.disconnect(); c2.disconnect(); } // test test_transaction_size CALL_TEST_FUNCTION(*this, "test_transaction", "test_transaction_size", fc::raw::pack(54) ); // TODO: Need a better way to test this. // test test_read_transaction // this is a bit rough, but I couldn't figure out a better way to compare the hashes auto tx_trace = CALL_TEST_FUNCTION( *this, "test_transaction", "test_read_transaction", {} ); string sha_expect = tx_trace->id; BOOST_TEST_MESSAGE( "tx_trace->action_traces.front().console: = " << tx_trace->action_traces.front().console ); BOOST_TEST_MESSAGE( "sha_expect = " << sha_expect ); BOOST_CHECK_EQUAL(tx_trace->action_traces.front().console == sha_expect, true); // test test_tapos_block_num CALL_TEST_FUNCTION(*this, "test_transaction", "test_tapos_block_num", fc::raw::pack(control->head_block_num()) ); // test test_tapos_block_prefix CALL_TEST_FUNCTION(*this, "test_transaction", "test_tapos_block_prefix", fc::raw::pack(control->head_block_id()._hash[1]) ); // test send_action_recurse BOOST_CHECK_EXCEPTION(CALL_TEST_FUNCTION(*this, "test_transaction", "send_action_recurse", {}), eosio::chain::transaction_exception, [](const eosio::chain::transaction_exception& e) { return expect_assert_message(e, "max inline action depth per transaction reached"); } ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } BOOST_FIXTURE_TEST_CASE(deferred_transaction_tests, TESTER) { try { produce_blocks(2); create_accounts( {N(testapi), N(testapi2), N(alice)} ); set_code( N(testapi), contracts::test_api_wasm() ); set_code( N(testapi2), contracts::test_api_wasm() ); produce_blocks(1); //schedule { transaction_trace_ptr trace; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t->scheduled) { trace = t; } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction", {} ); BOOST_CHECK(!trace); produce_block( fc::seconds(2) ); //check that it gets executed afterwards BOOST_REQUIRE(trace); //confirm printed message BOOST_TEST(!trace->action_traces.empty()); BOOST_TEST(trace->action_traces.back().console == "deferred executed\n"); c.disconnect(); } produce_blocks(10); //schedule twice without replace_existing flag (second deferred transaction should replace first one) { transaction_trace_ptr trace; uint32_t count = 0; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->scheduled) { trace = t; ++count; } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction", {}); BOOST_CHECK_THROW(CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction", {}), deferred_tx_duplicate); produce_blocks( 3 ); //check that only one deferred transaction executed auto dtrxs = get_scheduled_transactions(); BOOST_CHECK_EQUAL(dtrxs.size(), 1); for (const auto& trx: dtrxs) { control->push_scheduled_transaction(trx, fc::time_point::maximum(), 0, false); } BOOST_CHECK_EQUAL(1, count); BOOST_REQUIRE(trace); BOOST_CHECK_EQUAL( 1, trace->action_traces.size() ); c.disconnect(); } produce_blocks(10); //schedule twice with replace_existing flag (second deferred transaction should replace first one) { transaction_trace_ptr trace; uint32_t count = 0; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->scheduled) { trace = t; ++count; } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction_replace", {}); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction_replace", {}); produce_blocks( 3 ); //check that only one deferred transaction executed auto billed_cpu_time_us = control->get_global_properties().configuration.min_transaction_cpu_usage; auto dtrxs = get_scheduled_transactions(); BOOST_CHECK_EQUAL(dtrxs.size(), 1); for (const auto& trx: dtrxs) { control->push_scheduled_transaction(trx, fc::time_point::maximum(), billed_cpu_time_us, true); } BOOST_CHECK_EQUAL(1, count); BOOST_CHECK(trace); BOOST_CHECK_EQUAL( 1, trace->action_traces.size() ); c.disconnect(); } produce_blocks(10); //schedule and cancel { transaction_trace_ptr trace; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->scheduled) { trace = t; } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_transaction", {}); CALL_TEST_FUNCTION(*this, "test_transaction", "cancel_deferred_transaction_success", {}); produce_block( fc::seconds(2) ); BOOST_CHECK(!trace); c.disconnect(); } produce_blocks(10); //cancel_deferred() return zero if no scheduled transaction found { CALL_TEST_FUNCTION(*this, "test_transaction", "cancel_deferred_transaction_not_found", {}); } produce_blocks(10); //repeated deferred transactions { vector<transaction_trace_ptr> traces; auto c = control->applied_transaction.connect([&](std::tuple<const transaction_trace_ptr&, const signed_transaction&> x) { auto& t = std::get<0>(x); if (t && t->scheduled) { traces.push_back( t ); } } ); CALL_TEST_FUNCTION(*this, "test_transaction", "repeat_deferred_transaction", fc::raw::pack( (uint32_t)5 ) ); produce_block(); c.disconnect(); BOOST_CHECK_EQUAL( traces.size(), 5 ); } produce_blocks(10); { // Trigger a tx which in turn sends a deferred tx with payer != receiver // Payer is alice in this case, this tx should fail since we don't have the authorization of alice dtt_action dtt_act1; dtt_act1.payer = N(alice).to_uint64_t(); BOOST_CHECK_THROW(CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act1)), action_validate_exception); // Send a tx which in turn sends a deferred tx with the deferred tx's receiver != this tx receiver // This will include the authorization of the receiver, and impose any related delay associated with the authority // We set the authorization delay to be 10 sec here, and since the deferred tx delay is set to be 5 sec, so this tx should fail dtt_action dtt_act2; dtt_act2.deferred_account = N(testapi2).to_uint64_t(); dtt_act2.permission_name = N(additional).to_uint64_t(); dtt_act2.delay_sec = 5; auto auth = authority(get_public_key(name("testapi"), name(dtt_act2.permission_name).to_string()), 10); auth.accounts.push_back( permission_level_weight{{N(testapi), config::eosio_code_name}, 1} ); push_action(config::system_account_name, updateauth::get_name(), name("testapi"), fc::mutable_variant_object() ("account", "testapi") ("permission", name(dtt_act2.permission_name)) ("parent", "active") ("auth", auth) ); push_action(config::system_account_name, linkauth::get_name(), name("testapi"), fc::mutable_variant_object() ("account", "testapi") ("code", name(dtt_act2.deferred_account)) ("type", name(dtt_act2.deferred_action)) ("requirement", name(dtt_act2.permission_name))); BOOST_CHECK_THROW(CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act2)), unsatisfied_authorization); // But if the deferred transaction has a sufficient delay, then it should work. dtt_act2.delay_sec = 10; CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act2)); // If the deferred tx receiver == this tx receiver, the authorization checking would originally be bypassed. // But not anymore. With the RESTRICT_ACTION_TO_SELF protocol feature activated, it should now objectively // fail because testapi@additional permission is not unilaterally satisfied by testapi@eosio.code. dtt_action dtt_act3; dtt_act3.deferred_account = N(testapi).to_uint64_t(); dtt_act3.permission_name = N(additional).to_uint64_t(); push_action(config::system_account_name, linkauth::get_name(), name("testapi"), fc::mutable_variant_object() ("account", "testapi") ("code", name(dtt_act3.deferred_account)) ("type", name(dtt_act3.deferred_action)) ("requirement", name(dtt_act3.permission_name))); BOOST_CHECK_THROW(CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act3)), unsatisfied_authorization); // But it should again work if the deferred transaction has a sufficient delay. dtt_act3.delay_sec = 10; CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act3)); // If we make testapi account to be priviledged account: // - the deferred transaction will work no matter who is the payer // - the deferred transaction will not care about the delay of the authorization push_action(config::system_account_name, N(setpriv), config::system_account_name, mutable_variant_object() ("account", "testapi") ("is_priv", 1)); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act1)); CALL_TEST_FUNCTION(*this, "test_transaction", "send_deferred_tx_with_dtt_action", fc::raw::pack(dtt_act2)); } BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(more_deferred_transaction_tests) { try { fc::temp_directory tempdir; validating_tester chain( tempdir, true ); chain.execute_setup_policy( setup_policy::preactivate_feature_and_new_bios ); const auto& pfm = chain.control->get_protocol_feature_manager(); auto d = pfm.get_builtin_digest( builtin_protocol_feature_t::replace_deferred ); BOOST_REQUIRE( d ); chain.preactivate_protocol_features( {*d} ); chain.produce_block(); const auto& index = chain.control->db().get_index<generated_transaction_multi_index,by_id>(); auto print_deferred = [&index]() { for( const auto& gto : index ) { wlog("id = ${id}, trx_id = ${trx_id}", ("id", gto.id)("trx_id", gto.trx_id)); } }; const auto& contract_account = account_name("tester"); const auto& test_account = account_name("alice"); chain.create_accounts( {contract_account, test_account} ); chain.set_code( contract_account, contracts::deferred_test_wasm() ); chain.set_abi( contract_account, contracts::deferred_test_abi().data() ); chain.produce_block(); BOOST_REQUIRE_EQUAL(0, index.size()); chain.push_action( contract_account, N(delayedcall), test_account, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 0) ("contract", contract_account) ("payload", 42) ("delay_sec", 1000) ("replace_existing", false) ); BOOST_REQUIRE_EQUAL(1, index.size()); print_deferred(); signed_transaction trx; trx.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 0) ("contract", contract_account) ("payload", 13) ("delay_sec", 1000) ("replace_existing", true) ) ); trx.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 1) ("contract", contract_account) ("payload", 42) ("delay_sec", 1000) ("replace_existing", false) ) ); trx.actions.emplace_back( chain.get_action( contract_account, N(fail), vector<permission_level>{}, fc::mutable_variant_object() ) ); chain.set_transaction_headers(trx); trx.sign( chain.get_private_key( test_account, "active" ), chain.control->get_chain_id() ); BOOST_REQUIRE_EXCEPTION( chain.push_transaction( trx ), eosio_assert_message_exception, eosio_assert_message_is("fail") ); BOOST_REQUIRE_EQUAL(1, index.size()); print_deferred(); chain.produce_blocks(2); chain.push_action( contract_account, N(delayedcall), test_account, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 1) ("contract", contract_account) ("payload", 101) ("delay_sec", 1000) ("replace_existing", false) ); chain.push_action( contract_account, N(delayedcall), test_account, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 2) ("contract", contract_account) ("payload", 102) ("delay_sec", 1000) ("replace_existing", false) ); BOOST_REQUIRE_EQUAL(3, index.size()); print_deferred(); BOOST_REQUIRE_THROW( chain.push_action( contract_account, N(delayedcall), test_account, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 2) ("contract", contract_account) ("payload", 101) ("delay_sec", 1000) ("replace_existing", true) ), fc::exception ); BOOST_REQUIRE_EQUAL(3, index.size()); print_deferred(); signed_transaction trx2; trx2.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 1) ("contract", contract_account) ("payload", 100) ("delay_sec", 1000) ("replace_existing", true) ) ); trx2.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 2) ("contract", contract_account) ("payload", 101) ("delay_sec", 1000) ("replace_existing", true) ) ); trx2.actions.emplace_back( chain.get_action( contract_account, N(delayedcall), vector<permission_level>{{test_account, config::active_name}}, fc::mutable_variant_object() ("payer", test_account) ("sender_id", 1) ("contract", contract_account) ("payload", 102) ("delay_sec", 1000) ("replace_existing", true) ) ); trx2.actions.emplace_back( chain.get_action( contract_account, N(fail), vector<permission_level>{}, fc::mutable_variant_object() ) ); chain.set_transaction_headers(trx2); trx2.sign( chain.get_private_key( test_account, "active" ), chain.control->get_chain_id() ); BOOST_REQUIRE_EXCEPTION( chain.push_transaction( trx2 ), eosio_assert_message_exception, eosio_assert_message_is("fail") ); BOOST_REQUIRE_EQUAL(3, index.size()); print_deferred(); BOOST_REQUIRE_EQUAL( chain.validate(), true ); } FC_LOG_AND_RETHROW() } template <uint64_t NAME> struct setprod_act { static account_name get_account() { return N(config::system_account_name); } static action_name get_name() { return action_name(NAME); } }; /************************************************************************************* * chain_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(chain_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); vector<account_name> producers = { N(inita), N(initb), N(initc), N(initd), N(inite), N(initf), N(initg), N(inith), N(initi), N(initj), N(initk), N(initl), N(initm), N(initn), N(inito), N(initp), N(initq), N(initr), N(inits), N(initt), N(initu) }; create_accounts( producers ); set_producers (producers ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(100); vector<account_name> prods( control->active_producers().producers.size() ); for ( uint32_t i = 0; i < prods.size(); i++ ) { prods[i] = control->active_producers().producers[i].producer_name; } CALL_TEST_FUNCTION( *this, "test_chain", "test_activeprods", fc::raw::pack(prods) ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } static const char get_active_producers_wast[] = R"=====( (module (import "env" "get_active_producers" (func $get_active_producers (param i32 i32) (result i32))) (memory 1) (func (export "apply") (param i64 i64 i64) (drop (call $get_active_producers (i32.const 1) (i32.const 0xFFFFFFFF) )) ) ) )====="; BOOST_FIXTURE_TEST_CASE(get_producers_tests, TESTER) { try { produce_blocks(2); create_account( N(getprods) ); set_code( N(getprods), get_active_producers_wast ); produce_block(); for(int i = 0; i < 100; ++i) { signed_transaction trx; trx.actions.push_back({ { { N(getprods), config::active_name } }, N(getprods), N(), bytes() }); set_transaction_headers(trx); trx.sign(get_private_key(N(getprods), "active"), control->get_chain_id()); BOOST_CHECK_THROW(push_transaction(trx), wasm_exception); produce_block(); } } FC_LOG_AND_RETHROW() } /************************************************************************************* * db_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(db_tests, TESTER) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(testapi2) ); produce_blocks(10); set_code( N(testapi), contracts::test_api_db_wasm() ); set_abi( N(testapi), contracts::test_api_db_abi().data() ); set_code( N(testapi2), contracts::test_api_db_wasm() ); set_abi( N(testapi2), contracts::test_api_db_abi().data() ); produce_blocks(1); push_action( N(testapi), N(pg), N(testapi), mutable_variant_object() ); // primary_i64_general push_action( N(testapi), N(pl), N(testapi), mutable_variant_object() ); // primary_i64_lowerbound push_action( N(testapi), N(pu), N(testapi), mutable_variant_object() ); // primary_i64_upperbound push_action( N(testapi), N(s1g), N(testapi), mutable_variant_object() ); // idx64_general push_action( N(testapi), N(s1l), N(testapi), mutable_variant_object() ); // idx64_lowerbound push_action( N(testapi), N(s1u), N(testapi), mutable_variant_object() ); // idx64_upperbound // Store value in primary table push_action( N(testapi), N(tia), N(testapi), mutable_variant_object() // test_invalid_access ("code", "testapi") ("val", 10) ("index", 0) ("store", true) ); // Attempt to change the value stored in the primary table under the code of N(testapi) BOOST_CHECK_EXCEPTION( push_action( N(testapi2), N(tia), N(testapi2), mutable_variant_object() ("code", "testapi") ("val", "20") ("index", 0) ("store", true) ), table_access_violation, fc_exception_message_is("db access violation") ); // Verify that the value has not changed. push_action( N(testapi), N(tia), N(testapi), mutable_variant_object() ("code", "testapi") ("val", 10) ("index", 0) ("store", false) ); // Store value in secondary table push_action( N(testapi), N(tia), N(testapi), mutable_variant_object() // test_invalid_access ("code", "testapi") ("val", 10) ("index", 1) ("store", true) ); // Attempt to change the value stored in the secondary table under the code of N(testapi) BOOST_CHECK_EXCEPTION( push_action( N(testapi2), N(tia), N(testapi2), mutable_variant_object() ("code", "testapi") ("val", "20") ("index", 1) ("store", true) ), table_access_violation, fc_exception_message_is("db access violation") ); // Verify that the value has not changed. push_action( N(testapi), N(tia), N(testapi), mutable_variant_object() ("code", "testapi") ("val", 10) ("index", 1) ("store", false) ); // idx_double_nan_create_fail BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnancreate), N(testapi), mutable_variant_object() ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); // idx_double_nan_modify_fail BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnanmodify), N(testapi), mutable_variant_object() ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); // idx_double_nan_lookup_fail BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnanlookup), N(testapi), mutable_variant_object() ("lookup_type", 0) // 0 for find ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnanlookup), N(testapi), mutable_variant_object() ("lookup_type", 1) // 1 for lower bound ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); BOOST_CHECK_EXCEPTION( push_action( N(testapi), N(sdnanlookup), N(testapi), mutable_variant_object() ("lookup_type", 2) // 2 for upper bound ), transaction_exception, fc_exception_message_is("NaN is not an allowed value for a secondary key") ); push_action( N(testapi), N(sk32align), N(testapi), mutable_variant_object() ); // misaligned_secondary_key256_tests BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * multi_index_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(multi_index_tests, TESTER) { try { produce_blocks(1); create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_multi_index_wasm() ); set_abi( N(testapi), contracts::test_api_multi_index_abi().data() ); produce_blocks(1); auto check_failure = [this]( action_name a, const char* expected_error_msg ) { BOOST_CHECK_EXCEPTION( push_action( N(testapi), a, N(testapi), {} ), eosio_assert_message_exception, eosio_assert_message_is( expected_error_msg ) ); }; push_action( N(testapi), N(s1g), N(testapi), {} ); // idx64_general push_action( N(testapi), N(s1store), N(testapi), {} ); // idx64_store_only push_action( N(testapi), N(s1check), N(testapi), {} ); // idx64_check_without_storing push_action( N(testapi), N(s2g), N(testapi), {} ); // idx128_general push_action( N(testapi), N(s2store), N(testapi), {} ); // idx128_store_only push_action( N(testapi), N(s2check), N(testapi), {} ); // idx128_check_without_storing push_action( N(testapi), N(s2autoinc), N(testapi), {} ); // idx128_autoincrement_test push_action( N(testapi), N(s2autoinc1), N(testapi), {} ); // idx128_autoincrement_test_part1 push_action( N(testapi), N(s2autoinc2), N(testapi), {} ); // idx128_autoincrement_test_part2 push_action( N(testapi), N(s3g), N(testapi), {} ); // idx256_general push_action( N(testapi), N(sdg), N(testapi), {} ); // idx_double_general push_action( N(testapi), N(sldg), N(testapi), {} ); // idx_long_double_general check_failure( N(s1pkend), "cannot increment end iterator" ); // idx64_pk_iterator_exceed_end check_failure( N(s1skend), "cannot increment end iterator" ); // idx64_sk_iterator_exceed_end check_failure( N(s1pkbegin), "cannot decrement iterator at beginning of table" ); // idx64_pk_iterator_exceed_begin check_failure( N(s1skbegin), "cannot decrement iterator at beginning of index" ); // idx64_sk_iterator_exceed_begin check_failure( N(s1pkref), "object passed to iterator_to is not in multi_index" ); // idx64_pass_pk_ref_to_other_table check_failure( N(s1skref), "object passed to iterator_to is not in multi_index" ); // idx64_pass_sk_ref_to_other_table check_failure( N(s1pkitrto), "object passed to iterator_to is not in multi_index" ); // idx64_pass_pk_end_itr_to_iterator_to check_failure( N(s1pkmodify), "cannot pass end iterator to modify" ); // idx64_pass_pk_end_itr_to_modify check_failure( N(s1pkerase), "cannot pass end iterator to erase" ); // idx64_pass_pk_end_itr_to_erase check_failure( N(s1skitrto), "object passed to iterator_to is not in multi_index" ); // idx64_pass_sk_end_itr_to_iterator_to check_failure( N(s1skmodify), "cannot pass end iterator to modify" ); // idx64_pass_sk_end_itr_to_modify check_failure( N(s1skerase), "cannot pass end iterator to erase" ); // idx64_pass_sk_end_itr_to_erase check_failure( N(s1modpk), "updater cannot change primary key when modifying an object" ); // idx64_modify_primary_key check_failure( N(s1exhaustpk), "next primary key in table is at autoincrement limit" ); // idx64_run_out_of_avl_pk check_failure( N(s1findfail1), "unable to find key" ); // idx64_require_find_fail check_failure( N(s1findfail2), "unable to find primary key in require_find" );// idx64_require_find_fail_with_msg check_failure( N(s1findfail3), "unable to find secondary key" ); // idx64_require_find_sk_fail check_failure( N(s1findfail4), "unable to find sec key" ); // idx64_require_find_sk_fail_with_msg push_action( N(testapi), N(s1skcache), N(testapi), {} ); // idx64_sk_cache_pk_lookup push_action( N(testapi), N(s1pkcache), N(testapi), {} ); // idx64_pk_cache_sk_lookup BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * crypto_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(crypto_tests, TESTER) { try { produce_block(); create_account(N(testapi) ); produce_block(); set_code(N(testapi), contracts::test_api_wasm() ); produce_block(); { signed_transaction trx; auto pl = vector<permission_level>{{N(testapi), config::active_name}}; action act(pl, test_api_action<TEST_METHOD("test_crypto", "test_recover_key")>{}); const auto priv_key = get_private_key(N(testapi), "active" ); const auto pub_key = priv_key.get_public_key(); auto hash = trx.sig_digest( control->get_chain_id() ); auto sig = priv_key.sign(hash); auto pk = fc::raw::pack( pub_key ); auto sigs = fc::raw::pack( sig ); vector<char> payload(8192); datastream<char*> payload_ds(payload.data(), payload.size()); fc::raw::pack(payload_ds, hash, (uint32_t)pk.size(), (uint32_t)sigs.size() ); payload_ds.write(pk.data(), pk.size() ); payload_ds.write(sigs.data(), sigs.size()); payload.resize(payload_ds.tellp()); //No Error Here CALL_TEST_FUNCTION( *this, "test_crypto", "test_recover_key", payload ); // Error Here CALL_TEST_FUNCTION( *this, "test_crypto", "test_recover_key_assert_true", payload ); payload[payload.size()-1] = 0; BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_crypto", "test_recover_key_assert_false", payload ), crypto_api_exception, fc_exception_message_is("Error expected key different than recovered key") ); } { signed_transaction trx; auto pl = vector<permission_level>{{N(testapi), config::active_name}}; action act(pl, test_api_action<TEST_METHOD("test_crypto", "test_recover_key_partial")>{}); // construct a mock WebAuthN pubkey and signature, as it is the only type that would be variable-sized const auto priv_key = get_private_key<mock::webauthn_private_key>(N(testapi), "active" ); const auto pub_key = priv_key.get_public_key(); auto hash = trx.sig_digest( control->get_chain_id() ); auto sig = priv_key.sign(hash); auto pk = fc::raw::pack( pub_key ); auto sigs = fc::raw::pack( sig ); vector<char> payload(8192); datastream<char*> payload_ds(payload.data(), payload.size()); fc::raw::pack(payload_ds, hash, (uint32_t)pk.size(), (uint32_t)sigs.size() ); payload_ds.write(pk.data(), pk.size() ); payload_ds.write(sigs.data(), sigs.size()); payload.resize(payload_ds.tellp()); //No Error Here CALL_TEST_FUNCTION( *this, "test_crypto", "test_recover_key_partial", payload ); } CALL_TEST_FUNCTION( *this, "test_crypto", "test_sha1", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "test_sha256", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "test_sha512", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "test_ripemd160", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "sha1_no_data", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "sha256_no_data", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "sha512_no_data", {} ); CALL_TEST_FUNCTION( *this, "test_crypto", "ripemd160_no_data", {} ); CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION( *this, "test_crypto", "assert_sha256_false", {}, crypto_api_exception, "hash mismatch" ); CALL_TEST_FUNCTION( *this, "test_crypto", "assert_sha256_true", {} ); CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION( *this, "test_crypto", "assert_sha1_false", {}, crypto_api_exception, "hash mismatch" ); CALL_TEST_FUNCTION( *this, "test_crypto", "assert_sha1_true", {} ); CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION( *this, "test_crypto", "assert_sha512_false", {}, crypto_api_exception, "hash mismatch" ); CALL_TEST_FUNCTION( *this, "test_crypto", "assert_sha512_true", {} ); CALL_TEST_FUNCTION_AND_CHECK_EXCEPTION( *this, "test_crypto", "assert_ripemd160_false", {}, crypto_api_exception, "hash mismatch" ); CALL_TEST_FUNCTION( *this, "test_crypto", "assert_ripemd160_true", {} ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * print_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(print_tests, TESTER) { try { produce_blocks(2); create_account(N(testapi) ); produce_blocks(1000); set_code(N(testapi), contracts::test_api_wasm() ); produce_blocks(1000); string captured = ""; // test prints auto tx1_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_prints", {} ); auto tx1_act_cnsl = tx1_trace->action_traces.front().console; BOOST_CHECK_EQUAL(tx1_act_cnsl == "abcefg", true); // test prints_l auto tx2_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_prints_l", {} ); auto tx2_act_cnsl = tx2_trace->action_traces.front().console; BOOST_CHECK_EQUAL(tx2_act_cnsl == "abatest", true); // test printi auto tx3_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printi", {} ); auto tx3_act_cnsl = tx3_trace->action_traces.front().console; BOOST_CHECK_EQUAL( tx3_act_cnsl.substr(0,1), I64Str(0) ); BOOST_CHECK_EQUAL( tx3_act_cnsl.substr(1,6), I64Str(556644) ); BOOST_CHECK_EQUAL( tx3_act_cnsl.substr(7, std::string::npos), I64Str(-1) ); // test printui auto tx4_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printui", {} ); auto tx4_act_cnsl = tx4_trace->action_traces.front().console; BOOST_CHECK_EQUAL( tx4_act_cnsl.substr(0,1), U64Str(0) ); BOOST_CHECK_EQUAL( tx4_act_cnsl.substr(1,6), U64Str(556644) ); BOOST_CHECK_EQUAL( tx4_act_cnsl.substr(7, std::string::npos), U64Str(-1) ); // "18446744073709551615" // test printn auto tx5_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printn", {} ); auto tx5_act_cnsl = tx5_trace->action_traces.front().console; BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(0,1), "1" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(1,1), "5" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(2,1), "a" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(3,1), "z" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(4,3), "abc" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(7,3), "123" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(10,7), "abc.123" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(17,7), "123.abc" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(24,13), "12345abcdefgj" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(37,13), "ijklmnopqrstj" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(50,13), "vwxyz.12345aj" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(63, 13), "111111111111j" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(76, 13), "555555555555j" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(89, 13), "aaaaaaaaaaaaj" ); BOOST_CHECK_EQUAL( tx5_act_cnsl.substr(102,13), "zzzzzzzzzzzzj" ); // test printi128 auto tx6_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printi128", {} ); auto tx6_act_cnsl = tx6_trace->action_traces.front().console; size_t start = 0; size_t end = tx6_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx6_act_cnsl.substr(start, end-start), U128Str(1) ); start = end + 1; end = tx6_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx6_act_cnsl.substr(start, end-start), U128Str(0) ); start = end + 1; end = tx6_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx6_act_cnsl.substr(start, end-start), "-" + U128Str(static_cast<unsigned __int128>(std::numeric_limits<__int128>::lowest())) ); start = end + 1; end = tx6_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx6_act_cnsl.substr(start, end-start), "-" + U128Str(87654323456) ); // test printui128 auto tx7_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printui128", {} ); auto tx7_act_cnsl = tx7_trace->action_traces.front().console; start = 0; end = tx7_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx7_act_cnsl.substr(start, end-start), U128Str(std::numeric_limits<unsigned __int128>::max()) ); start = end + 1; end = tx7_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx7_act_cnsl.substr(start, end-start), U128Str(0) ); start = end + 1; end = tx7_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx7_act_cnsl.substr(start, end-start), U128Str(87654323456) ); // test printsf auto tx8_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printsf", {} ); auto tx8_act_cnsl = tx8_trace->action_traces.front().console; start = 0; end = tx8_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx8_act_cnsl.substr(start, end-start), "5.000000e-01" ); start = end + 1; end = tx8_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx8_act_cnsl.substr(start, end-start), "-3.750000e+00" ); start = end + 1; end = tx8_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx8_act_cnsl.substr(start, end-start), "6.666667e-07" ); // test printdf auto tx9_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printdf", {} ); auto tx9_act_cnsl = tx9_trace->action_traces.front().console; start = 0; end = tx9_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx9_act_cnsl.substr(start, end-start), "5.000000000000000e-01" ); start = end + 1; end = tx9_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx9_act_cnsl.substr(start, end-start), "-3.750000000000000e+00" ); start = end + 1; end = tx9_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx9_act_cnsl.substr(start, end-start), "6.666666666666666e-07" ); // test printqf #ifdef __x86_64__ std::string expect1 = "5.000000000000000000e-01"; std::string expect2 = "-3.750000000000000000e+00"; std::string expect3 = "6.666666666666666667e-07"; #else std::string expect1 = "5.000000000000000e-01"; std::string expect2 = "-3.750000000000000e+00"; std::string expect3 = "6.666666666666667e-07"; #endif auto tx10_trace = CALL_TEST_FUNCTION( *this, "test_print", "test_printqf", {} ); auto tx10_act_cnsl = tx10_trace->action_traces.front().console; start = 0; end = tx10_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx10_act_cnsl.substr(start, end-start), expect1 ); start = end + 1; end = tx10_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx10_act_cnsl.substr(start, end-start), expect2 ); start = end + 1; end = tx10_act_cnsl.find('\n', start); BOOST_CHECK_EQUAL( tx10_act_cnsl.substr(start, end-start), expect3 ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * types_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(types_tests, TESTER) { try { produce_blocks(1000); create_account( N(testapi) ); produce_blocks(1000); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1000); CALL_TEST_FUNCTION( *this, "test_types", "types_size", {}); CALL_TEST_FUNCTION( *this, "test_types", "char_to_symbol", {}); CALL_TEST_FUNCTION( *this, "test_types", "string_to_name", {}); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * permission_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(permission_tests, TESTER) { try { produce_blocks(1); create_account( N(testapi) ); produce_blocks(1); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); auto get_result_int64 = [&]() -> int64_t { const auto& db = control->db(); const auto* t_id = db.find<table_id_object, by_code_scope_table>(boost::make_tuple(N(testapi), N(testapi), N(testapi))); FC_ASSERT(t_id != 0, "Table id not found"); const auto& idx = db.get_index<key_value_index, by_scope_primary>(); auto itr = idx.lower_bound(boost::make_tuple(t_id->id)); FC_ASSERT( itr != idx.end() && itr->t_id == t_id->id, "lower_bound failed"); FC_ASSERT( 0 != itr->value.size(), "unexpected result size"); return *reinterpret_cast<const int64_t *>(itr->value.data()); }; CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(active), .pubkeys = { get_public_key(N(testapi), "active") } }) ); BOOST_CHECK_EQUAL( int64_t(1), get_result_int64() ); CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(active), .pubkeys = { public_key_type(string("EOS7GfRtyDWWgxV88a5TRaYY59XmHptyfjsFmHHfioGNJtPjpSmGX")) } }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(active), .pubkeys = { get_public_key(N(testapi), "active"), public_key_type(string("EOS7GfRtyDWWgxV88a5TRaYY59XmHptyfjsFmHHfioGNJtPjpSmGX")) } }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); // Failure due to irrelevant signatures CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(noname), .permission = N(active), .pubkeys = { get_public_key(N(testapi), "active") } }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(active), .pubkeys = {} }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); CALL_TEST_FUNCTION( *this, "test_permission", "check_authorization", fc::raw::pack( check_auth { .account = N(testapi), .permission = N(noname), .pubkeys = { get_public_key(N(testapi), "active") } }) ); BOOST_CHECK_EQUAL( int64_t(0), get_result_int64() ); } FC_LOG_AND_RETHROW() } #if 0 /************************************************************************************* * privileged_tests test case *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(privileged_tests, tester) { try { produce_blocks(2); create_account( N(testapi) ); create_account( N(acc1) ); produce_blocks(100); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); { signed_transaction trx; auto pl = vector<permission_level>{{config::system_account_name, config::active_name}}; action act(pl, test_chain_action<N(setprods)>()); vector<producer_key> prod_keys = { { N(inita), get_public_key( N(inita), "active" ) }, { N(initb), get_public_key( N(initb), "active" ) }, { N(initc), get_public_key( N(initc), "active" ) }, { N(initd), get_public_key( N(initd), "active" ) }, { N(inite), get_public_key( N(inite), "active" ) }, { N(initf), get_public_key( N(initf), "active" ) }, { N(initg), get_public_key( N(initg), "active" ) }, { N(inith), get_public_key( N(inith), "active" ) }, { N(initi), get_public_key( N(initi), "active" ) }, { N(initj), get_public_key( N(initj), "active" ) }, { N(initk), get_public_key( N(initk), "active" ) }, { N(initl), get_public_key( N(initl), "active" ) }, { N(initm), get_public_key( N(initm), "active" ) }, { N(initn), get_public_key( N(initn), "active" ) }, { N(inito), get_public_key( N(inito), "active" ) }, { N(initp), get_public_key( N(initp), "active" ) }, { N(initq), get_public_key( N(initq), "active" ) }, { N(initr), get_public_key( N(initr), "active" ) }, { N(inits), get_public_key( N(inits), "active" ) }, { N(initt), get_public_key( N(initt), "active" ) }, { N(initu), get_public_key( N(initu), "active" ) } }; vector<char> data = fc::raw::pack(uint32_t(0)); vector<char> keys = fc::raw::pack(prod_keys); data.insert( data.end(), keys.begin(), keys.end() ); act.data = data; trx.actions.push_back(act); set_tapos(trx); auto sigs = trx.sign(get_private_key(config::system_account_name, "active"), control->get_chain_id()); trx.get_signature_keys(control->get_chain_id() ); auto res = push_transaction(trx); BOOST_CHECK_EQUAL(res.status, transaction_receipt::executed); } CALL_TEST_FUNCTION( *this, "test_privileged", "test_is_privileged", {} ); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_privileged", "test_is_privileged", {} ), transaction_exception, [](const fc::exception& e) { return expect_assert_message(e, "context.privileged: testapi does not have permission to call this API"); } ); } FC_LOG_AND_RETHROW() } #endif /************************************************************************************* * real_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(datastream_tests, TESTER) { try { produce_blocks(1000); create_account(N(testapi) ); produce_blocks(1000); set_code(N(testapi), contracts::test_api_wasm() ); produce_blocks(1000); CALL_TEST_FUNCTION( *this, "test_datastream", "test_basic", {} ); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * permission_usage_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(permission_usage_tests, TESTER) { try { produce_block(); create_accounts( {N(testapi), N(alice), N(bob)} ); produce_block(); set_code(N(testapi), contracts::test_api_wasm() ); produce_block(); push_reqauth( N(alice), {{N(alice), config::active_name}}, {get_private_key(N(alice), "active")} ); CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(alice), config::active_name, control->pending_block_time() }) ); // Fails because the last used time is updated after the transaction executes. BOOST_CHECK_THROW( CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(testapi), config::active_name, control->head_block_time() + fc::milliseconds(config::block_interval_ms) }) ), eosio_assert_message_exception ); produce_blocks(5); set_authority( N(bob), N(perm1), authority( get_private_key(N(bob), "perm1").get_public_key() ) ); push_action(config::system_account_name, linkauth::get_name(), N(bob), fc::mutable_variant_object() ("account", "bob") ("code", "eosio") ("type", "reqauth") ("requirement", "perm1") ); auto permission_creation_time = control->pending_block_time(); produce_blocks(5); CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(bob), N(perm1), permission_creation_time }) ); produce_blocks(5); push_reqauth( N(bob), {{N(bob), N(perm1)}}, {get_private_key(N(bob), "perm1")} ); auto perm1_last_used_time = control->pending_block_time(); CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(bob), config::active_name, permission_creation_time }) ); BOOST_CHECK_THROW( CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(bob), N(perm1), permission_creation_time }) ), eosio_assert_message_exception ); CALL_TEST_FUNCTION( *this, "test_permission", "test_permission_last_used", fc::raw::pack(test_permission_last_used_action{ N(bob), N(perm1), perm1_last_used_time }) ); produce_block(); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * account_creation_time_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(account_creation_time_tests, TESTER) { try { produce_block(); create_account( N(testapi) ); produce_block(); set_code(N(testapi), contracts::test_api_wasm() ); produce_block(); create_account( N(alice) ); auto alice_creation_time = control->pending_block_time(); produce_blocks(10); CALL_TEST_FUNCTION( *this, "test_permission", "test_account_creation_time", fc::raw::pack(test_permission_last_used_action{ N(alice), config::active_name, alice_creation_time }) ); produce_block(); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * extended_symbol_api_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(extended_symbol_api_tests, TESTER) { try { name n0{"1"}; name n1{"5"}; name n2{"a"}; name n3{"z"}; name n4{"111111111111j"}; name n5{"555555555555j"}; name n6{"zzzzzzzzzzzzj"}; symbol s0{4, ""}; symbol s1{5, "Z"}; symbol s2{10, "AAAAA"}; symbol s3{10, "ZZZZZ"}; // Test comparison operators BOOST_REQUIRE( (extended_symbol{s0, n0} == extended_symbol{s0, n0}) ); BOOST_REQUIRE( (extended_symbol{s1, n3} == extended_symbol{s1, n3}) ); BOOST_REQUIRE( (extended_symbol{s2, n4} == extended_symbol{s2, n4}) ); BOOST_REQUIRE( (extended_symbol{s3, n6} == extended_symbol{s3, n6}) ); BOOST_REQUIRE( (extended_symbol{s0, n0} != extended_symbol{s1, n0}) ); BOOST_REQUIRE( (extended_symbol{s0, n0} != extended_symbol{s0, n1}) ); BOOST_REQUIRE( (extended_symbol{s1, n1} != extended_symbol{s2, n2}) ); BOOST_REQUIRE( (extended_symbol{s0, n0} < extended_symbol{s1, n0}) ); BOOST_REQUIRE( (extended_symbol{s0, n0} < extended_symbol{s0, n1}) ); BOOST_REQUIRE( (extended_symbol{s0, n5} < extended_symbol{s0, n3}) ); BOOST_REQUIRE( (extended_symbol{s2, n0} < extended_symbol{s3, n0}) ); } FC_LOG_AND_RETHROW() } /************************************************************************************* * eosio_assert_code_tests test cases *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(eosio_assert_code_tests, TESTER) { try { produce_block(); create_account( N(testapi) ); produce_block(); set_code(N(testapi), contracts::test_api_wasm() ); const char* abi_string = R"=====( { "version": "eosio::abi/1.0", "types": [], "structs": [], "actions": [], "tables": [], "ricardian_clauses": [], "error_messages": [ {"error_code": 1, "error_msg": "standard error message" }, {"error_code": 42, "error_msg": "The answer to life, the universe, and everything."} ] "abi_extensions": [] } )====="; set_abi( N(testapi), abi_string ); auto var = fc::json::from_string(abi_string); abi_serializer abis(var.as<abi_def>(), abi_serializer::create_yield_function( abi_serializer_max_time )); produce_blocks(10); BOOST_CHECK_EXCEPTION( CALL_TEST_FUNCTION( *this, "test_action", "test_assert_code", fc::raw::pack((uint64_t)42) ), eosio_assert_code_exception, eosio_assert_code_is(42) ); auto trace = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_assert_code", fc::raw::pack((uint64_t)42) ); BOOST_REQUIRE( trace ); BOOST_REQUIRE( trace->except ); BOOST_REQUIRE( trace->error_code ); BOOST_REQUIRE_EQUAL( *trace->error_code, 42 ); BOOST_REQUIRE_EQUAL( trace->action_traces.size(), 1 ); BOOST_REQUIRE( trace->action_traces[0].except ); BOOST_REQUIRE( trace->action_traces[0].error_code ); BOOST_REQUIRE_EQUAL( *trace->action_traces[0].error_code, 42 ); produce_block(); auto omsg1 = abis.get_error_message(1); BOOST_REQUIRE_EQUAL( omsg1.valid(), true ); BOOST_CHECK_EQUAL( *omsg1, "standard error message" ); auto omsg2 = abis.get_error_message(2); BOOST_CHECK_EQUAL( omsg2.valid(), false ); auto omsg3 = abis.get_error_message(42); BOOST_REQUIRE_EQUAL( omsg3.valid(), true ); BOOST_CHECK_EQUAL( *omsg3, "The answer to life, the universe, and everything." ); produce_block(); auto trace2 = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_assert_code", fc::raw::pack( static_cast<uint64_t>(system_error_code::generic_system_error) ) ); BOOST_REQUIRE( trace2 ); BOOST_REQUIRE( trace2->except ); BOOST_REQUIRE( trace2->error_code ); BOOST_REQUIRE_EQUAL( *trace2->error_code, static_cast<uint64_t>(system_error_code::contract_restricted_error_code) ); BOOST_REQUIRE_EQUAL( trace2->action_traces.size(), 1 ); BOOST_REQUIRE( trace2->action_traces[0].except ); BOOST_REQUIRE( trace2->action_traces[0].error_code ); BOOST_REQUIRE_EQUAL( *trace2->action_traces[0].error_code, static_cast<uint64_t>(system_error_code::contract_restricted_error_code) ); produce_block(); BOOST_REQUIRE_EQUAL( validate(), true ); } FC_LOG_AND_RETHROW() } /************************************************************************************* + * action_ordinal_test test cases + *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_ordinal_test, TESTER) { try { produce_blocks(1); create_account(N(testapi) ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(bob) ); set_code( N(bob), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(charlie) ); set_code( N(charlie), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(david) ); set_code( N(david), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(erin) ); set_code( N(erin), contracts::test_api_wasm() ); produce_blocks(1); // prove act digest auto pad = [](const digest_type& expected_act_digest, const action& act, const vector<char>& act_output) { std::vector<char> buf1; buf1.resize(64); datastream<char*> ds(buf1.data(), buf1.size()); { std::vector<char> buf2; const action_base* act_base = &act; buf2.resize(fc::raw::pack_size(*act_base)); datastream<char*> ds2(buf2.data(), buf2.size()); fc::raw::pack(ds2, *act_base); fc::raw::pack(ds, sha256::hash(buf2.data(), buf2.size())); } { std::vector<char> buf2; buf2.resize(fc::raw::pack_size(act.data) + fc::raw::pack_size(act_output)); datastream<char*> ds2(buf2.data(), buf2.size()); fc::raw::pack(ds2, act.data); fc::raw::pack(ds2, act_output); fc::raw::pack(ds, sha256::hash(buf2.data(), buf2.size())); } digest_type computed_act_digest = sha256::hash(buf1.data(), ds.tellp()); return expected_act_digest == computed_act_digest; }; transaction_trace_ptr txn_trace = CALL_TEST_FUNCTION_SCOPE( *this, "test_action", "test_action_ordinal1", {}, vector<account_name>{ N(testapi)}); BOOST_REQUIRE_EQUAL( validate(), true ); BOOST_REQUIRE_EQUAL( txn_trace != nullptr, true); BOOST_REQUIRE_EQUAL( txn_trace->action_traces.size(), 11); auto &atrace = txn_trace->action_traces; BOOST_REQUIRE_EQUAL((int)atrace[0].action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[0].creator_action_ordinal, 0); BOOST_REQUIRE_EQUAL((int)atrace[0].closest_unnotified_ancestor_action_ordinal, 0); BOOST_REQUIRE_EQUAL(atrace[0].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[0].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<unsigned_int>(atrace[0].return_value), unsigned_int(1) ); BOOST_REQUIRE(pad(atrace[0].receipt->act_digest, atrace[0].act, atrace[0].return_value)); int start_gseq = atrace[0].receipt->global_sequence; BOOST_REQUIRE_EQUAL((int)atrace[1].action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[1].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[1].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[1].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[1].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[1].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[1].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[1].return_value), "bob" ); BOOST_REQUIRE(pad(atrace[1].receipt->act_digest, atrace[1].act, atrace[1].return_value)); BOOST_REQUIRE_EQUAL(atrace[1].receipt->global_sequence, start_gseq + 1); BOOST_REQUIRE_EQUAL((int)atrace[2].action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[2].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[2].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[2].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[2].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<name>(atrace[2].return_value), name("five") ); BOOST_REQUIRE(pad(atrace[2].receipt->act_digest, atrace[2].act, atrace[2].return_value)); BOOST_REQUIRE_EQUAL(atrace[2].receipt->global_sequence, start_gseq + 4); BOOST_REQUIRE_EQUAL((int)atrace[3].action_ordinal, 4); BOOST_REQUIRE_EQUAL((int)atrace[3].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[3].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[3].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.name, TEST_METHOD("test_action", "test_action_ordinal3")); BOOST_REQUIRE_EQUAL(atrace[3].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<unsigned_int>(atrace[3].return_value), unsigned_int(9) ); BOOST_REQUIRE(pad(atrace[3].receipt->act_digest, atrace[3].act, atrace[3].return_value)); BOOST_REQUIRE_EQUAL(atrace[3].receipt->global_sequence, start_gseq + 8); BOOST_REQUIRE_EQUAL((int)atrace[4].action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[4].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[4].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[4].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[4].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[4].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[4].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[4].return_value), "charlie" ); BOOST_REQUIRE(pad(atrace[4].receipt->act_digest, atrace[4].act, atrace[4].return_value)); BOOST_REQUIRE_EQUAL(atrace[4].receipt->global_sequence, start_gseq + 2); BOOST_REQUIRE_EQUAL((int)atrace[5].action_ordinal, 6); BOOST_REQUIRE_EQUAL((int)atrace[5].creator_action_ordinal, 2); BOOST_REQUIRE_EQUAL((int)atrace[5].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[5].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.account, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.name, TEST_METHOD("test_action", "test_action_ordinal_foo")); BOOST_REQUIRE_EQUAL(atrace[5].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<double>(atrace[5].return_value), 13.23 ); BOOST_REQUIRE(pad(atrace[5].receipt->act_digest, atrace[5].act, atrace[5].return_value)); BOOST_REQUIRE_EQUAL(atrace[5].receipt->global_sequence, start_gseq + 9); BOOST_REQUIRE_EQUAL((int)atrace[6].action_ordinal, 7); BOOST_REQUIRE_EQUAL((int)atrace[6].creator_action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[6].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[6].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[6].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[6].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[6].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[6].return_value), "david" ); BOOST_REQUIRE(pad(atrace[6].receipt->act_digest, atrace[6].act, atrace[6].return_value)); BOOST_REQUIRE_EQUAL(atrace[6].receipt->global_sequence, start_gseq + 3); BOOST_REQUIRE_EQUAL((int)atrace[7].action_ordinal, 8); BOOST_REQUIRE_EQUAL((int)atrace[7].creator_action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[7].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[7].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.account, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.name, TEST_METHOD("test_action", "test_action_ordinal_bar")); BOOST_REQUIRE_EQUAL(atrace[7].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<float>(atrace[7].return_value), 11.42f ); BOOST_REQUIRE(pad(atrace[7].receipt->act_digest, atrace[7].act, atrace[7].return_value)); BOOST_REQUIRE_EQUAL(atrace[7].receipt->global_sequence, start_gseq + 10); BOOST_REQUIRE_EQUAL((int)atrace[8].action_ordinal, 9); BOOST_REQUIRE_EQUAL((int)atrace[8].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[8].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[8].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[8].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[8].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[8].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<bool>(atrace[8].return_value), true ); BOOST_REQUIRE(pad(atrace[8].receipt->act_digest, atrace[8].act, atrace[8].return_value)); BOOST_REQUIRE_EQUAL(atrace[8].receipt->global_sequence, start_gseq + 5); BOOST_REQUIRE_EQUAL((int)atrace[9].action_ordinal, 10); BOOST_REQUIRE_EQUAL((int)atrace[9].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[9].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[9].receiver, N(erin)); BOOST_REQUIRE_EQUAL(atrace[9].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[9].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[9].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<signed_int>(atrace[9].return_value), signed_int(7) ); BOOST_REQUIRE(pad(atrace[9].receipt->act_digest, atrace[9].act, atrace[9].return_value)); BOOST_REQUIRE_EQUAL(atrace[9].receipt->global_sequence, start_gseq + 6); BOOST_REQUIRE_EQUAL((int)atrace[10].action_ordinal, 11); BOOST_REQUIRE_EQUAL((int)atrace[10].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[10].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[10].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[10].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[10].act.name, TEST_METHOD("test_action", "test_action_ordinal4")); BOOST_REQUIRE_EQUAL(atrace[10].receipt.valid(), true); BOOST_REQUIRE_EQUAL(atrace[10].return_value.size(), 0 ); BOOST_REQUIRE_EQUAL(atrace[10].receipt->global_sequence, start_gseq + 7); } FC_LOG_AND_RETHROW() } /************************************************************************************* + * action_ordinal_failtest1 test cases + *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_ordinal_failtest1, TESTER) { try { produce_blocks(1); create_account(N(testapi) ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(bob) ); set_code( N(bob), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(charlie) ); set_code( N(charlie), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(david) ); set_code( N(david), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(erin) ); set_code( N(erin), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(fail1) ); // <- make first action fails in the middle produce_blocks(1); transaction_trace_ptr txn_trace = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_action_ordinal1", {}); BOOST_REQUIRE_EQUAL( validate(), true ); BOOST_REQUIRE_EQUAL( txn_trace != nullptr, true); BOOST_REQUIRE_EQUAL( txn_trace->action_traces.size(), 3); auto &atrace = txn_trace->action_traces; // fails here after creating one notify action and one inline action BOOST_REQUIRE_EQUAL((int)atrace[0].action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[0].creator_action_ordinal, 0); BOOST_REQUIRE_EQUAL((int)atrace[0].closest_unnotified_ancestor_action_ordinal, 0); BOOST_REQUIRE_EQUAL(atrace[0].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[0].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[0].except.valid(), true); BOOST_REQUIRE_EQUAL(atrace[0].except->code(), 3050003); // not executed BOOST_REQUIRE_EQUAL((int)atrace[1].action_ordinal, 2); BOOST_REQUIRE_EQUAL((int)atrace[1].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[1].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[1].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[1].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[1].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[1].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[1].except.valid(), false); // not executed BOOST_REQUIRE_EQUAL((int)atrace[2].action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[2].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[2].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[2].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[2].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[2].except.valid(), false); } FC_LOG_AND_RETHROW() } /************************************************************************************* + * action_ordinal_failtest2 test cases + *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_ordinal_failtest2, TESTER) { try { produce_blocks(1); create_account(N(testapi) ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(bob) ); set_code( N(bob), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(charlie) ); set_code( N(charlie), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(david) ); set_code( N(david), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(erin) ); set_code( N(erin), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(fail3) ); // <- make action 3 fails in the middle produce_blocks(1); transaction_trace_ptr txn_trace = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_action_ordinal1", {}); BOOST_REQUIRE_EQUAL( validate(), true ); BOOST_REQUIRE_EQUAL( txn_trace != nullptr, true); BOOST_REQUIRE_EQUAL( txn_trace->action_traces.size(), 8); auto &atrace = txn_trace->action_traces; // executed BOOST_REQUIRE_EQUAL((int)atrace[0].action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[0].creator_action_ordinal, 0); BOOST_REQUIRE_EQUAL((int)atrace[0].closest_unnotified_ancestor_action_ordinal, 0); BOOST_REQUIRE_EQUAL(atrace[0].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[0].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<unsigned_int>(atrace[0].return_value), unsigned_int(1) ); BOOST_REQUIRE_EQUAL(atrace[0].except.valid(), false); int start_gseq = atrace[0].receipt->global_sequence; // executed BOOST_REQUIRE_EQUAL((int)atrace[1].action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[1].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[1].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[1].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[1].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[1].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[1].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[1].return_value), "bob" ); BOOST_REQUIRE_EQUAL(atrace[1].receipt->global_sequence, start_gseq + 1); // not executed BOOST_REQUIRE_EQUAL((int)atrace[2].action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[2].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[2].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[2].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[2].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[2].except.valid(), false); // not executed BOOST_REQUIRE_EQUAL((int)atrace[3].action_ordinal, 4); BOOST_REQUIRE_EQUAL((int)atrace[3].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[3].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[3].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.name, TEST_METHOD("test_action", "test_action_ordinal3")); BOOST_REQUIRE_EQUAL(atrace[3].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[3].except.valid(), false); // hey exception is here BOOST_REQUIRE_EQUAL((int)atrace[4].action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[4].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[4].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[4].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[4].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[4].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[4].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[4].except.valid(), true); BOOST_REQUIRE_EQUAL(atrace[4].except->code(), 3050003); // not executed BOOST_REQUIRE_EQUAL((int)atrace[5].action_ordinal, 6); BOOST_REQUIRE_EQUAL((int)atrace[5].creator_action_ordinal, 2); BOOST_REQUIRE_EQUAL((int)atrace[5].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[5].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.account, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.name, TEST_METHOD("test_action", "test_action_ordinal_foo")); BOOST_REQUIRE_EQUAL(atrace[5].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[5].except.valid(), false); // not executed BOOST_REQUIRE_EQUAL((int)atrace[6].action_ordinal, 7); BOOST_REQUIRE_EQUAL((int)atrace[6].creator_action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[6].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[6].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[6].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[6].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[6].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[6].except.valid(), false); // not executed BOOST_REQUIRE_EQUAL((int)atrace[7].action_ordinal, 8); BOOST_REQUIRE_EQUAL((int)atrace[7].creator_action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[7].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[7].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.account, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.name, TEST_METHOD("test_action", "test_action_ordinal_bar")); BOOST_REQUIRE_EQUAL(atrace[7].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[7].except.valid(), false); } FC_LOG_AND_RETHROW() } /************************************************************************************* + * action_ordinal_failtest3 test cases + *************************************************************************************/ BOOST_FIXTURE_TEST_CASE(action_ordinal_failtest3, TESTER) { try { produce_blocks(1); create_account(N(testapi) ); set_code( N(testapi), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(bob) ); set_code( N(bob), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(charlie) ); set_code( N(charlie), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(david) ); set_code( N(david), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(erin) ); set_code( N(erin), contracts::test_api_wasm() ); produce_blocks(1); create_account(N(failnine) ); // <- make action 9 fails in the middle produce_blocks(1); transaction_trace_ptr txn_trace = CALL_TEST_FUNCTION_NO_THROW( *this, "test_action", "test_action_ordinal1", {}); BOOST_REQUIRE_EQUAL( validate(), true ); BOOST_REQUIRE_EQUAL( txn_trace != nullptr, true); BOOST_REQUIRE_EQUAL( txn_trace->action_traces.size(), 11); auto &atrace = txn_trace->action_traces; // executed BOOST_REQUIRE_EQUAL((int)atrace[0].action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[0].creator_action_ordinal, 0); BOOST_REQUIRE_EQUAL((int)atrace[0].closest_unnotified_ancestor_action_ordinal, 0); BOOST_REQUIRE_EQUAL(atrace[0].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[0].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[0].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<unsigned_int>(atrace[0].return_value), unsigned_int(1) ); BOOST_REQUIRE_EQUAL(atrace[0].except.valid(), false); int start_gseq = atrace[0].receipt->global_sequence; // executed BOOST_REQUIRE_EQUAL((int)atrace[1].action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[1].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[1].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[1].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[1].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[1].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[1].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[1].return_value), "bob" ); BOOST_REQUIRE_EQUAL(atrace[1].receipt->global_sequence, start_gseq + 1); // executed BOOST_REQUIRE_EQUAL((int)atrace[2].action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[2].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[2].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[2].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[2].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[2].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<name>(atrace[2].return_value), name("five") ); BOOST_REQUIRE_EQUAL(atrace[2].receipt->global_sequence, start_gseq + 4); // fails here BOOST_REQUIRE_EQUAL((int)atrace[3].action_ordinal, 4); BOOST_REQUIRE_EQUAL((int)atrace[3].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[3].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[3].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[3].act.name, TEST_METHOD("test_action", "test_action_ordinal3")); BOOST_REQUIRE_EQUAL(atrace[3].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[3].except.valid(), true); BOOST_REQUIRE_EQUAL(atrace[3].except->code(), 3050003); // executed BOOST_REQUIRE_EQUAL((int)atrace[4].action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[4].creator_action_ordinal, 1); BOOST_REQUIRE_EQUAL((int)atrace[4].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[4].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[4].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[4].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[4].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[4].return_value), "charlie" ); BOOST_REQUIRE_EQUAL(atrace[4].receipt->global_sequence, start_gseq + 2); // not executed BOOST_REQUIRE_EQUAL((int)atrace[5].action_ordinal, 6); BOOST_REQUIRE_EQUAL((int)atrace[5].creator_action_ordinal, 2); BOOST_REQUIRE_EQUAL((int)atrace[5].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[5].receiver, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.account, N(bob)); BOOST_REQUIRE_EQUAL(atrace[5].act.name, TEST_METHOD("test_action", "test_action_ordinal_foo")); BOOST_REQUIRE_EQUAL(atrace[5].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[5].except.valid(), false); // executed BOOST_REQUIRE_EQUAL((int)atrace[6].action_ordinal, 7); BOOST_REQUIRE_EQUAL((int)atrace[6].creator_action_ordinal,2); BOOST_REQUIRE_EQUAL((int)atrace[6].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[6].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[6].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[6].act.name, TEST_METHOD("test_action", "test_action_ordinal1")); BOOST_REQUIRE_EQUAL(atrace[6].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<std::string>(atrace[6].return_value), "david" ); BOOST_REQUIRE_EQUAL(atrace[6].receipt->global_sequence, start_gseq + 3); // not executed BOOST_REQUIRE_EQUAL((int)atrace[7].action_ordinal, 8); BOOST_REQUIRE_EQUAL((int)atrace[7].creator_action_ordinal, 5); BOOST_REQUIRE_EQUAL((int)atrace[7].closest_unnotified_ancestor_action_ordinal, 1); BOOST_REQUIRE_EQUAL(atrace[7].receiver, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.account, N(charlie)); BOOST_REQUIRE_EQUAL(atrace[7].act.name, TEST_METHOD("test_action", "test_action_ordinal_bar")); BOOST_REQUIRE_EQUAL(atrace[7].receipt.valid(), false); BOOST_REQUIRE_EQUAL(atrace[7].except.valid(), false); // executed BOOST_REQUIRE_EQUAL((int)atrace[8].action_ordinal, 9); BOOST_REQUIRE_EQUAL((int)atrace[8].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[8].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[8].receiver, N(david)); BOOST_REQUIRE_EQUAL(atrace[8].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[8].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[8].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<bool>(atrace[8].return_value), true ); BOOST_REQUIRE_EQUAL(atrace[8].receipt->global_sequence, start_gseq + 5); // executed BOOST_REQUIRE_EQUAL((int)atrace[9].action_ordinal, 10); BOOST_REQUIRE_EQUAL((int)atrace[9].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[9].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[9].receiver, N(erin)); BOOST_REQUIRE_EQUAL(atrace[9].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[9].act.name, TEST_METHOD("test_action", "test_action_ordinal2")); BOOST_REQUIRE_EQUAL(atrace[9].receipt.valid(), true); BOOST_REQUIRE_EQUAL(fc::raw::unpack<signed_int>(atrace[9].return_value), signed_int(7) ); BOOST_REQUIRE_EQUAL(atrace[9].receipt->global_sequence, start_gseq + 6); // executed BOOST_REQUIRE_EQUAL((int)atrace[10].action_ordinal, 11); BOOST_REQUIRE_EQUAL((int)atrace[10].creator_action_ordinal, 3); BOOST_REQUIRE_EQUAL((int)atrace[10].closest_unnotified_ancestor_action_ordinal, 3); BOOST_REQUIRE_EQUAL(atrace[10].receiver, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[10].act.account, N(testapi)); BOOST_REQUIRE_EQUAL(atrace[10].act.name, TEST_METHOD("test_action", "test_action_ordinal4")); BOOST_REQUIRE_EQUAL(atrace[10].receipt.valid(), true); BOOST_REQUIRE_EQUAL(atrace[10].return_value.size(), 0 ); BOOST_REQUIRE_EQUAL(atrace[10].receipt->global_sequence, start_gseq + 7); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END()
/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #ifndef CLIENT_ONLY #include "server_get.h" #include "server_ping.h" #include "database.h" #include "../stringtools.h" #include "fileclient/FileClient.h" #include "../Interface/Server.h" #include "../Interface/ThreadPool.h" #include "fileclient/tcpstack.h" #include "fileclient/data.h" #include "../fsimageplugin/IFSImageFactory.h" #include "../fsimageplugin/IVHDFile.h" #include "server_channel.h" #include "server_log.h" #include "server_writer.h" #include "server_cleanup.h" #include "server_update_stats.h" #include "escape.h" #include "mbr_code.h" #include "zero_hash.h" #include "server_running.h" #include "treediff/TreeDiff.h" #include "../urlplugin/IUrlFactory.h" #include <time.h> #include <algorithm> #include <memory.h> extern IFSImageFactory *image_fak; extern IUrlFactory *url_fak; extern std::string server_identity; extern std::string server_token; const unsigned short serviceport=35623; const unsigned int full_backup_construct_timeout=4*60*60*1000; const unsigned int shadow_copy_timeout=30*60*1000; const unsigned int check_time_intervall_tried_backup=30*60*1000; const unsigned int check_time_intervall=5*60*1000; const unsigned int status_update_intervall=1000; const unsigned int mbr_size=(1024*1024)/2; const size_t minfreespace_image=1000*1024*1024; //1000 MB const size_t minfreespace_min=50*1024*1024; const unsigned int curr_image_version=1; const unsigned int image_timeout=10*24*60*60*1000; const unsigned int image_recv_timeout=1*60*60*1000; int BackupServerGet::running_backups=0; int BackupServerGet::running_file_backups=0; IMutex *BackupServerGet::running_backup_mutex=NULL; BackupServerGet::BackupServerGet(IPipe *pPipe, sockaddr_in pAddr, const std::wstring &pName) { q_update_lastseen=NULL; pipe=pPipe; clientaddr=pAddr; clientaddr_mutex=Server->createMutex(); clientname=pName; clientid=0; hashpipe=Server->createMemoryPipe(); hashpipe_prepare=Server->createMemoryPipe(); exitpipe=Server->createMemoryPipe(); exitpipe_prepare=Server->createMemoryPipe(); do_full_backup_now=false; do_incr_backup_now=false; do_update_settings=false; do_full_image_now=false; do_incr_image_now=false; can_backup_images=true; filesrv_protocol_version=0; } BackupServerGet::~BackupServerGet(void) { if(q_update_lastseen!=NULL) unloadSQL(); Server->destroy(clientaddr_mutex); } void BackupServerGet::init_mutex(void) { running_backup_mutex=Server->createMutex(); } void BackupServerGet::destroy_mutex(void) { Server->destroy(running_backup_mutex); } void BackupServerGet::unloadSQL(void) { db->destroyQuery(q_update_lastseen); db->destroyQuery(q_update_full); db->destroyQuery(q_update_incr); db->destroyQuery(q_create_backup); db->destroyQuery(q_get_last_incremental); db->destroyQuery(q_set_last_backup); db->destroyQuery(q_update_setting); db->destroyQuery(q_insert_setting); db->destroyQuery(q_set_complete); db->destroyQuery(q_update_image_full); db->destroyQuery(q_update_image_incr); db->destroyQuery(q_create_backup_image); db->destroyQuery(q_set_image_complete); db->destroyQuery(q_set_last_image_backup); db->destroyQuery(q_get_last_incremental_image); db->destroyQuery(q_set_image_size); db->destroyQuery(q_update_running_file); db->destroyQuery(q_update_running_image); db->destroyQuery(q_update_images_size); db->destroyQuery(q_set_done); db->destroyQuery(q_save_logdata); db->destroyQuery(q_get_unsent_logdata); db->destroyQuery(q_set_logdata_sent); db->destroyQuery(q_save_image_assoc); db->destroyQuery(q_get_users); db->destroyQuery(q_get_rights); db->destroyQuery(q_get_report_settings); db->destroyQuery(q_format_unixtime); } void BackupServerGet::operator ()(void) { { bool b=sendClientMessage("ADD IDENTITY", "OK", L"Sending Identity to client failed stopping...", 10000, false); if(!b) { pipe->Write("ok"); Server->Log(L"server_get Thread for client "+clientname+L" finished, because the identity was not recognized", LL_INFO); ServerStatus::setWrongIdent(clientname, true); ServerLogger::reset(clientid); delete this; return; } } if( clientname.find(L"##restore##")==0 ) { ServerChannelThread channel_thread(this, -1); THREADPOOL_TICKET channel_thread_id=Server->getThreadPool()->execute(&channel_thread); while(true) { std::string msg; pipe->Read(&msg); if(msg=="exit" || msg=="exitnow" ) break; } channel_thread.doExit(); Server->getThreadPool()->waitFor(channel_thread_id); pipe->Write("ok"); Server->Log(L"server_get Thread for client "+clientname+L" finished, restore thread"); delete this; return; } db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER); server_settings=new ServerSettings(db); clientid=getClientID(); if(clientid==-1) { pipe->Write("ok"); Server->Log(L"server_get Thread for client "+clientname+L" finished, because there were too many clients", LL_INFO); ServerStatus::setTooManyClients(clientname, true); ServerLogger::reset(clientid); delete server_settings; delete this; return; } settings=Server->createDBSettingsReader(db, "settings", "SELECT value FROM settings_db.settings WHERE key=? AND clientid=0"); settings_client=Server->createDBSettingsReader(db, "settings", "SELECT value FROM settings_db.settings WHERE key=? AND clientid="+nconvert(clientid)); delete server_settings; server_settings=new ServerSettings(db, clientid); std::wstring backupfolder=server_settings->getSettings()->backupfolder; if(!os_create_dir(os_file_prefix()+backupfolder+os_file_sep()+clientname) && !os_directory_exists(os_file_prefix()+backupfolder+os_file_sep()+clientname) ) { Server->Log(L"Could not create or read directory for client \""+clientname+L"\"", LL_ERROR); pipe->Write("ok"); delete server_settings; delete this; return; } prepareSQL(); updateLastseen(); if(!updateCapabilities()) { Server->Log(L"Could not get client capabilities", LL_ERROR); pipe->Write("ok"); delete server_settings; delete this; return; } status.client=clientname; status.clientid=clientid; ServerStatus::setServerStatus(status); BackupServerHash *bsh=new BackupServerHash(hashpipe, exitpipe, clientid ); BackupServerPrepareHash *bsh_prepare=new BackupServerPrepareHash(hashpipe_prepare, exitpipe_prepare, hashpipe, exitpipe, clientid); Server->getThreadPool()->execute(bsh); Server->getThreadPool()->execute(bsh_prepare); ServerChannelThread channel_thread(this, clientid); THREADPOOL_TICKET channel_thread_id=Server->getThreadPool()->execute(&channel_thread); sendSettings(); ServerLogger::Log(clientid, "Getting client settings...", LL_DEBUG); if(server_settings->getSettings()->allow_overwrite && !getClientSettings()) { ServerLogger::Log(clientid, "Getting client settings failed. Retrying...", LL_INFO); Server->wait(200000); if(!getClientSettings()) { ServerLogger::Log(clientid, "Getting client settings failed -1", LL_ERROR); } } ServerLogger::Log(clientid, "Sending backup incr intervall...", LL_DEBUG); sendClientBackupIncrIntervall(); if(server_settings->getSettings()->autoupdate_clients) { checkClientVersion(); } sendClientLogdata(); bool skip_checking=false; if( server_settings->getSettings()->startup_backup_delay>0 ) { pipe->isReadable(server_settings->getSettings()->startup_backup_delay*1000); skip_checking=true; } bool do_exit_now=false; bool tried_backup=false; bool file_backup_err=false; while(true) { if(!skip_checking) { if(do_update_settings) { ServerLogger::Log(clientid, "Getting client settings...", LL_DEBUG); do_update_settings=false; if(server_settings->getSettings()->allow_overwrite && !getClientSettings()) { ServerLogger::Log(clientid, "Getting client settings failed -2", LL_ERROR); } } tried_backup=false; unsigned int ttime=Server->getTimeMS(); status.starttime=ttime; has_error=false; bool hbu=false; bool r_success=false; bool r_image=false; r_incremental=false; pingthread=NULL; pingthread_ticket=ILLEGAL_THREADPOOL_TICKET; status.pcdone=0; status.hashqueuesize=0; status.prepare_hashqueuesize=0; ServerStatus::setServerStatus(status); if(do_incr_image_now) { if(!can_backup_images) Server->Log("Cannot do image backup because can_backup_images=false", LL_DEBUG); if(server_settings->getSettings()->no_images) Server->Log("Cannot do image backup because no_images=true", LL_DEBUG); if(!isBackupsRunningOkay()) Server->Log("Cannot do image backup because isBackupsRunningOkay()=false", LL_DEBUG); } if( !file_backup_err && isBackupsRunningOkay() && ( (isUpdateFull() && isInBackupWindow(server_settings->getBackupWindow())) || do_full_backup_now ) ) { ScopedActiveThread sat; status.statusaction=sa_full_file; ServerStatus::setServerStatus(status, true); ServerLogger::Log(clientid, "Doing full file backup...", LL_DEBUG); do_full_backup_now=false; hbu=true; startBackupRunning(true); if(!constructBackupPath()) { ServerLogger::Log(clientid, "Cannot create Directory for backup (Server error)", LL_ERROR); r_success=false; } else { pingthread=new ServerPingThread(this); pingthread_ticket=Server->getThreadPool()->execute(pingthread); r_success=doFullBackup(); } } else if( !file_backup_err && isBackupsRunningOkay() && ( (isUpdateIncr() && isInBackupWindow(server_settings->getBackupWindow())) || do_incr_backup_now ) ) { ScopedActiveThread sat; status.statusaction=sa_incr_file; ServerStatus::setServerStatus(status, true); ServerLogger::Log(clientid, "Doing incremental file backup...", LL_DEBUG); do_incr_backup_now=false; hbu=true; startBackupRunning(true); r_incremental=true; if(!constructBackupPath()) { ServerLogger::Log(clientid, "Cannot create Directory for backup (Server error)", LL_ERROR); r_success=false; } else { pingthread=new ServerPingThread(this); pingthread_ticket=Server->getThreadPool()->execute(pingthread); r_success=doIncrBackup(); } } else if(can_backup_images && !server_settings->getSettings()->no_images && isBackupsRunningOkay() && ( (isUpdateFullImage() && isInBackupWindow(server_settings->getBackupWindow())) || do_full_image_now) ) { ScopedActiveThread sat; status.statusaction=sa_full_image; ServerStatus::setServerStatus(status, true); ServerLogger::Log(clientid, "Doing full image backup...", LL_DEBUG); r_image=true; pingthread=new ServerPingThread(this); pingthread_ticket=Server->getThreadPool()->execute(pingthread); startBackupRunning(true); r_success=true; std::vector<std::string> vols=server_settings->getBackupVolumes(); for(size_t i=0;i<vols.size();++i) { if(isUpdateFullImage(vols[i]+":") || do_full_image_now) { int sysvol_id=-1; if(strlower(vols[i])=="c") { ServerLogger::Log(clientid, "Backing up SYSVOL...", LL_DEBUG); if(doImage("SYSVOL", L"", 0, 0)) { sysvol_id=backupid; } ServerLogger::Log(clientid, "Backing up SYSVOL done.", LL_DEBUG); } bool b=doImage(vols[i]+":", L"", 0, 0); if(!b) { r_success=false; break; } else if(sysvol_id!=-1) { saveImageAssociation(backupid, sysvol_id); } } } do_full_image_now=false; } else if(can_backup_images && !server_settings->getSettings()->no_images && isBackupsRunningOkay() && ( (isUpdateIncrImage() && isInBackupWindow(server_settings->getBackupWindow())) || do_incr_image_now) ) { ScopedActiveThread sat; status.statusaction=sa_incr_image; ServerStatus::setServerStatus(status, true); ServerLogger::Log(clientid, "Doing incremental image backup...", LL_DEBUG); r_image=true; r_incremental=true; startBackupRunning(true); pingthread=new ServerPingThread(this); pingthread_ticket=Server->getThreadPool()->execute(pingthread); std::vector<std::string> vols=server_settings->getBackupVolumes(); for(size_t i=0;i<vols.size();++i) { std::string letter=vols[i]+":"; if(isUpdateIncrImage(letter) || do_incr_image_now) { int sysvol_id=-1; if(strlower(letter)=="c:") { ServerLogger::Log(clientid, "Backing up SYSVOL...", LL_DEBUG); if(doImage("SYSVOL", L"", 0, 0)) { sysvol_id=backupid; } ServerLogger::Log(clientid, "Backing up SYSVOL done.", LL_DEBUG); } SBackup last=getLastIncrementalImage(letter); if(last.incremental==-2) { ServerLogger::Log(clientid, "Error retrieving last backup.", LL_ERROR); r_success=false; break; } else { r_success=doImage(letter, last.path, last.incremental+1, last.incremental_ref); } if(r_success && sysvol_id!=-1) { saveImageAssociation(backupid, sysvol_id); } if(!r_success) break; } } do_incr_image_now=false; } file_backup_err=false; if(hbu && !has_error) { if(r_success) { notifyClientBackupSuccessfull(); } else { if(pingthread!=NULL) { pingthread->setStop(true); Server->getThreadPool()->waitFor(pingthread_ticket); } pingthread=NULL; } } else if(hbu && has_error) { file_backup_err=true; os_remove_nonempty_dir(backuppath); tried_backup=true; } status.action_done=false; status.statusaction=sa_none; status.pcdone=100; //Flush buffer before continuing... status.hashqueuesize=(_u32)hashpipe->getNumElements()+(bsh->isWorking()?1:0); status.prepare_hashqueuesize=(_u32)hashpipe_prepare->getNumElements()+(bsh_prepare->isWorking()?1:0); hashpipe->Write("flush"); while(status.hashqueuesize>0 || status.prepare_hashqueuesize>0) { ServerStatus::setServerStatus(status, true); Server->wait(1000); status.hashqueuesize=(_u32)hashpipe->getNumElements()+(bsh->isWorking()?1:0); status.prepare_hashqueuesize=(_u32)hashpipe_prepare->getNumElements()+(bsh_prepare->isWorking()?1:0); } ServerStatus::setServerStatus(status); unsigned int ptime=Server->getTimeMS()-ttime; if(hbu && !has_error) { ServerLogger::Log(clientid, L"Time taken for backing up client "+clientname+L": "+convert(ptime), LL_INFO); if(!r_success) { ServerLogger::Log(clientid, "Backup not complete because of connection problems", LL_ERROR); } else if( bsh->hasError() ) { ServerLogger::Log(clientid, "Backup not complete because of disk problems", LL_ERROR); } else { updateLastBackup(); setBackupComplete(); } status.pcdone=100; ServerStatus::setServerStatus(status, true); } if( r_image ) { ServerLogger::Log(clientid, L"Time taken for creating image of client "+clientname+L": "+convert(ptime), LL_INFO); if(!r_success) { ServerLogger::Log(clientid, "Backup not complete because of connection problems", LL_ERROR); } else { updateLastImageBackup(); } status.pcdone=100; ServerStatus::setServerStatus(status, true); } if(hbu || r_image) { stopBackupRunning(!r_image); saveClientLogdata(r_image?1:0, r_incremental?1:0, r_success && !has_error); sendClientLogdata(); } if(hbu) { ServerCleanupThread::updateStats(true); } if(pingthread!=NULL) { pingthread->setStop(true); Server->getThreadPool()->waitFor(pingthread_ticket); pingthread=NULL; } /* Predict sleep time -- unsigned int wtime; if((unsigned int)update_freq_incr*1000>ptime) { wtime=update_freq_incr*1000-ptime; } else { wtime=0; } wtime+=60000;*/ } std::string msg; if(file_backup_err) pipe->Read(&msg, 0); else if(tried_backup) pipe->Read(&msg, skip_checking?0:check_time_intervall_tried_backup); else pipe->Read(&msg, skip_checking?0:check_time_intervall); skip_checking=false; if(msg=="exit") break; else if(msg=="exitnow") { do_exit_now=true; break; } else if(msg=="START BACKUP INCR") do_incr_backup_now=true; else if(msg=="START BACKUP FULL") do_full_backup_now=true; else if(msg=="UPDATE SETTINGS") do_update_settings=true; else if(msg=="START IMAGE INCR") do_incr_image_now=true; else if(msg=="START IMAGE FULL") do_full_image_now=true; else if(msg.find("address")==0) { IScopedLock lock(clientaddr_mutex); memcpy(&clientaddr, &msg[7], sizeof(sockaddr_in) ); } Server->Log("msg="+msg, LL_DEBUG); } //destroy channel { Server->Log("Stopping channel...", LL_DEBUG); channel_thread.doExit(); Server->getThreadPool()->waitFor(channel_thread_id); } if(do_exit_now) { hashpipe_prepare->Write("exitnow"); std::string msg; exitpipe_prepare->Read(&msg); Server->destroy(exitpipe_prepare); } else { hashpipe_prepare->Write("exit"); } Server->destroy(settings); Server->destroy(settings_client); delete server_settings; pipe->Write("ok"); Server->Log(L"server_get Thread for client "+clientname+L" finished"); delete this; } void BackupServerGet::prepareSQL(void) { SSettings *s=server_settings->getSettings(); q_update_lastseen=db->Prepare("UPDATE clients SET lastseen=CURRENT_TIMESTAMP WHERE id=?", false); q_update_full=db->Prepare("SELECT id FROM backups WHERE datetime('now','-"+nconvert(s->update_freq_full)+" seconds')<backuptime AND clientid=? AND incremental=0 AND done=1", false); q_update_incr=db->Prepare("SELECT id FROM backups WHERE datetime('now','-"+nconvert(s->update_freq_incr)+" seconds')<backuptime AND clientid=? AND complete=1 AND done=1", false); q_create_backup=db->Prepare("INSERT INTO backups (incremental, clientid, path, complete, running, size_bytes, done) VALUES (?, ?, ?, 0, CURRENT_TIMESTAMP, -1, 0)", false); q_get_last_incremental=db->Prepare("SELECT incremental,path FROM backups WHERE clientid=? AND done=1 ORDER BY backuptime DESC LIMIT 1", false); q_set_last_backup=db->Prepare("UPDATE clients SET lastbackup=CURRENT_TIMESTAMP WHERE id=?", false); q_update_setting=db->Prepare("UPDATE settings_db.settings SET value=? WHERE key=? AND clientid=?", false); q_insert_setting=db->Prepare("INSERT INTO settings_db.settings (key, value, clientid) VALUES (?,?,?)", false); q_set_complete=db->Prepare("UPDATE backups SET complete=1 WHERE id=?", false); q_update_image_full=db->Prepare("SELECT id FROM backup_images WHERE datetime('now','-"+nconvert(s->update_freq_image_full)+" seconds')<backuptime AND clientid=? AND incremental=0 AND complete=1 AND version="+nconvert(curr_image_version)+" AND letter=?", false); q_update_image_incr=db->Prepare("SELECT id FROM backup_images WHERE datetime('now','-"+nconvert(s->update_freq_image_incr)+" seconds')<backuptime AND clientid=? AND complete=1 AND version="+nconvert(curr_image_version)+" AND letter=?", false); q_create_backup_image=db->Prepare("INSERT INTO backup_images (clientid, path, incremental, incremental_ref, complete, running, size_bytes, version, letter) VALUES (?, ?, ?, ?, 0, CURRENT_TIMESTAMP, 0, "+nconvert(curr_image_version)+",?)", false); q_set_image_size=db->Prepare("UPDATE backup_images SET size_bytes=? WHERE id=?", false); q_set_image_complete=db->Prepare("UPDATE backup_images SET complete=1 WHERE id=?", false); q_set_last_image_backup=db->Prepare("UPDATE clients SET lastbackup_image=CURRENT_TIMESTAMP WHERE id=?", false); q_get_last_incremental_image=db->Prepare("SELECT id,incremental,path FROM backup_images WHERE clientid=? AND incremental=0 AND complete=1 AND version="+nconvert(curr_image_version)+" AND letter=? ORDER BY backuptime DESC LIMIT 1", false); q_update_running_file=db->Prepare("UPDATE backups SET running=CURRENT_TIMESTAMP WHERE id=?", false); q_update_running_image=db->Prepare("UPDATE backup_images SET running=CURRENT_TIMESTAMP WHERE id=?", false); q_update_images_size=db->Prepare("UPDATE clients SET bytes_used_images=(SELECT bytes_used_images FROM clients WHERE id=?)+? WHERE id=?", false); q_set_done=db->Prepare("UPDATE backups SET done=1 WHERE id=?", false); q_save_logdata=db->Prepare("INSERT INTO logs (clientid, logdata, errors, warnings, infos, image, incremental) VALUES (?,?,?,?,?,?,?)", false); q_get_unsent_logdata=db->Prepare("SELECT id, strftime('%s', created) AS created, logdata FROM logs WHERE sent=0 AND clientid=?", false); q_set_logdata_sent=db->Prepare("UPDATE logs SET sent=1 WHERE id=?", false); q_save_image_assoc=db->Prepare("INSERT INTO assoc_images (img_id, assoc_id) VALUES (?,?)", false); q_get_users=db->Prepare("SELECT id FROM settings_db.si_users WHERE report_mail IS NOT NULL AND report_mail<>''", false); q_get_rights=db->Prepare("SELECT t_right FROM settings_db.si_permissions WHERE clientid=? AND t_domain=?", false); q_get_report_settings=db->Prepare("SELECT report_mail, report_loglevel, report_sendonly FROM settings_db.si_users WHERE id=?", false); q_format_unixtime=db->Prepare("SELECT datetime(?, 'unixepoch', 'localtime') AS time", false); } int BackupServerGet::getClientID(void) { IQuery *q=db->Prepare("SELECT id FROM clients WHERE name=?",false); q->Bind(clientname); db_results res=q->Read(); db->destroyQuery(q); if(res.size()>0) return watoi(res[0][L"id"]); else { IQuery *q_get_num_clients=db->Prepare("SELECT count(*) AS c FROM clients WHERE lastseen > date('now', '-2 month')", false); db_results res_r=q_get_num_clients->Read(); q_get_num_clients->Reset(); int c_clients=-1; if(!res_r.empty()) c_clients=watoi(res_r[0][L"c"]); db->destroyQuery(q_get_num_clients); if(c_clients<server_settings->getSettings()->max_active_clients) { IQuery *q_insert_newclient=db->Prepare("INSERT INTO clients (name, lastseen,bytes_used_files,bytes_used_images) VALUES (?, CURRENT_TIMESTAMP, 0, 0)", false); q_insert_newclient->Bind(clientname); q_insert_newclient->Write(); int rid=(int)db->getLastInsertID(); q_insert_newclient->Reset(); db->destroyQuery(q_insert_newclient); return rid; } else { Server->Log(L"Too many clients. Didn't accept client '"+clientname+L"'", LL_INFO); return -1; } } } SBackup BackupServerGet::getLastIncremental(void) { q_get_last_incremental->Bind(clientid); db_results res=q_get_last_incremental->Read(); q_get_last_incremental->Reset(); if(res.size()>0) { SBackup b; b.incremental=watoi(res[0][L"incremental"]); b.path=res[0][L"path"]; return b; } else { SBackup b; b.incremental=-2; return b; } } SBackup BackupServerGet::getLastIncrementalImage(const std::string &letter) { q_get_last_incremental_image->Bind(clientid); q_get_last_incremental_image->Bind(letter); db_results res=q_get_last_incremental_image->Read(); q_get_last_incremental_image->Reset(); if(res.size()>0) { SBackup b; b.incremental=watoi(res[0][L"incremental"]); b.path=res[0][L"path"]; b.incremental_ref=watoi(res[0][L"id"]); return b; } else { SBackup b; b.incremental=-2; return b; } } int BackupServerGet::createBackupSQL(int incremental, int clientid, std::wstring path) { q_create_backup->Bind(incremental); q_create_backup->Bind(clientid); q_create_backup->Bind(path); q_create_backup->Write(); q_create_backup->Reset(); return (int)db->getLastInsertID(); } int BackupServerGet::createBackupImageSQL(int incremental, int incremental_ref, int clientid, std::wstring path, std::string letter) { q_create_backup_image->Bind(clientid); q_create_backup_image->Bind(path); q_create_backup_image->Bind(incremental); q_create_backup_image->Bind(incremental_ref); q_create_backup_image->Bind(letter); q_create_backup_image->Write(); q_create_backup_image->Reset(); return (int)db->getLastInsertID(); } void BackupServerGet::updateLastseen(void) { q_update_lastseen->Bind(clientid); q_update_lastseen->Write(); q_update_lastseen->Reset(); } bool BackupServerGet::isUpdateFull(void) { q_update_full->Bind(clientid); db_results res=q_update_full->Read(); q_update_full->Reset(); return res.empty(); } bool BackupServerGet::isUpdateIncr(void) { q_update_incr->Bind(clientid); db_results res=q_update_incr->Read(); q_update_incr->Reset(); return res.empty(); } bool BackupServerGet::isUpdateFullImage(const std::string &letter) { if(server_settings->getSettings()->update_freq_image_full<0) return false; q_update_image_full->Bind(clientid); q_update_image_full->Bind(letter); db_results res=q_update_image_full->Read(); q_update_image_full->Reset(); return res.empty(); } bool BackupServerGet::isUpdateFullImage(void) { std::vector<std::string> vols=server_settings->getBackupVolumes(); for(size_t i=0;i<vols.size();++i) { if( isUpdateFullImage(vols[i]+":") ) { return true; } } return false; } bool BackupServerGet::isUpdateIncrImage(void) { std::vector<std::string> vols=server_settings->getBackupVolumes(); for(size_t i=0;i<vols.size();++i) { if( isUpdateIncrImage(vols[i]+":") ) { return true; } } return false; } bool BackupServerGet::isUpdateIncrImage(const std::string &letter) { if(server_settings->getSettings()->update_freq_image_full<=0) return false; q_update_image_incr->Bind(clientid); q_update_image_incr->Bind(letter); db_results res=q_update_image_incr->Read(); q_update_image_incr->Reset(); return res.empty(); } void BackupServerGet::updateRunning(bool image) { if(image) { q_update_running_image->Bind(backupid); q_update_running_image->Write(); q_update_running_image->Reset(); } else { q_update_running_file->Bind(backupid); q_update_running_file->Write(); q_update_running_file->Reset(); } } void BackupServerGet::saveImageAssociation(int image_id, int assoc_id) { q_save_image_assoc->Bind(image_id); q_save_image_assoc->Bind(assoc_id); q_save_image_assoc->Write(); q_save_image_assoc->Reset(); } bool BackupServerGet::getNextEntry(char ch, SFile &data) { switch(state) { case 0: if(ch=='f') data.isdir=false; else if(ch=='d') data.isdir=true; else ServerLogger::Log(clientid, "Error parsing file BackupServerGet::getNextEntry - 1", LL_ERROR); state=1; break; case 1: //" state=2; break; case 3: if(ch!='"') { t_name.erase(t_name.size()-1,1); data.name=Server->ConvertToUnicode(t_name); t_name=""; if(data.isdir) { resetEntryState(); return true; } else state=4; } case 2: if(state==2 && ch=='"') state=3; else if(state==3) state=2; t_name+=ch; break; case 4: if(ch!=' ') { t_name+=ch; } else { data.size=os_atoi64(t_name); t_name=""; state=5; } break; case 5: if(ch!='\n') { t_name+=ch; } else { data.last_modified=os_atoi64(t_name); resetEntryState(); return true; } break; } return false; } void BackupServerGet::resetEntryState(void) { t_name=""; state=0; } bool BackupServerGet::request_filelist_construct(bool full, bool with_token) { CTCPStack tcpstack; Server->Log(clientname+L": Connecting for filelist...", LL_DEBUG); IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed - CONNECT error during filelist construction", LL_ERROR); return false; } if(full) tcpstack.Send(cc, server_identity+"START FULL BACKUP"+(with_token?("#token="+server_token):"")); else tcpstack.Send(cc, server_identity+"START BACKUP"+(with_token?("#token="+server_token):"")); Server->Log(clientname+L": Waiting for filelist", LL_DEBUG); std::string ret; unsigned int starttime=Server->getTimeMS(); while(Server->getTimeMS()-starttime<=full_backup_construct_timeout) { size_t rc=cc->Read(&ret, full_backup_construct_timeout); if(rc==0) { if(Server->getTimeMS()-starttime<=20000 && with_token==true) //Compatibility with older clients { Server->destroy(cc); Server->Log(clientname+L": Trying old filelist request", LL_WARNING); return request_filelist_construct(full, false); } else { ServerLogger::Log(clientid, L"Constructing of filelist of \""+clientname+L"\" failed - TIMEOUT(1)", LL_ERROR); } break; } tcpstack.AddData((char*)ret.c_str(), ret.size()); size_t packetsize; char *pck=tcpstack.getPacket(&packetsize); if(pck!=NULL && packetsize>0) { ret=pck; delete [] pck; if(ret!="DONE") { ServerLogger::Log(clientid, L"Constructing of filelist of \""+clientname+L"\" failed: "+widen(ret), LL_ERROR); break; } else { Server->destroy(cc); return true; } } } Server->destroy(cc); return false; } bool BackupServerGet::doFullBackup(void) { int64 free_space=os_free_space(os_file_prefix()+server_settings->getSettings()->backupfolder); if(free_space!=-1 && free_space<minfreespace_min) { Server->Log("No space for directory entries. Freeing space", LL_WARNING); ServerCleanupThread cleanup; if(!cleanup.do_cleanup(minfreespace_min) ) { ServerLogger::Log(clientid, "Could not free space for directory entries. NOT ENOUGH FREE SPACE.", LL_ERROR); return false; } } bool b=request_filelist_construct(true); if(!b) { has_error=true; return false; } FileClient fc(filesrv_protocol_version); sockaddr_in addr=getClientaddr(); _u32 rc=fc.Connect(&addr); if(rc!=ERR_CONNECTED) { ServerLogger::Log(clientid, L"Full Backup of "+clientname+L" failed - CONNECT error", LL_ERROR); has_error=true; return false; } IFile *tmp=Server->openTemporaryFile(); if(tmp==NULL) return false; rc=fc.GetFile("urbackup/filelist.ub", tmp); if(rc!=ERR_SUCCESS) { ServerLogger::Log(clientid, L"Error getting filelist of "+clientname+L". Errorcode: "+convert(rc), LL_ERROR); has_error=true; return false; } backupid=createBackupSQL(0, clientid, backuppath_single); tmp->Seek(0); resetEntryState(); IFile *clientlist=Server->openFile("urbackup/clientlist_"+nconvert(clientid)+".ub", MODE_WRITE); if(clientlist==NULL ) { ServerLogger::Log(clientid, L"Error creating clientlist for client "+clientname, LL_ERROR); has_error=true; return false; } _i64 filelist_size=tmp->Size(); char buffer[4096]; _u32 read; _i64 filelist_currpos=0; std::wstring curr_path; SFile cf; int depth=0; bool r_done=false; unsigned int laststatsupdate=0; ServerStatus::setServerStatus(status, true); ServerRunningUpdater *running_updater=new ServerRunningUpdater(backupid, false); Server->getThreadPool()->execute(running_updater); std::vector<size_t> diffs; _i64 files_size=getIncrementalSize(tmp, diffs, true); _i64 transferred=0; tmp->Seek(0); bool c_has_error=false; while( (read=tmp->Read(buffer, 4096))>0 && r_done==false && c_has_error==false) { filelist_currpos+=read; for(size_t i=0;i<read;++i) { unsigned int ctime=Server->getTimeMS(); if(ctime-laststatsupdate>status_update_intervall) { laststatsupdate=ctime; if(files_size==0) { status.pcdone=100; } else { status.pcdone=(std::min)(100,(int)(((float)transferred)/((float)files_size/100.f)+0.5f)); } status.hashqueuesize=(_u32)hashpipe->getNumElements(); status.prepare_hashqueuesize=(_u32)hashpipe_prepare->getNumElements(); ServerStatus::setServerStatus(status, true); } bool b=getNextEntry(buffer[i], cf); if(b) { if(cf.isdir==true) { if(cf.name!=L"..") { curr_path+=L"/"+cf.name; std::wstring os_curr_path=curr_path; if(os_file_sep()!=L"/") { for(size_t i=0;i<os_curr_path.size();++i) if(os_curr_path[i]=='/') os_curr_path[i]=os_file_sep()[0]; } if(!os_create_dir(os_file_prefix()+backuppath+os_curr_path)) { ServerLogger::Log(clientid, L"Creating directory \""+backuppath+os_curr_path+L"\" failed.", LL_ERROR); c_has_error=true; break; } ++depth; if(depth==1) { std::wstring t=curr_path; t.erase(0,1); ServerLogger::Log(clientid, L"Starting shadowcopy \""+t+L"\".", LL_INFO); start_shadowcopy(Server->ConvertToUTF8(t)); Server->wait(10000); } } else { --depth; if(depth==0) { std::wstring t=curr_path; t.erase(0,1); ServerLogger::Log(clientid, L"Stoping shadowcopy \""+t+L"\".", LL_INFO); stop_shadowcopy(Server->ConvertToUTF8(t)); } curr_path=ExtractFilePath(curr_path); } } else { bool b=load_file(cf.name, curr_path, fc); if(!b) { ServerLogger::Log(clientid, L"Client "+clientname+L" went offline.", LL_ERROR); r_done=true; break; } transferred+=cf.size; } } } writeFileRepeat(clientlist, buffer, read); if(read<4096) break; } if(r_done==false && c_has_error==false) { std::wstring backupfolder=server_settings->getSettings()->backupfolder; std::wstring currdir=backupfolder+os_file_sep()+clientname+os_file_sep()+L"current"; Server->deleteFile(os_file_prefix()+currdir); os_link_symbolic(os_file_prefix()+backuppath, os_file_prefix()+currdir); currdir=backupfolder+os_file_sep()+L"clients"; if(!os_create_dir(os_file_prefix()+currdir) && !os_directory_exists(os_file_prefix()+currdir)) { Server->Log("Error creating \"clients\" dir for symbolic links", LL_ERROR); } currdir+=os_file_sep()+clientname; Server->deleteFile(os_file_prefix()+currdir); os_link_symbolic(os_file_prefix()+backuppath, os_file_prefix()+currdir); } running_updater->stop(); updateRunning(false); Server->destroy(clientlist); Server->destroy(tmp); setBackupDone(); if(c_has_error) return false; return !r_done; } bool BackupServerGet::load_file(const std::wstring &fn, const std::wstring &curr_path, FileClient &fc) { ServerLogger::Log(clientid, L"Loading file \""+fn+L"\"", LL_DEBUG); IFile *fd=NULL; while(fd==NULL) { fd=Server->openTemporaryFile(); if(fd==NULL) { ServerLogger::Log(clientid, "Error opening temporary file. Retrying...", LL_WARNING); Server->wait(500); } } std::wstring cfn=curr_path+L"/"+fn; if(cfn[0]=='/') cfn.erase(0,1); if(!server_token.empty()) { cfn=widen(server_token)+L"|"+cfn; } _u32 rc=fc.GetFile(Server->ConvertToUTF8(cfn), fd); if(rc!=ERR_SUCCESS) { ServerLogger::Log(clientid, L"Error getting file \""+cfn+L"\" from "+clientname+L". Errorcode: "+convert(rc), LL_ERROR); std::wstring temp_fn=fd->getFilenameW(); Server->destroy(fd); Server->deleteFile(temp_fn); if(rc==ERR_TIMEOUT || rc==ERR_ERROR || rc==ERR_BASE_DIR_LOST) return false; } else { std::wstring os_curr_path=curr_path+L"/"+fn; if(os_file_sep()!=L"/") { for(size_t i=0;i<os_curr_path.size();++i) if(os_curr_path[i]=='/') os_curr_path[i]=os_file_sep()[0]; } std::wstring dstpath=backuppath+os_curr_path; hashFile(dstpath, fd); } return true; } _i64 BackupServerGet::getIncrementalSize(IFile *f, const std::vector<size_t> &diffs, bool all) { f->Seek(0); _i64 rsize=0; resetEntryState(); SFile cf; bool indirchange=false; size_t read; size_t line=0; char buffer[4096]; int indir_currdepth=0; int depth=0; int indir_curr_depth=0; int changelevel=0; if(all) { indirchange=true; } while( (read=f->Read(buffer, 4096))>0 ) { for(size_t i=0;i<read;++i) { bool b=getNextEntry(buffer[i], cf); if(b) { if(cf.isdir==true) { if(indirchange==false && hasChange(line, diffs) ) { indirchange=true; changelevel=depth; indir_currdepth=0; } else if(indirchange==true) { if(cf.name!=L"..") ++indir_currdepth; else --indir_currdepth; } if(cf.name==L".." && indir_currdepth>0) { --indir_currdepth; } if(cf.name!=L"..") { ++depth; } else { --depth; if(indirchange==true && depth==changelevel) { if(!all) { indirchange=false; } } } } else { if(indirchange==true || hasChange(line, diffs)) { rsize+=cf.size; } } ++line; } } if(read<4096) break; } return rsize; } bool BackupServerGet::doIncrBackup(void) { int64 free_space=os_free_space(os_file_prefix()+server_settings->getSettings()->backupfolder); if(free_space!=-1 && free_space<minfreespace_min) { Server->Log("No space for directory entries. Freeing space", LL_WARNING); ServerCleanupThread cleanup; if(!cleanup.do_cleanup(minfreespace_min) ) { ServerLogger::Log(clientid, "Could not free space for directory entries. NOT ENOUGH FREE SPACE.", LL_ERROR); return false; } } bool b=request_filelist_construct(false); if(!b) { has_error=true; return false; } Server->Log(clientname+L": Connecting to client...", LL_DEBUG); FileClient fc(filesrv_protocol_version); sockaddr_in addr=getClientaddr(); _u32 rc=fc.Connect(&addr); if(rc!=ERR_CONNECTED) { ServerLogger::Log(clientid, L"Incremental Backup of "+clientname+L" failed - CONNECT error", LL_ERROR); has_error=true; return false; } Server->Log(clientname+L": Loading filelist...", LL_DEBUG); IFile *tmp=Server->openTemporaryFile(); if(tmp==NULL) return false; rc=fc.GetFile("urbackup/filelist.ub", tmp); if(rc!=ERR_SUCCESS) { ServerLogger::Log(clientid, L"Error getting filelist of "+clientname+L". Errorcode: "+convert(rc), LL_ERROR); has_error=true; return false; } Server->Log(clientname+L" Starting incremental backup...", LL_DEBUG); SBackup last=getLastIncremental(); if(last.incremental==-2) { ServerLogger::Log(clientid, "Error retrieving last backup.", LL_ERROR); has_error=true; return false; } backupid=createBackupSQL(last.incremental+1, clientid, backuppath_single); std::wstring backupfolder=server_settings->getSettings()->backupfolder; std::wstring last_backuppath=backupfolder+os_file_sep()+clientname+os_file_sep()+last.path; std::wstring tmpfilename=tmp->getFilenameW(); Server->destroy(tmp); Server->Log(clientname+L": Calculating file tree differences...", LL_DEBUG); bool error=false; std::vector<size_t> diffs=TreeDiff::diffTrees("urbackup/clientlist_"+nconvert(clientid)+".ub", wnarrow(tmpfilename), error); if(error) { ServerLogger::Log(clientid, "Error while calculating tree diff. Doing full backup.", LL_ERROR); return doFullBackup(); } IFile *clientlist=Server->openFile("urbackup/clientlist_"+nconvert(clientid)+"_new.ub", MODE_WRITE); tmp=Server->openFile(tmpfilename, MODE_READ); ServerRunningUpdater *running_updater=new ServerRunningUpdater(backupid, false); Server->getThreadPool()->execute(running_updater); resetEntryState(); char buffer[4096]; _u32 read; std::wstring curr_path; SFile cf; int depth=0; int line=0; link_logcnt=0; bool indirchange=false; int changelevel; bool r_offline=false; _i64 filelist_size=tmp->Size(); _i64 filelist_currpos=0; int indir_currdepth=0; Server->Log(clientname+L": Calculating tree difference size...", LL_DEBUG); _i64 files_size=getIncrementalSize(tmp, diffs); tmp->Seek(0); _i64 transferred=0; unsigned int laststatsupdate=0; ServerStatus::setServerStatus(status, true); Server->Log(clientname+L": Linking unchanged and loading new files...", LL_DEBUG); bool c_has_error=false; while( (read=tmp->Read(buffer, 4096))>0 ) { filelist_currpos+=read; for(size_t i=0;i<read;++i) { bool b=getNextEntry(buffer[i], cf); if(b) { unsigned int ctime=Server->getTimeMS(); if(ctime-laststatsupdate>status_update_intervall) { laststatsupdate=ctime; if(files_size==0) { status.pcdone=100; } else { status.pcdone=(std::min)(100,(int)(((float)transferred)/((float)files_size/100.f)+0.5f)); } status.hashqueuesize=(_u32)hashpipe->getNumElements(); status.prepare_hashqueuesize=(_u32)hashpipe_prepare->getNumElements(); ServerStatus::setServerStatus(status, true); } if(cf.isdir==true) { if(indirchange==false && hasChange(line, diffs) ) { indirchange=true; changelevel=depth; indir_currdepth=0; if(cf.name!=L"..") indir_currdepth=1; else --changelevel; } else if(indirchange==true && r_offline==false) { if(cf.name!=L"..") ++indir_currdepth; else --indir_currdepth; } if(indirchange==false || r_offline==false ) { writeFileRepeat(clientlist, "d\""+Server->ConvertToUTF8(cf.name)+"\"\n"); } else if(cf.name==L".." && indir_currdepth>0) { --indir_currdepth; writeFileRepeat(clientlist, "d\"..\"\n"); } if(cf.name!=L"..") { curr_path+=L"/"+cf.name; std::wstring os_curr_path=curr_path; if(os_file_sep()!=L"/") { for(size_t i=0;i<os_curr_path.size();++i) if(os_curr_path[i]=='/') os_curr_path[i]=os_file_sep()[0]; } if(!os_create_dir(os_file_prefix()+backuppath+os_curr_path)) { ServerLogger::Log(clientid, L"Creating directory \""+backuppath+os_curr_path+L"\" failed.", LL_ERROR); c_has_error=true; break; } ++depth; if(depth==1) { std::wstring t=curr_path; t.erase(0,1); if(r_offline==false) { start_shadowcopy(Server->ConvertToUTF8(t)); } } } else { --depth; if(indirchange==true && depth==changelevel) { indirchange=false; } if(depth==0) { std::wstring t=curr_path; t.erase(0,1); if(r_offline==false) { stop_shadowcopy(Server->ConvertToUTF8(t)); } } curr_path=ExtractFilePath(curr_path); } } else { if(indirchange==true || hasChange(line, diffs)) { if(r_offline==false) { bool b=load_file(cf.name, curr_path, fc); if(!b) { ServerLogger::Log(clientid, L"Client "+clientname+L" went offline.", LL_ERROR); r_offline=true; } else { transferred+=cf.size; writeFileRepeat(clientlist, "f\""+Server->ConvertToUTF8(cf.name)+"\" "+nconvert(cf.size)+" "+nconvert(cf.last_modified)+"\n"); } } } else { std::wstring os_curr_path=curr_path+L"/"+cf.name; if(os_file_sep()!=L"/") { for(size_t i=0;i<os_curr_path.size();++i) if(os_curr_path[i]=='/') os_curr_path[i]=os_file_sep()[0]; } std::wstring srcpath=last_backuppath+os_curr_path; bool f_ok=true; bool b=os_create_hardlink(os_file_prefix()+backuppath+os_curr_path, os_file_prefix()+srcpath); if(!b) { if(link_logcnt<5) { ServerLogger::Log(clientid, L"Creating hardlink from \""+srcpath+L"\" to \""+backuppath+os_curr_path+L"\" failed. Loading file...", LL_WARNING); } else if(link_logcnt==5) { ServerLogger::Log(clientid, L"More warnings of kind: Creating hardlink from \""+srcpath+L"\" to \""+backuppath+os_curr_path+L"\" failed. Loading file... Skipping.", LL_WARNING); } else { Server->Log(L"Creating hardlink from \""+srcpath+L"\" to \""+backuppath+os_curr_path+L"\" failed. Loading file...", LL_WARNING); } ++link_logcnt; if(r_offline==false) { bool b2=load_file(cf.name, curr_path, fc); if(!b2) { ServerLogger::Log(clientid, L"Client "+clientname+L" went offline.", LL_ERROR); r_offline=true; f_ok=false; } } else { f_ok=false; } } if(f_ok) { writeFileRepeat(clientlist, "f\""+Server->ConvertToUTF8(cf.name)+"\" "+nconvert(cf.size)+" "+nconvert(cf.last_modified)+"\n"); } } } ++line; } } if(c_has_error) break; if(read<4096) break; } status.pcdone=100; ServerStatus::setServerStatus(status, true); Server->destroy(clientlist); if(r_offline==false && c_has_error==false) { Server->Log("Client ok. Copying full file...", LL_DEBUG); IFile *clientlist=Server->openFile("urbackup/clientlist_"+nconvert(clientid)+".ub", MODE_WRITE); bool clientlist_copy_err=false; if(clientlist!=NULL) { tmp->Seek(0); _u32 r=0; char buf[4096]; do { r=tmp->Read(buf, 4096); if(r>0) { _u32 written=0; _u32 rc; int tries=50; do { rc=clientlist->Write(buf+written, r-written); written+=rc; if(rc==0) { Server->Log("Failed to write to file... waiting...", LL_WARNING); Server->wait(10000); --tries; } } while(written<r && (rc>0 || tries>0) ); if(rc==0) { ServerLogger::Log(clientid, "Fatal error copying clientlist. Write error.", LL_ERROR); clientlist_copy_err=true; break; } } } while(r>0); Server->Log("Copying done.", LL_DEBUG); Server->Log("Creating symbolic links. -1", LL_DEBUG); std::wstring backupfolder=server_settings->getSettings()->backupfolder; std::wstring currdir=backupfolder+os_file_sep()+clientname+os_file_sep()+L"current"; Server->deleteFile(os_file_prefix()+currdir); os_link_symbolic(os_file_prefix()+backuppath, os_file_prefix()+currdir); Server->Log("Creating symbolic links. -2", LL_DEBUG); currdir=backupfolder+os_file_sep()+L"clients"; if(!os_create_dir(os_file_prefix()+currdir) && !os_directory_exists(os_file_prefix()+currdir)) { Server->Log("Error creating \"clients\" dir for symbolic links", LL_ERROR); } currdir+=os_file_sep()+clientname; Server->deleteFile(os_file_prefix()+currdir); os_link_symbolic(os_file_prefix()+backuppath, os_file_prefix()+currdir); Server->Log("Symbolic links created.", LL_DEBUG); Server->destroy(clientlist); } else { ServerLogger::Log(clientid, "Fatal error copying clientlist. Open error.", LL_ERROR); } if(!clientlist_copy_err) { Server->deleteFile("urbackup/clientlist_"+nconvert(clientid)+"_new.ub"); } } else if(!c_has_error) { Server->Log("Client disconnected while backing up. Copying partial file...", LL_DEBUG); Server->deleteFile("urbackup/clientlist_"+nconvert(clientid)+".ub"); moveFile(L"urbackup/clientlist_"+convert(clientid)+L"_new.ub", L"urbackup/clientlist_"+convert(clientid)+L".ub"); } else { ServerLogger::Log(clientid, "Fatal error during backup. Backup not completed", LL_ERROR); } running_updater->stop(); updateRunning(false); Server->destroy(tmp); Server->deleteFile(tmpfilename); setBackupDone(); if(c_has_error) return false; return !r_offline; } bool BackupServerGet::hasChange(size_t line, const std::vector<size_t> &diffs) { return std::binary_search(diffs.begin(), diffs.end(), line); } void BackupServerGet::hashFile(std::wstring dstpath, IFile *fd) { unsigned int l_backup_id=backupid; CWData data; data.addString(Server->ConvertToUTF8(fd->getFilenameW())); data.addUInt(l_backup_id); data.addChar(r_incremental==true?1:0); data.addString(Server->ConvertToUTF8(dstpath)); ServerLogger::Log(clientid, "GT: Loaded file \""+ExtractFileName(Server->ConvertToUTF8(dstpath))+"\"", LL_DEBUG); Server->destroy(fd); hashpipe_prepare->Write(data.getDataPtr(), data.getDataSize() ); } bool BackupServerGet::constructBackupPath(void) { time_t tt=time(NULL); #ifdef _WIN32 tm lt; tm *t=&lt; localtime_s(t, &tt); #else tm *t=localtime(&tt); #endif char buffer[500]; strftime(buffer, 500, "%y%m%d-%H%M", t); backuppath_single=widen((std::string)buffer); std::wstring backupfolder=server_settings->getSettings()->backupfolder; backuppath=backupfolder+os_file_sep()+clientname+os_file_sep()+backuppath_single; return os_create_dir(os_file_prefix()+backuppath); } std::wstring BackupServerGet::constructImagePath(const std::wstring &letter) { time_t tt=time(NULL); #ifdef _WIN32 tm lt; tm *t=&lt; localtime_s(t, &tt); #else tm *t=localtime(&tt); #endif char buffer[500]; strftime(buffer, 500, "%y%m%d-%H%M", t); std::wstring backupfolder_uncompr=server_settings->getSettings()->backupfolder_uncompr; return backupfolder_uncompr+os_file_sep()+clientname+os_file_sep()+L"Image_"+letter+L"_"+widen((std::string)buffer)+L".vhd"; } void BackupServerGet::updateLastBackup(void) { q_set_last_backup->Bind(clientid); q_set_last_backup->Write(); q_set_last_backup->Reset(); } void BackupServerGet::updateLastImageBackup(void) { q_set_last_image_backup->Bind(clientid); q_set_last_image_backup->Write(); q_set_last_image_backup->Reset(); } std::string BackupServerGet::sendClientMessage(const std::string &msg, const std::wstring &errmsg, unsigned int timeout, bool logerr) { CTCPStack tcpstack; IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { if(logerr) ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed: "+errmsg, LL_ERROR); else Server->Log(L"Connecting to ClientService of \""+clientname+L"\" failed: "+errmsg, LL_DEBUG); return ""; } tcpstack.Send(cc, server_identity+msg); std::string ret; unsigned int starttime=Server->getTimeMS(); bool ok=false; bool herr=false; while(Server->getTimeMS()-starttime<=timeout) { size_t rc=cc->Read(&ret, timeout); if(rc==0) { ServerLogger::Log(clientid, errmsg, LL_ERROR); break; } tcpstack.AddData((char*)ret.c_str(), ret.size()); size_t packetsize; char *pck=tcpstack.getPacket(&packetsize); if(pck!=NULL && packetsize>0) { ret.resize(packetsize); memcpy(&ret[0], pck, packetsize); delete [] pck; Server->destroy(cc); return ret; } } ServerLogger::Log(clientid, L"Timeout: "+errmsg, LL_ERROR); Server->destroy(cc); return ""; } bool BackupServerGet::sendClientMessage(const std::string &msg, const std::string &retok, const std::wstring &errmsg, unsigned int timeout, bool logerr) { CTCPStack tcpstack; IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { if(logerr) ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed: "+errmsg, LL_ERROR); else Server->Log(L"Connecting to ClientService of \""+clientname+L"\" failed: "+errmsg, LL_DEBUG); return false; } tcpstack.Send(cc, server_identity+msg); std::string ret; unsigned int starttime=Server->getTimeMS(); bool ok=false; bool herr=false; while(Server->getTimeMS()-starttime<=timeout) { size_t rc=cc->Read(&ret, timeout); if(rc==0) { if(logerr) ServerLogger::Log(clientid, errmsg, LL_ERROR); else Server->Log(errmsg, LL_ERROR); break; } tcpstack.AddData((char*)ret.c_str(), ret.size()); size_t packetsize; char *pck=tcpstack.getPacket(&packetsize); if(pck!=NULL && packetsize>0) { ret=pck; delete [] pck; if(ret!=retok) { herr=true; if(logerr) ServerLogger::Log(clientid, errmsg, LL_ERROR); else Server->Log(errmsg, LL_ERROR); break; } else { ok=true; break; } } } if(!ok && !herr) { if(logerr) ServerLogger::Log(clientid, L"Timeout: "+errmsg, LL_ERROR); else Server->Log(L"Timeout: "+errmsg, LL_ERROR); } Server->destroy(cc); return ok; } void BackupServerGet::start_shadowcopy(const std::string &path) { sendClientMessage("START SC \""+path+"\"#token="+server_token, "DONE", L"Activating shadow copy on \""+clientname+L"\" failed", shadow_copy_timeout); } void BackupServerGet::stop_shadowcopy(const std::string &path) { sendClientMessage("STOP SC \""+path+"\"#token="+server_token, "DONE", L"Removing shadow copy on \""+clientname+L"\" failed", shadow_copy_timeout); } void BackupServerGet::notifyClientBackupSuccessfull(void) { sendClientMessage("DID BACKUP", "OK", L"Sending status to client failed", 10000); } void BackupServerGet::sendClientBackupIncrIntervall(void) { sendClientMessage("INCRINTERVALL \""+nconvert(server_settings->getSettings()->update_freq_incr)+"\"", "OK", L"Sending incrintervall to client failed", 10000); } bool BackupServerGet::updateCapabilities(void) { std::string cap=sendClientMessage("CAPA", L"Querying capabilities failed", 10000, false); if(cap!="ERR" && !cap.empty()) { str_map params; ParseParamStr(cap, &params); if(params[L"IMAGE"]!=L"1") { Server->Log("Client doesn't have IMAGE capability", LL_DEBUG); can_backup_images=false; } str_map::iterator it=params.find(L"FILESRV"); if(it!=params.end()) { filesrv_protocol_version=watoi(it->second); } } return !cap.empty(); } void BackupServerGet::sendSettings(void) { std::string s_settings; std::vector<std::wstring> settings_names=getSettingsList(); for(size_t i=0;i<settings_names.size();++i) { std::wstring key=settings_names[i]; std::wstring value; if(!settings_client->getValue(key, &value) ) { if(!settings->getValue(key, &value) ) key=L""; else key+=L"_def"; } if(!key.empty()) { s_settings+=Server->ConvertToUTF8(key)+"="+Server->ConvertToUTF8(value)+"\n"; } } escapeClientMessage(s_settings); sendClientMessage("SETTINGS "+s_settings, "OK", L"Sending settings to client failed", 10000); } bool BackupServerGet::getClientSettings(void) { FileClient fc(filesrv_protocol_version); sockaddr_in addr=getClientaddr(); _u32 rc=fc.Connect(&addr); if(rc!=ERR_CONNECTED) { ServerLogger::Log(clientid, L"Getting Client settings of "+clientname+L" failed - CONNECT error", LL_ERROR); return false; } IFile *tmp=Server->openTemporaryFile(); if(tmp==NULL) { ServerLogger::Log(clientid, "Error creating temporary file in BackupServerGet::getClientSettings", LL_ERROR); return false; } rc=fc.GetFile("urbackup/settings.cfg", tmp); if(rc!=ERR_SUCCESS) { ServerLogger::Log(clientid, L"Error getting Client settings of "+clientname+L". Errorcode: "+convert(rc), LL_ERROR); return false; } ISettingsReader *sr=Server->createFileSettingsReader(tmp->getFilename()); std::vector<std::wstring> setting_names=getSettingsList(); bool mod=false; for(size_t i=0;i<setting_names.size();++i) { std::wstring &key=setting_names[i]; std::wstring value; if(sr->getValue(key, &value) ) { bool b=updateClientSetting(key, value); if(b) mod=true; } } Server->destroy(sr); bool b=updateClientSetting(L"client_overwrite", L"true"); if(b) mod=true; std::string tmp_fn=tmp->getFilename(); Server->destroy(tmp); Server->deleteFile(tmp_fn); if(mod) { server_settings->update(); unloadSQL(); prepareSQL(); } return true; } bool BackupServerGet::updateClientSetting(const std::wstring &key, const std::wstring &value) { std::wstring tmp; if(settings_client->getValue(key, &tmp)==false ) { q_insert_setting->Bind(key); q_insert_setting->Bind(value); q_insert_setting->Bind(clientid); q_insert_setting->Write(); q_insert_setting->Reset(); return true; } else if(tmp!=value) { q_update_setting->Bind(value); q_update_setting->Bind(key); q_update_setting->Bind(clientid); q_update_setting->Write(); q_update_setting->Reset(); return true; } return false; } void BackupServerGet::setBackupComplete(void) { q_set_complete->Bind(backupid); q_set_complete->Write(); q_set_complete->Reset(); } void BackupServerGet::setBackupDone(void) { q_set_done->Bind(backupid); q_set_done->Write(); q_set_done->Reset(); } void BackupServerGet::setBackupImageComplete(void) { q_set_image_complete->Bind(backupid); q_set_image_complete->Write(); q_set_image_complete->Reset(); } void BackupServerGet::sendToPipe(const std::string &msg) { pipe->Write(msg); } int BackupServerGet::getPCDone(void) { SStatus st=ServerStatus::getStatus(clientname); if(!st.has_status) return 0; else return st.pcdone; } void BackupServerGet::sendClientLogdata(void) { q_get_unsent_logdata->Bind(clientid); db_results res=q_get_unsent_logdata->Read(); q_get_unsent_logdata->Reset(); for(size_t i=0;i<res.size();++i) { std::string logdata=Server->ConvertToUTF8(res[i][L"logdata"]); escapeClientMessage(logdata); sendClientMessage("2LOGDATA "+wnarrow(res[i][L"created"])+" "+logdata, "OK", L"Sending logdata to client failed", 10000); q_set_logdata_sent->Bind(res[i][L"id"]); q_set_logdata_sent->Write(); q_set_logdata_sent->Reset(); } } void BackupServerGet::saveClientLogdata(int image, int incremental, bool r_success) { int errors=0; int warnings=0; int infos=0; std::wstring logdata=ServerLogger::getLogdata(clientid, errors, warnings, infos); q_save_logdata->Bind(clientid); q_save_logdata->Bind(logdata); q_save_logdata->Bind(errors); q_save_logdata->Bind(warnings); q_save_logdata->Bind(infos); q_save_logdata->Bind(image); q_save_logdata->Bind(incremental); q_save_logdata->Write(); q_save_logdata->Reset(); sendLogdataMail(r_success, image, incremental, errors, warnings, infos, logdata); ServerLogger::reset(clientid); } std::wstring BackupServerGet::getUserRights(int userid, std::string domain) { if(domain!="all") { if(getUserRights(userid, "all")==L"all") return L"all"; } q_get_rights->Bind(userid); q_get_rights->Bind(domain); db_results res=q_get_rights->Read(); q_get_rights->Reset(); if(!res.empty()) { return res[0][L"t_right"]; } else { return L"none"; } } void BackupServerGet::sendLogdataMail(bool r_success, int image, int incremental, int errors, int warnings, int infos, std::wstring &data) { MailServer mail_server=getMailServerSettings(); if(mail_server.servername.empty()) return; if(url_fak==NULL) return; db_results res_users=q_get_users->Read(); q_get_users->Reset(); for(size_t i=0;i<res_users.size();++i) { std::wstring logr=getUserRights(watoi(res_users[i][L"id"]), "logs"); bool has_r=false; if(logr!=L"all") { std::vector<std::wstring> toks; Tokenize(logr, toks, L","); for(size_t j=0;j<toks.size();++j) { if(toks[j]==res_users[i][L"id"]) { has_r=true; } } } else { has_r=true; } if(has_r) { q_get_report_settings->Bind(watoi(res_users[i][L"id"])); db_results res=q_get_report_settings->Read(); q_get_report_settings->Reset(); if(!res.empty()) { std::wstring report_mail=res[0][L"report_mail"]; int report_loglevel=watoi(res[0][L"report_loglevel"]); int report_sendonly=watoi(res[0][L"report_sendonly"]); if( ( ( report_loglevel==0 && infos>0 ) || ( report_loglevel<=1 && warnings>0 ) || ( report_loglevel<=2 && errors>0 ) ) && (report_sendonly==0 || ( report_sendonly==1 && !r_success ) || ( report_sendonly==2 && r_success)) ) { std::vector<std::string> to_addrs; Tokenize(Server->ConvertToUTF8(report_mail), to_addrs, ",;"); std::string subj="UrBackup: "; std::string msg="UrBackup just did "; if(incremental>0) { msg+="an incremental "; subj="Incremental "; } else { msg+="a full "; subj="Full "; } if(image>0) { msg+="image "; subj+="image "; } else { msg+="file "; subj+="file "; } subj+="backup of \""+Server->ConvertToUTF8(clientname)+"\"\n"; msg+="backup of \""+Server->ConvertToUTF8(clientname)+"\".\n"; msg+="\nReport:\n"; msg+="( "+nconvert(infos); if(infos!=1) msg+=" infos, "; else msg+=" info, "; msg+=nconvert(warnings); if(warnings!=1) msg+=" warnings, "; else msg+=" warning, "; msg+=nconvert(errors); if(errors!=1) msg+=" errors"; else msg+=" error"; msg+=" )\n\n"; std::vector<std::wstring> msgs; TokenizeMail(data, msgs, L"\n"); for(size_t j=0;j<msgs.size();++j) { std::wstring ll; if(!msgs[j].empty()) ll=msgs[j][0]; int li=watoi(ll); msgs[j].erase(0, 2); std::wstring tt=getuntil(L"-", msgs[j]); std::wstring m=getafter(L"-", msgs[j]); q_format_unixtime->Bind(tt); db_results ft=q_format_unixtime->Read(); q_format_unixtime->Reset(); if( !ft.empty() ) { tt=ft[0][L"time"]; } std::string lls="info"; if(li==1) lls="warning"; else if(li==2) lls="error"; msg+=Server->ConvertToUTF8(tt)+"("+lls+"): "+Server->ConvertToUTF8(m)+"\n"; } if(!r_success) subj+=" - failed"; else subj+=" - success"; std::string errmsg; bool b=url_fak->sendMail(mail_server, to_addrs, subj, msg, &errmsg); if(!b) { Server->Log("Sending mail failed. "+errmsg, LL_WARNING); } } } } } } MailServer BackupServerGet::getMailServerSettings(void) { ISettingsReader *settings=Server->createDBSettingsReader(Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER), "settings_db.settings", "SELECT value FROM settings WHERE key=? AND clientid=0"); MailServer ms; ms.servername=settings->getValue("mail_servername", ""); ms.port=(unsigned short)watoi(settings->getValue(L"mail_serverport", L"587")); ms.username=settings->getValue("mail_username", ""); ms.password=settings->getValue("mail_password", ""); ms.mailfrom=settings->getValue("mail_from", ""); if(ms.mailfrom.empty()) ms.mailfrom="report@urbackup.org"; ms.ssl_only=(settings->getValue("mail_ssl_only", "false")=="true")?true:false; ms.check_certificate=(settings->getValue("mail_check_certificate", "false")=="true")?true:false; Server->destroy(settings); return ms; } const unsigned int stat_update_skip=20; const unsigned int sector_size=512; const unsigned int sha_size=32; void writeZeroblockdata(void) { const int64 vhd_blocksize=(1024*1024/2); unsigned char *zeroes=new unsigned char[vhd_blocksize]; memset(zeroes, 0, vhd_blocksize); unsigned char dig[sha_size]; sha256(zeroes, vhd_blocksize, dig); IFile *out=Server->openFile("zero.hash", MODE_WRITE); out->Write((char*)dig, sha_size); Server->destroy(out); delete []zeroes; } bool BackupServerGet::doImage(const std::string &pLetter, const std::wstring &pParentvhd, int incremental, int incremental_ref) { CTCPStack tcpstack; IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed - CONNECT error", LL_ERROR); return false; } std::string sletter=pLetter; if(pLetter!="SYSVOL") { sletter=pLetter[0]; } if(pParentvhd.empty()) { tcpstack.Send(cc, server_identity+"FULL IMAGE letter="+pLetter+"&token="+server_token); } else { IFile *hashfile=Server->openFile(os_file_prefix()+pParentvhd+L".hash"); if(hashfile==NULL) { ServerLogger::Log(clientid, "Error opening hashfile", LL_ERROR); Server->Log("Starting image path repair...", LL_INFO); ServerUpdateStats::repairImages(); Server->destroy(cc); return false; } std::string ts=server_identity+"INCR IMAGE letter="+pLetter+"&hashsize="+nconvert(hashfile->Size())+"&token="+server_token; size_t rc=tcpstack.Send(cc, ts); if(rc==0) { ServerLogger::Log(clientid, "Sending 'INCR IMAGE' command failed", LL_ERROR); Server->destroy(cc); Server->destroy(hashfile); return false; } hashfile->Seek(0); char buffer[4096]; for(size_t i=0,hsize=(size_t)hashfile->Size();i<hsize;i+=4096) { size_t tsend=(std::min)((size_t)4096, hsize-i); if(hashfile->Read(buffer, (_u32)tsend)!=tsend) { ServerLogger::Log(clientid, "Reading from hashfile failed", LL_ERROR); Server->destroy(cc); Server->destroy(hashfile); return false; } if(!cc->Write(buffer, tsend)) { ServerLogger::Log(clientid, "Sending hashdata failed", LL_ERROR); Server->destroy(cc); Server->destroy(hashfile); return false; } } Server->destroy(hashfile); } std::wstring imagefn=constructImagePath(widen(sletter)); int64 free_space=os_free_space(os_file_prefix()+ExtractFilePath(imagefn)); if(free_space!=-1 && free_space<minfreespace_image) { ServerLogger::Log(clientid, "Not enough free space. Cleaning up.", LL_INFO); ServerCleanupThread cleanup; if(!cleanup.do_cleanup(minfreespace_image) ) { ServerLogger::Log(clientid, "Could not free space for image. NOT ENOUGH FREE SPACE.", LL_ERROR); Server->destroy(cc); return false; } } { std::string mbrd=getMBR(widen(sletter)); if(mbrd.empty()) { if(pLetter!="SYSVOL") { ServerLogger::Log(clientid, "Error getting MBR data", LL_ERROR); } } else { IFile *mbr_file=Server->openFile(os_file_prefix()+imagefn+L".mbr", MODE_WRITE); if(mbr_file!=NULL) { _u32 w=mbr_file->Write(mbrd); if(w!=mbrd.size()) { Server->Log("Error writing mbr data.", LL_ERROR); Server->destroy(mbr_file); Server->destroy(cc); return false; } Server->destroy(mbr_file); } else { Server->Log("Error creating file for writing MBR data.", LL_ERROR); Server->destroy(cc); return false; } } } if(pParentvhd.empty()) backupid=createBackupImageSQL(0,0, clientid, imagefn, pLetter); else backupid=createBackupImageSQL(incremental, incremental_ref, clientid, imagefn, pLetter); std::string ret; unsigned int starttime=Server->getTimeMS(); bool first=true; char buffer[4096]; unsigned int blocksize=0xFFFFFFFF; unsigned int blockleft=0; int64 currblock=-1; char *blockdata=NULL; int64 drivesize; ServerVHDWriter *vhdfile=NULL; THREADPOOL_TICKET vhdfile_ticket; IVHDFile *r_vhdfile=NULL; IFile *hashfile=NULL; IFile *parenthashfile=NULL; int64 blockcnt=0; int64 numblocks=0; int64 totalblocks=0; int64 mbr_offset=0; _u32 off=0; std::string shadowdrive; int shadow_id=-1; bool persistent=false; unsigned char *zeroblockdata=NULL; int64 nextblock=0; int64 vhd_blocksize=(1024*1024)/2; ServerRunningUpdater *running_updater=new ServerRunningUpdater(backupid, true); Server->getThreadPool()->execute(running_updater); bool has_parent=false; if(!pParentvhd.empty()) has_parent=true; sha256_ctx shactx; sha256_init(&shactx); unsigned int stat_update_cnt=0; while(Server->getTimeMS()-starttime<=image_timeout) { size_t r=cc->Read(&buffer[off], 4096-off, image_recv_timeout); if(r!=0) r+=off; starttime=Server->getTimeMS(); off=0; if(r==0 ) { if(persistent && nextblock!=0) { bool reconnected=false; while(Server->getTimeMS()-starttime<=image_timeout) { ServerStatus::setROnline(clientname, false); if(cc!=NULL) Server->destroy(cc); Server->Log("Trying to reconnect in doImage", LL_DEBUG); cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { std::string msg; if(pipe->Read(&msg, 0)>0) { if(msg.find("address")==0) { IScopedLock lock(clientaddr_mutex); memcpy(&clientaddr, &msg[7], sizeof(sockaddr_in) ); } else { pipe->Write(msg); } Server->wait(60000); } } else { reconnected=true; ServerStatus::setROnline(clientname, true); Server->Log("Reconnected.", LL_DEBUG); break; } } if(!reconnected) { ServerLogger::Log(clientid, "Timeout while trying to reconnect", LL_ERROR); goto do_image_cleanup; } if(pParentvhd.empty()) { tcpstack.Send(cc, server_identity+"FULL IMAGE letter="+pLetter+"&shadowdrive="+shadowdrive+"&start="+nconvert(nextblock)+"&shadowid="+nconvert(shadow_id)); } else { std::string ts="INCR IMAGE letter=C:&shadowdrive="+shadowdrive+"&start="+nconvert(nextblock)+"&shadowid="+nconvert(shadow_id)+"&hashsize="+nconvert(parenthashfile->Size()); size_t rc=tcpstack.Send(cc, server_identity+ts); if(rc==0) { ServerLogger::Log(clientid, "Sending 'INCR IMAGE' command failed", LL_ERROR); goto do_image_cleanup; } parenthashfile->Seek(0); char buffer[4096]; for(size_t i=0,hsize=(size_t)parenthashfile->Size();i<hsize;i+=4096) { size_t tsend=(std::min)((size_t)4096, hsize-i); if(parenthashfile->Read(buffer, (_u32)tsend)!=tsend) { ServerLogger::Log(clientid, "Reading from hashfile failed i="+nconvert(i), LL_ERROR); goto do_image_cleanup; } if(!cc->Write(buffer, tsend)) { ServerLogger::Log(clientid, "Sending hashdata failed", LL_ERROR); goto do_image_cleanup; } } } off=0; starttime=Server->getTimeMS(); blockleft=0; currblock=-1; } else { ServerLogger::Log(clientid, "Pipe to client unexpectedly closed", LL_ERROR); goto do_image_cleanup; } } else { if(first) { first=false; if(r>=sizeof(unsigned int)) { memcpy(&blocksize, buffer, sizeof(unsigned int) ); off+=sizeof(unsigned int); vhd_blocksize/=blocksize; } if(blocksize==0xFFFFFFFF) { off+=sizeof(unsigned int); if(r>sizeof(uint64)) { std::string err; err.resize(r-sizeof(uint64) ); memcpy(&err[0], &buffer[off], r-off); if(pLetter!="SYSVOL") { ServerLogger::Log(clientid, "Request of image backup failed. Reason: "+err, LL_ERROR); } else { ServerLogger::Log(clientid, "Request of SYSVOL failed. Reason: "+err, LL_INFO); } } else { ServerLogger::Log(clientid, "Error on client. No reason given.", LL_ERROR); } goto do_image_cleanup; } bool issmall=false; if(r>=sizeof(unsigned int)+sizeof(int64)) { memcpy(&drivesize, &buffer[off], sizeof(int64) ); off+=sizeof(int64); blockcnt=drivesize/blocksize; totalblocks=blockcnt; zeroblockdata=new unsigned char[blocksize]; memset(zeroblockdata, 0, blocksize); if(!has_parent) r_vhdfile=image_fak->createVHDFile(os_file_prefix()+imagefn, false, drivesize+(int64)mbr_size, (unsigned int)vhd_blocksize*blocksize); else r_vhdfile=image_fak->createVHDFile(os_file_prefix()+imagefn, pParentvhd, false); if(r_vhdfile==NULL) { ServerLogger::Log(clientid, L"Error opening VHD file \""+imagefn+L"\"", LL_ERROR); goto do_image_cleanup; } vhdfile=new ServerVHDWriter(r_vhdfile, blocksize, 5000, clientid); vhdfile_ticket=Server->getThreadPool()->execute(vhdfile); blockdata=vhdfile->getBuffer(); hashfile=Server->openFile(os_file_prefix()+imagefn+L".hash", MODE_WRITE); if(hashfile==NULL) { ServerLogger::Log(clientid, L"Error opening Hashfile \""+imagefn+L".hash\"", LL_ERROR); goto do_image_cleanup; } if(has_parent) { parenthashfile=Server->openFile(os_file_prefix()+pParentvhd+L".hash", MODE_READ); if(parenthashfile==NULL) { ServerLogger::Log(clientid, L"Error opening Parenthashfile \""+pParentvhd+L".hash\"", LL_ERROR); goto do_image_cleanup; } } mbr_offset=writeMBR(vhdfile, drivesize); } else { issmall=true; } if(r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)) { memcpy(&blockcnt, &buffer[off], sizeof(int64) ); off+=sizeof(int64); } else { issmall=true; } if(r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)+1) { char c_persistent=buffer[off]; if(c_persistent!=0) persistent=true; ++off; } else { issmall=true; } unsigned int shadowdrive_size=0; if(r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)+1+sizeof(unsigned int)) { memcpy(&shadowdrive_size, &buffer[off], sizeof(unsigned int)); off+=sizeof(unsigned int); if(shadowdrive_size>0) { if( r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)+1+sizeof(unsigned int)+shadowdrive_size) { shadowdrive.resize(shadowdrive_size); memcpy(&shadowdrive[0], &buffer[off], shadowdrive_size); off+=shadowdrive_size; } else { issmall=true; } } } else { issmall=true; } if(r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)+1+sizeof(unsigned int)+shadowdrive_size+sizeof(int)) { memcpy(&shadow_id, &buffer[off], sizeof(int)); off+=sizeof(int); } else { issmall=true; } if(issmall) { ServerLogger::Log(clientid, "First packet to small", LL_ERROR); goto do_image_cleanup; } if(r==off) { off=0; continue; } } while(true) { if(blockleft==0) { if(currblock!=-1) // write current block { ++numblocks; ++stat_update_cnt; if(stat_update_cnt%stat_update_skip==0) { stat_update_cnt=0; if(blockcnt!=0) { if(has_parent) { status.pcdone=(int)(((double)currblock/(double)totalblocks)*100.0+0.5); } else { status.pcdone=(int)(((double)numblocks/(double)blockcnt)*100.0+0.5); } ServerStatus::setServerStatus(status, true); } } nextblock=updateNextblock(nextblock, currblock, &shactx, zeroblockdata, has_parent, vhdfile, hashfile, parenthashfile, blocksize, mbr_offset, vhd_blocksize); sha256_update(&shactx, (unsigned char *)blockdata, blocksize); vhdfile->writeBuffer(mbr_offset+currblock*blocksize, blockdata, blocksize); blockdata=vhdfile->getBuffer(); if(nextblock%vhd_blocksize==0 && nextblock!=0) { //Server->Log("Hash written "+nconvert(currblock), LL_DEBUG); unsigned char dig[sha_size]; sha256_final(&shactx, dig); hashfile->Write((char*)dig, sha_size); sha256_init(&shactx); } if(vhdfile->hasError()) { ServerLogger::Log(clientid, "FATAL ERROR: Could not write to VHD-File", LL_ERROR); goto do_image_cleanup; } currblock=-1; } if(r-off>=sizeof(int64) ) { memcpy(&currblock, &buffer[off], sizeof(int64) ); if(currblock==-123) { int64 t_totalblocks=totalblocks; if(t_totalblocks%vhd_blocksize!=0) t_totalblocks+=vhd_blocksize-t_totalblocks%vhd_blocksize; nextblock=updateNextblock(nextblock, t_totalblocks, &shactx, zeroblockdata, has_parent, vhdfile, hashfile, parenthashfile, blocksize, mbr_offset, vhd_blocksize); if(nextblock%vhd_blocksize==0 && nextblock!=0) { //Server->Log("Hash written "+nconvert(nextblock), LL_INFO); unsigned char dig[sha_size]; sha256_final(&shactx, dig); hashfile->Write((char*)dig, sha_size); } Server->destroy(cc); if(hashfile!=NULL) Server->destroy(hashfile); if(vhdfile!=NULL) { vhdfile->freeBuffer(blockdata); } if(parenthashfile!=NULL) Server->destroy(parenthashfile); bool vhdfile_err=false; status.action_done=true; ServerStatus::setServerStatus(status); if(vhdfile!=NULL) { vhdfile->doExit(); Server->getThreadPool()->waitFor(vhdfile_ticket); vhdfile_err=vhdfile->hasError(); delete vhdfile; vhdfile=NULL; } IFile *t_file=Server->openFile(os_file_prefix()+imagefn, MODE_READ); if(t_file!=NULL) { db->BeginTransaction(); q_set_image_size->Bind(t_file->Size()); q_set_image_size->Bind(backupid); q_set_image_size->Write(); q_set_image_size->Reset(); q_update_images_size->Bind(clientid); q_update_images_size->Bind(t_file->Size()); q_update_images_size->Bind(clientid); q_update_images_size->Write(); q_update_images_size->Reset(); if(vhdfile_err==false) { setBackupImageComplete(); } db->EndTransaction(); Server->destroy(t_file); } running_updater->stop(); updateRunning(true); return !vhdfile_err; } else if(currblock==-124 || #ifndef _WIN32 currblock==0xFFFFFFFFFFFFFFFFLLU) #else currblock==0xFFFFFFFFFFFFFFFF) #endif { if(r-off>sizeof(int64)) { std::string err; err.resize(r-off-sizeof(int64) ); memcpy(&err[0], &buffer[off+sizeof(int64)], r-off-sizeof(int64)); ServerLogger::Log(clientid, "Error on client occured: "+err, LL_ERROR); } Server->destroy(cc); if(vhdfile!=NULL) { vhdfile->freeBuffer(blockdata); vhdfile->doExitNow(); std::vector<THREADPOOL_TICKET> wf;wf.push_back(vhdfile_ticket); Server->getThreadPool()->waitFor(wf); delete vhdfile; vhdfile=NULL; } if(hashfile!=NULL) Server->destroy(hashfile); if(parenthashfile!=NULL) Server->destroy(parenthashfile); running_updater->stop(); return false; } else if(currblock==-125) //ping { off+=sizeof(int64); currblock=-1; } else { off+=sizeof(int64); blockleft=blocksize; } } else if(r-off>0) { char buf2[4096]; memcpy(buf2, &buffer[off], r-off); memcpy(buffer, buf2, r-off); off=(_u32)r-off; break; } else { off=0; break; } } else { unsigned int available=(std::min)(blockleft, (unsigned int)r-off); memcpy(&blockdata[blocksize-blockleft], &buffer[off], available); blockleft-=available; off+=available; if( off>=r ) { off=0; break; } } } } } ServerLogger::Log(clientid, "Timeout while transfering image data", LL_ERROR); do_image_cleanup: Server->destroy(cc); if(vhdfile!=NULL) { if(blockdata!=NULL) vhdfile->freeBuffer(blockdata); vhdfile->doExitNow(); Server->getThreadPool()->waitFor(vhdfile_ticket); delete vhdfile; vhdfile=NULL; } if(hashfile!=NULL) Server->destroy(hashfile); if(parenthashfile!=NULL) Server->destroy(parenthashfile); running_updater->stop(); return false; } unsigned int BackupServerGet::writeMBR(ServerVHDWriter *vhdfile, uint64 volsize) { unsigned char *mbr=(unsigned char *)vhdfile->getBuffer(); unsigned char *mptr=mbr; memcpy(mptr, mbr_code, 440); mptr+=440; int sig=rand(); memcpy(mptr, &sig, sizeof(int)); mptr+=sizeof(int); *mptr=0; ++mptr; *mptr=0; ++mptr; unsigned char partition[16]; partition[0]=0x80; partition[1]=0xfe; partition[2]=0xff; partition[3]=0xff; partition[4]=0x07; //ntfs partition[5]=0xfe; partition[6]=0xff; partition[7]=0xff; partition[8]=0x00; partition[9]=0x04; partition[10]=0x00; partition[11]=0x00; unsigned int sectors=(unsigned int)(volsize/((uint64)sector_size)); memcpy(&partition[12], &sectors, sizeof(unsigned int) ); memcpy(mptr, partition, 16); mptr+=16; for(int i=0;i<3;++i) { memset(mptr, 0, 16); mptr+=16; } *mptr=0x55; ++mptr; *mptr=0xaa; vhdfile->writeBuffer(0, (char*)mbr, 512); for(int i=0;i<1023;++i) { char *buf=vhdfile->getBuffer(); memset(buf, 0, 512); vhdfile->writeBuffer((i+1)*512, buf, 512); } return 1024*512; } int64 BackupServerGet::updateNextblock(int64 nextblock, int64 currblock, sha256_ctx *shactx, unsigned char *zeroblockdata, bool parent_fn, ServerVHDWriter *parentfile, IFile *hashfile, IFile *parenthashfile, unsigned int blocksize, int64 mbr_offset, int64 vhd_blocksize) { unsigned char *blockdata=NULL; if(parent_fn) blockdata=new unsigned char[blocksize]; if(currblock-nextblock>vhd_blocksize) { while(true) { if(!parent_fn) { sha256_update(shactx, zeroblockdata, blocksize); } else { { IScopedLock lock(parentfile->getVHDMutex()); IVHDFile *vhd=parentfile->getVHD(); vhd->Seek(mbr_offset+nextblock*blocksize); size_t read; bool b=vhd->Read((char*)blockdata, blocksize, read); if(!b) Server->Log("Reading from VHD failed", LL_ERROR); } sha256_update(shactx, blockdata, blocksize); } ++nextblock; if(nextblock%vhd_blocksize==0) { unsigned char dig[sha_size]; sha256_final(shactx, dig); hashfile->Write((char*)dig, sha_size); sha256_init(shactx); break; } } while(currblock-nextblock>vhd_blocksize) { if(!parent_fn) { hashfile->Write((char*)zero_hash, sha_size); } else { bool b=parenthashfile->Seek((nextblock/vhd_blocksize)*sha_size); if(!b) { Server->Log("Seeking in parenthashfile failed", LL_ERROR); } char dig[sha_size]; _u32 rc=parenthashfile->Read(dig, sha_size); if(rc!=sha_size) Server->Log("Writing to parenthashfile failed", LL_ERROR); hashfile->Write(dig, sha_size); } nextblock+=vhd_blocksize; } } while(nextblock<currblock) { if(!parent_fn) { sha256_update(shactx, zeroblockdata, blocksize); } else { { IScopedLock lock(parentfile->getVHDMutex()); IVHDFile *vhd=parentfile->getVHD(); vhd->Seek(mbr_offset+nextblock*blocksize); size_t read; bool b=vhd->Read((char*)blockdata, blocksize, read); if(!b) Server->Log("Reading from VHD failed", LL_ERROR); } sha256_update(shactx, blockdata, blocksize); } ++nextblock; if(nextblock%vhd_blocksize==0 && nextblock!=0) { unsigned char dig[sha_size]; sha256_final(shactx, dig); hashfile->Write((char*)dig, sha_size); sha256_init(shactx); } } delete [] blockdata; return nextblock+1; } std::string BackupServerGet::getMBR(const std::wstring &dl) { std::string ret=sendClientMessage("MBR driveletter="+wnarrow(dl), L"Getting MBR for drive "+dl+L" failed", 10000); CRData r(&ret); char b; if(r.getChar(&b) && b==1 ) { char ver; if(r.getChar(&ver) ) { if(ver!=0) { ServerLogger::Log(clientid, L"Server version does not fit", LL_ERROR); } else { return ret; } } else { ServerLogger::Log(clientid, L"Could not read version information in MBR", LL_ERROR); } } else if(dl!=L"SYSVOL") { ServerLogger::Log(clientid, L"Could not read MBR", LL_ERROR); } return ""; } void BackupServerGet::checkClientVersion(void) { std::string version=getFile("urbackup/version.txt"); if(!version.empty()) { std::string r=sendClientMessage("VERSION "+version, L"Sending version to client failed", 10000); if(r=="update") { IFile *sigfile=Server->openFile("urbackup/UrBackupUpdate.sig", MODE_READ); if(sigfile==NULL) { ServerLogger::Log(clientid, "Error opening sigfile", LL_ERROR); return; } IFile *updatefile=Server->openFile("urbackup/UrBackupUpdate.exe", MODE_READ); if(updatefile==NULL) { ServerLogger::Log(clientid, "Error opening updatefile", LL_ERROR); return; } size_t datasize=3*sizeof(unsigned int)+version.size()+(size_t)sigfile->Size()+(size_t)updatefile->Size(); CTCPStack tcpstack; IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed - CONNECT error", LL_ERROR); return; } std::string msg="CLIENTUPDATE "+nconvert(datasize); tcpstack.Send(cc, server_identity+msg); int timeout=10000; unsigned int c_size=(unsigned int)version.size(); if(!cc->Write((char*)&c_size, sizeof(unsigned int), timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } if(!cc->Write(version, timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } c_size=(unsigned int)sigfile->Size(); if(!cc->Write((char*)&c_size, sizeof(unsigned int), timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } if(!sendFile(cc, sigfile, timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } c_size=(unsigned int)updatefile->Size(); if(!cc->Write((char*)&c_size, sizeof(unsigned int), timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } if(!sendFile(cc, updatefile, timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } Server->destroy(sigfile); Server->destroy(updatefile); std::string ret; unsigned int starttime=Server->getTimeMS(); bool ok=false; while(Server->getTimeMS()-starttime<=10000) { size_t rc=cc->Read(&ret, timeout); if(rc==0) { ServerLogger::Log(clientid, "Reading from client failed in update", LL_ERROR); break; } tcpstack.AddData((char*)ret.c_str(), ret.size()); size_t packetsize; char *pck=tcpstack.getPacket(&packetsize); if(pck!=NULL && packetsize>0) { ret.resize(packetsize); memcpy(&ret[0], pck, packetsize); delete [] pck; if(ret=="ok") { ok=true; break; } else { ok=false; ServerLogger::Log(clientid, "Error in update: "+ret, LL_ERROR); break; } } } if(!ok) { ServerLogger::Log(clientid, L"Timeout: In client update", LL_ERROR); } Server->destroy(cc); ServerLogger::Log(clientid, L"Updated client successfully", LL_INFO); } } } bool BackupServerGet::sendFile(IPipe *cc, IFile *f, int timeout) { char buf[4096]; _u32 r; while((r=f->Read(buf, 4096))>0) { if(!cc->Write(buf, r, timeout)) return false; } return true; } sockaddr_in BackupServerGet::getClientaddr(void) { IScopedLock lock(clientaddr_mutex); return clientaddr; } std::string BackupServerGet::strftimeInt(std::string fs) { time_t rawtime; char buffer [100]; time ( &rawtime ); #ifdef _WIN32 struct tm timeinfo; localtime_s(&timeinfo, &rawtime); strftime (buffer,100,fs.c_str(),&timeinfo); #else struct tm *timeinfo; timeinfo = localtime ( &rawtime ); strftime (buffer,100,fs.c_str(),timeinfo); #endif std::string r(buffer); return r; } std::string BackupServerGet::remLeadingZeros(std::string t) { std::string r; bool in=false; for(size_t i=0;i<t.size();++i) { if(!in && t[i]!='0' ) in=true; if(in) { r+=t[i]; } } return r; } bool BackupServerGet::isInBackupWindow(std::vector<STimeSpan> bw) { if(bw.empty()) return true; int dow=atoi(strftimeInt("%w").c_str()); if(dow==0) dow=7; float hm=(float)atoi(remLeadingZeros(strftimeInt("%H")).c_str())+(float)atoi(remLeadingZeros(strftimeInt("%M")).c_str())*(1.f/60.f); for(size_t i=0;i<bw.size();++i) { if(bw[i].dayofweek==dow) { if(hm>=bw[i].start_hour && hm<=bw[i].stop_hour ) { return true; } } } return false; } bool BackupServerGet::isBackupsRunningOkay(void) { IScopedLock lock(running_backup_mutex); if(running_backups<server_settings->getSettings()->max_sim_backups) { return true; } else { return false; } } void BackupServerGet::startBackupRunning(bool file) { IScopedLock lock(running_backup_mutex); ++running_backups; if(file) { ++running_file_backups; } } void BackupServerGet::stopBackupRunning(bool file) { IScopedLock lock(running_backup_mutex); --running_backups; if(file) { --running_file_backups; } } int BackupServerGet::getNumberOfRunningBackups(void) { IScopedLock lock(running_backup_mutex); return running_backups; } int BackupServerGet::getNumberOfRunningFileBackups(void) { IScopedLock lock(running_backup_mutex); return running_file_backups; } void BackupServerGet::writeFileRepeat(IFile *f, const std::string &str) { writeFileRepeat(f, str.c_str(), str.size()); } void BackupServerGet::writeFileRepeat(IFile *f, const char *buf, size_t bsize) { _u32 written=0; _u32 rc; int tries=50; do { rc=f->Write(buf+written, (_u32)(bsize-written)); written+=rc; if(rc==0) { Server->Log("Failed to write to file... waiting...", LL_WARNING); Server->wait(10000); --tries; } } while(written<bsize && (rc>0 || tries>0) ); if(rc==0) { Server->Log("Fatal error writing to file in writeFileRepeat. Write error.", LL_ERROR); } } #endif //CLIENT_ONLY Fixed bug which leads to too many transfered files /************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #ifndef CLIENT_ONLY #include "server_get.h" #include "server_ping.h" #include "database.h" #include "../stringtools.h" #include "fileclient/FileClient.h" #include "../Interface/Server.h" #include "../Interface/ThreadPool.h" #include "fileclient/tcpstack.h" #include "fileclient/data.h" #include "../fsimageplugin/IFSImageFactory.h" #include "../fsimageplugin/IVHDFile.h" #include "server_channel.h" #include "server_log.h" #include "server_writer.h" #include "server_cleanup.h" #include "server_update_stats.h" #include "escape.h" #include "mbr_code.h" #include "zero_hash.h" #include "server_running.h" #include "treediff/TreeDiff.h" #include "../urlplugin/IUrlFactory.h" #include <time.h> #include <algorithm> #include <memory.h> extern IFSImageFactory *image_fak; extern IUrlFactory *url_fak; extern std::string server_identity; extern std::string server_token; const unsigned short serviceport=35623; const unsigned int full_backup_construct_timeout=4*60*60*1000; const unsigned int shadow_copy_timeout=30*60*1000; const unsigned int check_time_intervall_tried_backup=30*60*1000; const unsigned int check_time_intervall=5*60*1000; const unsigned int status_update_intervall=1000; const unsigned int mbr_size=(1024*1024)/2; const size_t minfreespace_image=1000*1024*1024; //1000 MB const size_t minfreespace_min=50*1024*1024; const unsigned int curr_image_version=1; const unsigned int image_timeout=10*24*60*60*1000; const unsigned int image_recv_timeout=1*60*60*1000; int BackupServerGet::running_backups=0; int BackupServerGet::running_file_backups=0; IMutex *BackupServerGet::running_backup_mutex=NULL; BackupServerGet::BackupServerGet(IPipe *pPipe, sockaddr_in pAddr, const std::wstring &pName) { q_update_lastseen=NULL; pipe=pPipe; clientaddr=pAddr; clientaddr_mutex=Server->createMutex(); clientname=pName; clientid=0; hashpipe=Server->createMemoryPipe(); hashpipe_prepare=Server->createMemoryPipe(); exitpipe=Server->createMemoryPipe(); exitpipe_prepare=Server->createMemoryPipe(); do_full_backup_now=false; do_incr_backup_now=false; do_update_settings=false; do_full_image_now=false; do_incr_image_now=false; can_backup_images=true; filesrv_protocol_version=0; } BackupServerGet::~BackupServerGet(void) { if(q_update_lastseen!=NULL) unloadSQL(); Server->destroy(clientaddr_mutex); } void BackupServerGet::init_mutex(void) { running_backup_mutex=Server->createMutex(); } void BackupServerGet::destroy_mutex(void) { Server->destroy(running_backup_mutex); } void BackupServerGet::unloadSQL(void) { db->destroyQuery(q_update_lastseen); db->destroyQuery(q_update_full); db->destroyQuery(q_update_incr); db->destroyQuery(q_create_backup); db->destroyQuery(q_get_last_incremental); db->destroyQuery(q_set_last_backup); db->destroyQuery(q_update_setting); db->destroyQuery(q_insert_setting); db->destroyQuery(q_set_complete); db->destroyQuery(q_update_image_full); db->destroyQuery(q_update_image_incr); db->destroyQuery(q_create_backup_image); db->destroyQuery(q_set_image_complete); db->destroyQuery(q_set_last_image_backup); db->destroyQuery(q_get_last_incremental_image); db->destroyQuery(q_set_image_size); db->destroyQuery(q_update_running_file); db->destroyQuery(q_update_running_image); db->destroyQuery(q_update_images_size); db->destroyQuery(q_set_done); db->destroyQuery(q_save_logdata); db->destroyQuery(q_get_unsent_logdata); db->destroyQuery(q_set_logdata_sent); db->destroyQuery(q_save_image_assoc); db->destroyQuery(q_get_users); db->destroyQuery(q_get_rights); db->destroyQuery(q_get_report_settings); db->destroyQuery(q_format_unixtime); } void BackupServerGet::operator ()(void) { { bool b=sendClientMessage("ADD IDENTITY", "OK", L"Sending Identity to client failed stopping...", 10000, false); if(!b) { pipe->Write("ok"); Server->Log(L"server_get Thread for client "+clientname+L" finished, because the identity was not recognized", LL_INFO); ServerStatus::setWrongIdent(clientname, true); ServerLogger::reset(clientid); delete this; return; } } if( clientname.find(L"##restore##")==0 ) { ServerChannelThread channel_thread(this, -1); THREADPOOL_TICKET channel_thread_id=Server->getThreadPool()->execute(&channel_thread); while(true) { std::string msg; pipe->Read(&msg); if(msg=="exit" || msg=="exitnow" ) break; } channel_thread.doExit(); Server->getThreadPool()->waitFor(channel_thread_id); pipe->Write("ok"); Server->Log(L"server_get Thread for client "+clientname+L" finished, restore thread"); delete this; return; } db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER); server_settings=new ServerSettings(db); clientid=getClientID(); if(clientid==-1) { pipe->Write("ok"); Server->Log(L"server_get Thread for client "+clientname+L" finished, because there were too many clients", LL_INFO); ServerStatus::setTooManyClients(clientname, true); ServerLogger::reset(clientid); delete server_settings; delete this; return; } settings=Server->createDBSettingsReader(db, "settings", "SELECT value FROM settings_db.settings WHERE key=? AND clientid=0"); settings_client=Server->createDBSettingsReader(db, "settings", "SELECT value FROM settings_db.settings WHERE key=? AND clientid="+nconvert(clientid)); delete server_settings; server_settings=new ServerSettings(db, clientid); std::wstring backupfolder=server_settings->getSettings()->backupfolder; if(!os_create_dir(os_file_prefix()+backupfolder+os_file_sep()+clientname) && !os_directory_exists(os_file_prefix()+backupfolder+os_file_sep()+clientname) ) { Server->Log(L"Could not create or read directory for client \""+clientname+L"\"", LL_ERROR); pipe->Write("ok"); delete server_settings; delete this; return; } prepareSQL(); updateLastseen(); if(!updateCapabilities()) { Server->Log(L"Could not get client capabilities", LL_ERROR); pipe->Write("ok"); delete server_settings; delete this; return; } status.client=clientname; status.clientid=clientid; ServerStatus::setServerStatus(status); BackupServerHash *bsh=new BackupServerHash(hashpipe, exitpipe, clientid ); BackupServerPrepareHash *bsh_prepare=new BackupServerPrepareHash(hashpipe_prepare, exitpipe_prepare, hashpipe, exitpipe, clientid); Server->getThreadPool()->execute(bsh); Server->getThreadPool()->execute(bsh_prepare); ServerChannelThread channel_thread(this, clientid); THREADPOOL_TICKET channel_thread_id=Server->getThreadPool()->execute(&channel_thread); sendSettings(); ServerLogger::Log(clientid, "Getting client settings...", LL_DEBUG); if(server_settings->getSettings()->allow_overwrite && !getClientSettings()) { ServerLogger::Log(clientid, "Getting client settings failed. Retrying...", LL_INFO); Server->wait(200000); if(!getClientSettings()) { ServerLogger::Log(clientid, "Getting client settings failed -1", LL_ERROR); } } ServerLogger::Log(clientid, "Sending backup incr intervall...", LL_DEBUG); sendClientBackupIncrIntervall(); if(server_settings->getSettings()->autoupdate_clients) { checkClientVersion(); } sendClientLogdata(); bool skip_checking=false; if( server_settings->getSettings()->startup_backup_delay>0 ) { pipe->isReadable(server_settings->getSettings()->startup_backup_delay*1000); skip_checking=true; } bool do_exit_now=false; bool tried_backup=false; bool file_backup_err=false; while(true) { if(!skip_checking) { if(do_update_settings) { ServerLogger::Log(clientid, "Getting client settings...", LL_DEBUG); do_update_settings=false; if(server_settings->getSettings()->allow_overwrite && !getClientSettings()) { ServerLogger::Log(clientid, "Getting client settings failed -2", LL_ERROR); } } tried_backup=false; unsigned int ttime=Server->getTimeMS(); status.starttime=ttime; has_error=false; bool hbu=false; bool r_success=false; bool r_image=false; r_incremental=false; pingthread=NULL; pingthread_ticket=ILLEGAL_THREADPOOL_TICKET; status.pcdone=0; status.hashqueuesize=0; status.prepare_hashqueuesize=0; ServerStatus::setServerStatus(status); if(do_incr_image_now) { if(!can_backup_images) Server->Log("Cannot do image backup because can_backup_images=false", LL_DEBUG); if(server_settings->getSettings()->no_images) Server->Log("Cannot do image backup because no_images=true", LL_DEBUG); if(!isBackupsRunningOkay()) Server->Log("Cannot do image backup because isBackupsRunningOkay()=false", LL_DEBUG); } if( !file_backup_err && isBackupsRunningOkay() && ( (isUpdateFull() && isInBackupWindow(server_settings->getBackupWindow())) || do_full_backup_now ) ) { ScopedActiveThread sat; status.statusaction=sa_full_file; ServerStatus::setServerStatus(status, true); ServerLogger::Log(clientid, "Doing full file backup...", LL_DEBUG); do_full_backup_now=false; hbu=true; startBackupRunning(true); if(!constructBackupPath()) { ServerLogger::Log(clientid, "Cannot create Directory for backup (Server error)", LL_ERROR); r_success=false; } else { pingthread=new ServerPingThread(this); pingthread_ticket=Server->getThreadPool()->execute(pingthread); r_success=doFullBackup(); } } else if( !file_backup_err && isBackupsRunningOkay() && ( (isUpdateIncr() && isInBackupWindow(server_settings->getBackupWindow())) || do_incr_backup_now ) ) { ScopedActiveThread sat; status.statusaction=sa_incr_file; ServerStatus::setServerStatus(status, true); ServerLogger::Log(clientid, "Doing incremental file backup...", LL_DEBUG); do_incr_backup_now=false; hbu=true; startBackupRunning(true); r_incremental=true; if(!constructBackupPath()) { ServerLogger::Log(clientid, "Cannot create Directory for backup (Server error)", LL_ERROR); r_success=false; } else { pingthread=new ServerPingThread(this); pingthread_ticket=Server->getThreadPool()->execute(pingthread); r_success=doIncrBackup(); } } else if(can_backup_images && !server_settings->getSettings()->no_images && isBackupsRunningOkay() && ( (isUpdateFullImage() && isInBackupWindow(server_settings->getBackupWindow())) || do_full_image_now) ) { ScopedActiveThread sat; status.statusaction=sa_full_image; ServerStatus::setServerStatus(status, true); ServerLogger::Log(clientid, "Doing full image backup...", LL_DEBUG); r_image=true; pingthread=new ServerPingThread(this); pingthread_ticket=Server->getThreadPool()->execute(pingthread); startBackupRunning(true); r_success=true; std::vector<std::string> vols=server_settings->getBackupVolumes(); for(size_t i=0;i<vols.size();++i) { if(isUpdateFullImage(vols[i]+":") || do_full_image_now) { int sysvol_id=-1; if(strlower(vols[i])=="c") { ServerLogger::Log(clientid, "Backing up SYSVOL...", LL_DEBUG); if(doImage("SYSVOL", L"", 0, 0)) { sysvol_id=backupid; } ServerLogger::Log(clientid, "Backing up SYSVOL done.", LL_DEBUG); } bool b=doImage(vols[i]+":", L"", 0, 0); if(!b) { r_success=false; break; } else if(sysvol_id!=-1) { saveImageAssociation(backupid, sysvol_id); } } } do_full_image_now=false; } else if(can_backup_images && !server_settings->getSettings()->no_images && isBackupsRunningOkay() && ( (isUpdateIncrImage() && isInBackupWindow(server_settings->getBackupWindow())) || do_incr_image_now) ) { ScopedActiveThread sat; status.statusaction=sa_incr_image; ServerStatus::setServerStatus(status, true); ServerLogger::Log(clientid, "Doing incremental image backup...", LL_DEBUG); r_image=true; r_incremental=true; startBackupRunning(true); pingthread=new ServerPingThread(this); pingthread_ticket=Server->getThreadPool()->execute(pingthread); std::vector<std::string> vols=server_settings->getBackupVolumes(); for(size_t i=0;i<vols.size();++i) { std::string letter=vols[i]+":"; if(isUpdateIncrImage(letter) || do_incr_image_now) { int sysvol_id=-1; if(strlower(letter)=="c:") { ServerLogger::Log(clientid, "Backing up SYSVOL...", LL_DEBUG); if(doImage("SYSVOL", L"", 0, 0)) { sysvol_id=backupid; } ServerLogger::Log(clientid, "Backing up SYSVOL done.", LL_DEBUG); } SBackup last=getLastIncrementalImage(letter); if(last.incremental==-2) { ServerLogger::Log(clientid, "Error retrieving last backup.", LL_ERROR); r_success=false; break; } else { r_success=doImage(letter, last.path, last.incremental+1, last.incremental_ref); } if(r_success && sysvol_id!=-1) { saveImageAssociation(backupid, sysvol_id); } if(!r_success) break; } } do_incr_image_now=false; } file_backup_err=false; if(hbu && !has_error) { if(r_success) { notifyClientBackupSuccessfull(); } else { if(pingthread!=NULL) { pingthread->setStop(true); Server->getThreadPool()->waitFor(pingthread_ticket); } pingthread=NULL; } } else if(hbu && has_error) { file_backup_err=true; os_remove_nonempty_dir(backuppath); tried_backup=true; } status.action_done=false; status.statusaction=sa_none; status.pcdone=100; //Flush buffer before continuing... status.hashqueuesize=(_u32)hashpipe->getNumElements()+(bsh->isWorking()?1:0); status.prepare_hashqueuesize=(_u32)hashpipe_prepare->getNumElements()+(bsh_prepare->isWorking()?1:0); hashpipe->Write("flush"); while(status.hashqueuesize>0 || status.prepare_hashqueuesize>0) { ServerStatus::setServerStatus(status, true); Server->wait(1000); status.hashqueuesize=(_u32)hashpipe->getNumElements()+(bsh->isWorking()?1:0); status.prepare_hashqueuesize=(_u32)hashpipe_prepare->getNumElements()+(bsh_prepare->isWorking()?1:0); } ServerStatus::setServerStatus(status); unsigned int ptime=Server->getTimeMS()-ttime; if(hbu && !has_error) { ServerLogger::Log(clientid, L"Time taken for backing up client "+clientname+L": "+convert(ptime), LL_INFO); if(!r_success) { ServerLogger::Log(clientid, "Backup not complete because of connection problems", LL_ERROR); } else if( bsh->hasError() ) { ServerLogger::Log(clientid, "Backup not complete because of disk problems", LL_ERROR); } else { updateLastBackup(); setBackupComplete(); } status.pcdone=100; ServerStatus::setServerStatus(status, true); } if( r_image ) { ServerLogger::Log(clientid, L"Time taken for creating image of client "+clientname+L": "+convert(ptime), LL_INFO); if(!r_success) { ServerLogger::Log(clientid, "Backup not complete because of connection problems", LL_ERROR); } else { updateLastImageBackup(); } status.pcdone=100; ServerStatus::setServerStatus(status, true); } if(hbu || r_image) { stopBackupRunning(!r_image); saveClientLogdata(r_image?1:0, r_incremental?1:0, r_success && !has_error); sendClientLogdata(); } if(hbu) { ServerCleanupThread::updateStats(true); } if(pingthread!=NULL) { pingthread->setStop(true); Server->getThreadPool()->waitFor(pingthread_ticket); pingthread=NULL; } /* Predict sleep time -- unsigned int wtime; if((unsigned int)update_freq_incr*1000>ptime) { wtime=update_freq_incr*1000-ptime; } else { wtime=0; } wtime+=60000;*/ } std::string msg; if(file_backup_err) pipe->Read(&msg, 0); else if(tried_backup) pipe->Read(&msg, skip_checking?0:check_time_intervall_tried_backup); else pipe->Read(&msg, skip_checking?0:check_time_intervall); skip_checking=false; if(msg=="exit") break; else if(msg=="exitnow") { do_exit_now=true; break; } else if(msg=="START BACKUP INCR") do_incr_backup_now=true; else if(msg=="START BACKUP FULL") do_full_backup_now=true; else if(msg=="UPDATE SETTINGS") do_update_settings=true; else if(msg=="START IMAGE INCR") do_incr_image_now=true; else if(msg=="START IMAGE FULL") do_full_image_now=true; else if(msg.find("address")==0) { IScopedLock lock(clientaddr_mutex); memcpy(&clientaddr, &msg[7], sizeof(sockaddr_in) ); } Server->Log("msg="+msg, LL_DEBUG); } //destroy channel { Server->Log("Stopping channel...", LL_DEBUG); channel_thread.doExit(); Server->getThreadPool()->waitFor(channel_thread_id); } if(do_exit_now) { hashpipe_prepare->Write("exitnow"); std::string msg; exitpipe_prepare->Read(&msg); Server->destroy(exitpipe_prepare); } else { hashpipe_prepare->Write("exit"); } Server->destroy(settings); Server->destroy(settings_client); delete server_settings; pipe->Write("ok"); Server->Log(L"server_get Thread for client "+clientname+L" finished"); delete this; } void BackupServerGet::prepareSQL(void) { SSettings *s=server_settings->getSettings(); q_update_lastseen=db->Prepare("UPDATE clients SET lastseen=CURRENT_TIMESTAMP WHERE id=?", false); q_update_full=db->Prepare("SELECT id FROM backups WHERE datetime('now','-"+nconvert(s->update_freq_full)+" seconds')<backuptime AND clientid=? AND incremental=0 AND done=1", false); q_update_incr=db->Prepare("SELECT id FROM backups WHERE datetime('now','-"+nconvert(s->update_freq_incr)+" seconds')<backuptime AND clientid=? AND complete=1 AND done=1", false); q_create_backup=db->Prepare("INSERT INTO backups (incremental, clientid, path, complete, running, size_bytes, done) VALUES (?, ?, ?, 0, CURRENT_TIMESTAMP, -1, 0)", false); q_get_last_incremental=db->Prepare("SELECT incremental,path FROM backups WHERE clientid=? AND done=1 ORDER BY backuptime DESC LIMIT 1", false); q_set_last_backup=db->Prepare("UPDATE clients SET lastbackup=CURRENT_TIMESTAMP WHERE id=?", false); q_update_setting=db->Prepare("UPDATE settings_db.settings SET value=? WHERE key=? AND clientid=?", false); q_insert_setting=db->Prepare("INSERT INTO settings_db.settings (key, value, clientid) VALUES (?,?,?)", false); q_set_complete=db->Prepare("UPDATE backups SET complete=1 WHERE id=?", false); q_update_image_full=db->Prepare("SELECT id FROM backup_images WHERE datetime('now','-"+nconvert(s->update_freq_image_full)+" seconds')<backuptime AND clientid=? AND incremental=0 AND complete=1 AND version="+nconvert(curr_image_version)+" AND letter=?", false); q_update_image_incr=db->Prepare("SELECT id FROM backup_images WHERE datetime('now','-"+nconvert(s->update_freq_image_incr)+" seconds')<backuptime AND clientid=? AND complete=1 AND version="+nconvert(curr_image_version)+" AND letter=?", false); q_create_backup_image=db->Prepare("INSERT INTO backup_images (clientid, path, incremental, incremental_ref, complete, running, size_bytes, version, letter) VALUES (?, ?, ?, ?, 0, CURRENT_TIMESTAMP, 0, "+nconvert(curr_image_version)+",?)", false); q_set_image_size=db->Prepare("UPDATE backup_images SET size_bytes=? WHERE id=?", false); q_set_image_complete=db->Prepare("UPDATE backup_images SET complete=1 WHERE id=?", false); q_set_last_image_backup=db->Prepare("UPDATE clients SET lastbackup_image=CURRENT_TIMESTAMP WHERE id=?", false); q_get_last_incremental_image=db->Prepare("SELECT id,incremental,path FROM backup_images WHERE clientid=? AND incremental=0 AND complete=1 AND version="+nconvert(curr_image_version)+" AND letter=? ORDER BY backuptime DESC LIMIT 1", false); q_update_running_file=db->Prepare("UPDATE backups SET running=CURRENT_TIMESTAMP WHERE id=?", false); q_update_running_image=db->Prepare("UPDATE backup_images SET running=CURRENT_TIMESTAMP WHERE id=?", false); q_update_images_size=db->Prepare("UPDATE clients SET bytes_used_images=(SELECT bytes_used_images FROM clients WHERE id=?)+? WHERE id=?", false); q_set_done=db->Prepare("UPDATE backups SET done=1 WHERE id=?", false); q_save_logdata=db->Prepare("INSERT INTO logs (clientid, logdata, errors, warnings, infos, image, incremental) VALUES (?,?,?,?,?,?,?)", false); q_get_unsent_logdata=db->Prepare("SELECT id, strftime('%s', created) AS created, logdata FROM logs WHERE sent=0 AND clientid=?", false); q_set_logdata_sent=db->Prepare("UPDATE logs SET sent=1 WHERE id=?", false); q_save_image_assoc=db->Prepare("INSERT INTO assoc_images (img_id, assoc_id) VALUES (?,?)", false); q_get_users=db->Prepare("SELECT id FROM settings_db.si_users WHERE report_mail IS NOT NULL AND report_mail<>''", false); q_get_rights=db->Prepare("SELECT t_right FROM settings_db.si_permissions WHERE clientid=? AND t_domain=?", false); q_get_report_settings=db->Prepare("SELECT report_mail, report_loglevel, report_sendonly FROM settings_db.si_users WHERE id=?", false); q_format_unixtime=db->Prepare("SELECT datetime(?, 'unixepoch', 'localtime') AS time", false); } int BackupServerGet::getClientID(void) { IQuery *q=db->Prepare("SELECT id FROM clients WHERE name=?",false); q->Bind(clientname); db_results res=q->Read(); db->destroyQuery(q); if(res.size()>0) return watoi(res[0][L"id"]); else { IQuery *q_get_num_clients=db->Prepare("SELECT count(*) AS c FROM clients WHERE lastseen > date('now', '-2 month')", false); db_results res_r=q_get_num_clients->Read(); q_get_num_clients->Reset(); int c_clients=-1; if(!res_r.empty()) c_clients=watoi(res_r[0][L"c"]); db->destroyQuery(q_get_num_clients); if(c_clients<server_settings->getSettings()->max_active_clients) { IQuery *q_insert_newclient=db->Prepare("INSERT INTO clients (name, lastseen,bytes_used_files,bytes_used_images) VALUES (?, CURRENT_TIMESTAMP, 0, 0)", false); q_insert_newclient->Bind(clientname); q_insert_newclient->Write(); int rid=(int)db->getLastInsertID(); q_insert_newclient->Reset(); db->destroyQuery(q_insert_newclient); return rid; } else { Server->Log(L"Too many clients. Didn't accept client '"+clientname+L"'", LL_INFO); return -1; } } } SBackup BackupServerGet::getLastIncremental(void) { q_get_last_incremental->Bind(clientid); db_results res=q_get_last_incremental->Read(); q_get_last_incremental->Reset(); if(res.size()>0) { SBackup b; b.incremental=watoi(res[0][L"incremental"]); b.path=res[0][L"path"]; return b; } else { SBackup b; b.incremental=-2; return b; } } SBackup BackupServerGet::getLastIncrementalImage(const std::string &letter) { q_get_last_incremental_image->Bind(clientid); q_get_last_incremental_image->Bind(letter); db_results res=q_get_last_incremental_image->Read(); q_get_last_incremental_image->Reset(); if(res.size()>0) { SBackup b; b.incremental=watoi(res[0][L"incremental"]); b.path=res[0][L"path"]; b.incremental_ref=watoi(res[0][L"id"]); return b; } else { SBackup b; b.incremental=-2; return b; } } int BackupServerGet::createBackupSQL(int incremental, int clientid, std::wstring path) { q_create_backup->Bind(incremental); q_create_backup->Bind(clientid); q_create_backup->Bind(path); q_create_backup->Write(); q_create_backup->Reset(); return (int)db->getLastInsertID(); } int BackupServerGet::createBackupImageSQL(int incremental, int incremental_ref, int clientid, std::wstring path, std::string letter) { q_create_backup_image->Bind(clientid); q_create_backup_image->Bind(path); q_create_backup_image->Bind(incremental); q_create_backup_image->Bind(incremental_ref); q_create_backup_image->Bind(letter); q_create_backup_image->Write(); q_create_backup_image->Reset(); return (int)db->getLastInsertID(); } void BackupServerGet::updateLastseen(void) { q_update_lastseen->Bind(clientid); q_update_lastseen->Write(); q_update_lastseen->Reset(); } bool BackupServerGet::isUpdateFull(void) { q_update_full->Bind(clientid); db_results res=q_update_full->Read(); q_update_full->Reset(); return res.empty(); } bool BackupServerGet::isUpdateIncr(void) { q_update_incr->Bind(clientid); db_results res=q_update_incr->Read(); q_update_incr->Reset(); return res.empty(); } bool BackupServerGet::isUpdateFullImage(const std::string &letter) { if(server_settings->getSettings()->update_freq_image_full<0) return false; q_update_image_full->Bind(clientid); q_update_image_full->Bind(letter); db_results res=q_update_image_full->Read(); q_update_image_full->Reset(); return res.empty(); } bool BackupServerGet::isUpdateFullImage(void) { std::vector<std::string> vols=server_settings->getBackupVolumes(); for(size_t i=0;i<vols.size();++i) { if( isUpdateFullImage(vols[i]+":") ) { return true; } } return false; } bool BackupServerGet::isUpdateIncrImage(void) { std::vector<std::string> vols=server_settings->getBackupVolumes(); for(size_t i=0;i<vols.size();++i) { if( isUpdateIncrImage(vols[i]+":") ) { return true; } } return false; } bool BackupServerGet::isUpdateIncrImage(const std::string &letter) { if(server_settings->getSettings()->update_freq_image_full<=0) return false; q_update_image_incr->Bind(clientid); q_update_image_incr->Bind(letter); db_results res=q_update_image_incr->Read(); q_update_image_incr->Reset(); return res.empty(); } void BackupServerGet::updateRunning(bool image) { if(image) { q_update_running_image->Bind(backupid); q_update_running_image->Write(); q_update_running_image->Reset(); } else { q_update_running_file->Bind(backupid); q_update_running_file->Write(); q_update_running_file->Reset(); } } void BackupServerGet::saveImageAssociation(int image_id, int assoc_id) { q_save_image_assoc->Bind(image_id); q_save_image_assoc->Bind(assoc_id); q_save_image_assoc->Write(); q_save_image_assoc->Reset(); } bool BackupServerGet::getNextEntry(char ch, SFile &data) { switch(state) { case 0: if(ch=='f') data.isdir=false; else if(ch=='d') data.isdir=true; else ServerLogger::Log(clientid, "Error parsing file BackupServerGet::getNextEntry - 1", LL_ERROR); state=1; break; case 1: //" state=2; break; case 3: if(ch!='"') { t_name.erase(t_name.size()-1,1); data.name=Server->ConvertToUnicode(t_name); t_name=""; if(data.isdir) { resetEntryState(); return true; } else state=4; } case 2: if(state==2 && ch=='"') state=3; else if(state==3) state=2; t_name+=ch; break; case 4: if(ch!=' ') { t_name+=ch; } else { data.size=os_atoi64(t_name); t_name=""; state=5; } break; case 5: if(ch!='\n') { t_name+=ch; } else { data.last_modified=os_atoi64(t_name); resetEntryState(); return true; } break; } return false; } void BackupServerGet::resetEntryState(void) { t_name=""; state=0; } bool BackupServerGet::request_filelist_construct(bool full, bool with_token) { CTCPStack tcpstack; Server->Log(clientname+L": Connecting for filelist...", LL_DEBUG); IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed - CONNECT error during filelist construction", LL_ERROR); return false; } if(full) tcpstack.Send(cc, server_identity+"START FULL BACKUP"+(with_token?("#token="+server_token):"")); else tcpstack.Send(cc, server_identity+"START BACKUP"+(with_token?("#token="+server_token):"")); Server->Log(clientname+L": Waiting for filelist", LL_DEBUG); std::string ret; unsigned int starttime=Server->getTimeMS(); while(Server->getTimeMS()-starttime<=full_backup_construct_timeout) { size_t rc=cc->Read(&ret, full_backup_construct_timeout); if(rc==0) { if(Server->getTimeMS()-starttime<=20000 && with_token==true) //Compatibility with older clients { Server->destroy(cc); Server->Log(clientname+L": Trying old filelist request", LL_WARNING); return request_filelist_construct(full, false); } else { ServerLogger::Log(clientid, L"Constructing of filelist of \""+clientname+L"\" failed - TIMEOUT(1)", LL_ERROR); } break; } tcpstack.AddData((char*)ret.c_str(), ret.size()); size_t packetsize; char *pck=tcpstack.getPacket(&packetsize); if(pck!=NULL && packetsize>0) { ret=pck; delete [] pck; if(ret!="DONE") { ServerLogger::Log(clientid, L"Constructing of filelist of \""+clientname+L"\" failed: "+widen(ret), LL_ERROR); break; } else { Server->destroy(cc); return true; } } } Server->destroy(cc); return false; } bool BackupServerGet::doFullBackup(void) { int64 free_space=os_free_space(os_file_prefix()+server_settings->getSettings()->backupfolder); if(free_space!=-1 && free_space<minfreespace_min) { Server->Log("No space for directory entries. Freeing space", LL_WARNING); ServerCleanupThread cleanup; if(!cleanup.do_cleanup(minfreespace_min) ) { ServerLogger::Log(clientid, "Could not free space for directory entries. NOT ENOUGH FREE SPACE.", LL_ERROR); return false; } } bool b=request_filelist_construct(true); if(!b) { has_error=true; return false; } FileClient fc(filesrv_protocol_version); sockaddr_in addr=getClientaddr(); _u32 rc=fc.Connect(&addr); if(rc!=ERR_CONNECTED) { ServerLogger::Log(clientid, L"Full Backup of "+clientname+L" failed - CONNECT error", LL_ERROR); has_error=true; return false; } IFile *tmp=Server->openTemporaryFile(); if(tmp==NULL) return false; rc=fc.GetFile("urbackup/filelist.ub", tmp); if(rc!=ERR_SUCCESS) { ServerLogger::Log(clientid, L"Error getting filelist of "+clientname+L". Errorcode: "+convert(rc), LL_ERROR); has_error=true; return false; } backupid=createBackupSQL(0, clientid, backuppath_single); tmp->Seek(0); resetEntryState(); IFile *clientlist=Server->openFile("urbackup/clientlist_"+nconvert(clientid)+".ub", MODE_WRITE); if(clientlist==NULL ) { ServerLogger::Log(clientid, L"Error creating clientlist for client "+clientname, LL_ERROR); has_error=true; return false; } _i64 filelist_size=tmp->Size(); char buffer[4096]; _u32 read; _i64 filelist_currpos=0; std::wstring curr_path; SFile cf; int depth=0; bool r_done=false; unsigned int laststatsupdate=0; ServerStatus::setServerStatus(status, true); ServerRunningUpdater *running_updater=new ServerRunningUpdater(backupid, false); Server->getThreadPool()->execute(running_updater); std::vector<size_t> diffs; _i64 files_size=getIncrementalSize(tmp, diffs, true); _i64 transferred=0; tmp->Seek(0); bool c_has_error=false; while( (read=tmp->Read(buffer, 4096))>0 && r_done==false && c_has_error==false) { filelist_currpos+=read; for(size_t i=0;i<read;++i) { unsigned int ctime=Server->getTimeMS(); if(ctime-laststatsupdate>status_update_intervall) { laststatsupdate=ctime; if(files_size==0) { status.pcdone=100; } else { status.pcdone=(std::min)(100,(int)(((float)transferred)/((float)files_size/100.f)+0.5f)); } status.hashqueuesize=(_u32)hashpipe->getNumElements(); status.prepare_hashqueuesize=(_u32)hashpipe_prepare->getNumElements(); ServerStatus::setServerStatus(status, true); } bool b=getNextEntry(buffer[i], cf); if(b) { if(cf.isdir==true) { if(cf.name!=L"..") { curr_path+=L"/"+cf.name; std::wstring os_curr_path=curr_path; if(os_file_sep()!=L"/") { for(size_t i=0;i<os_curr_path.size();++i) if(os_curr_path[i]=='/') os_curr_path[i]=os_file_sep()[0]; } if(!os_create_dir(os_file_prefix()+backuppath+os_curr_path)) { ServerLogger::Log(clientid, L"Creating directory \""+backuppath+os_curr_path+L"\" failed.", LL_ERROR); c_has_error=true; break; } ++depth; if(depth==1) { std::wstring t=curr_path; t.erase(0,1); ServerLogger::Log(clientid, L"Starting shadowcopy \""+t+L"\".", LL_INFO); start_shadowcopy(Server->ConvertToUTF8(t)); Server->wait(10000); } } else { --depth; if(depth==0) { std::wstring t=curr_path; t.erase(0,1); ServerLogger::Log(clientid, L"Stoping shadowcopy \""+t+L"\".", LL_INFO); stop_shadowcopy(Server->ConvertToUTF8(t)); } curr_path=ExtractFilePath(curr_path); } } else { bool b=load_file(cf.name, curr_path, fc); if(!b) { ServerLogger::Log(clientid, L"Client "+clientname+L" went offline.", LL_ERROR); r_done=true; break; } transferred+=cf.size; } } } writeFileRepeat(clientlist, buffer, read); if(read<4096) break; } if(r_done==false && c_has_error==false) { std::wstring backupfolder=server_settings->getSettings()->backupfolder; std::wstring currdir=backupfolder+os_file_sep()+clientname+os_file_sep()+L"current"; Server->deleteFile(os_file_prefix()+currdir); os_link_symbolic(os_file_prefix()+backuppath, os_file_prefix()+currdir); currdir=backupfolder+os_file_sep()+L"clients"; if(!os_create_dir(os_file_prefix()+currdir) && !os_directory_exists(os_file_prefix()+currdir)) { Server->Log("Error creating \"clients\" dir for symbolic links", LL_ERROR); } currdir+=os_file_sep()+clientname; Server->deleteFile(os_file_prefix()+currdir); os_link_symbolic(os_file_prefix()+backuppath, os_file_prefix()+currdir); } running_updater->stop(); updateRunning(false); Server->destroy(clientlist); Server->destroy(tmp); setBackupDone(); if(c_has_error) return false; return !r_done; } bool BackupServerGet::load_file(const std::wstring &fn, const std::wstring &curr_path, FileClient &fc) { ServerLogger::Log(clientid, L"Loading file \""+fn+L"\"", LL_DEBUG); IFile *fd=NULL; while(fd==NULL) { fd=Server->openTemporaryFile(); if(fd==NULL) { ServerLogger::Log(clientid, "Error opening temporary file. Retrying...", LL_WARNING); Server->wait(500); } } std::wstring cfn=curr_path+L"/"+fn; if(cfn[0]=='/') cfn.erase(0,1); if(!server_token.empty()) { cfn=widen(server_token)+L"|"+cfn; } _u32 rc=fc.GetFile(Server->ConvertToUTF8(cfn), fd); if(rc!=ERR_SUCCESS) { ServerLogger::Log(clientid, L"Error getting file \""+cfn+L"\" from "+clientname+L". Errorcode: "+convert(rc), LL_ERROR); std::wstring temp_fn=fd->getFilenameW(); Server->destroy(fd); Server->deleteFile(temp_fn); if(rc==ERR_TIMEOUT || rc==ERR_ERROR || rc==ERR_BASE_DIR_LOST) return false; } else { std::wstring os_curr_path=curr_path+L"/"+fn; if(os_file_sep()!=L"/") { for(size_t i=0;i<os_curr_path.size();++i) if(os_curr_path[i]=='/') os_curr_path[i]=os_file_sep()[0]; } std::wstring dstpath=backuppath+os_curr_path; hashFile(dstpath, fd); } return true; } _i64 BackupServerGet::getIncrementalSize(IFile *f, const std::vector<size_t> &diffs, bool all) { f->Seek(0); _i64 rsize=0; resetEntryState(); SFile cf; bool indirchange=false; size_t read; size_t line=0; char buffer[4096]; int indir_currdepth=0; int depth=0; int indir_curr_depth=0; int changelevel=0; if(all) { indirchange=true; } while( (read=f->Read(buffer, 4096))>0 ) { for(size_t i=0;i<read;++i) { bool b=getNextEntry(buffer[i], cf); if(b) { if(cf.isdir==true) { if(indirchange==false && hasChange(line, diffs) ) { indirchange=true; changelevel=depth; indir_currdepth=0; } else if(indirchange==true) { if(cf.name!=L"..") ++indir_currdepth; else --indir_currdepth; } if(cf.name==L".." && indir_currdepth>0) { --indir_currdepth; } if(cf.name!=L"..") { ++depth; } else { --depth; if(indirchange==true && depth==changelevel) { if(!all) { indirchange=false; } } } } else { if(indirchange==true || hasChange(line, diffs)) { rsize+=cf.size; } } ++line; } } if(read<4096) break; } return rsize; } bool BackupServerGet::doIncrBackup(void) { int64 free_space=os_free_space(os_file_prefix()+server_settings->getSettings()->backupfolder); if(free_space!=-1 && free_space<minfreespace_min) { Server->Log("No space for directory entries. Freeing space", LL_WARNING); ServerCleanupThread cleanup; if(!cleanup.do_cleanup(minfreespace_min) ) { ServerLogger::Log(clientid, "Could not free space for directory entries. NOT ENOUGH FREE SPACE.", LL_ERROR); return false; } } bool b=request_filelist_construct(false); if(!b) { has_error=true; return false; } Server->Log(clientname+L": Connecting to client...", LL_DEBUG); FileClient fc(filesrv_protocol_version); sockaddr_in addr=getClientaddr(); _u32 rc=fc.Connect(&addr); if(rc!=ERR_CONNECTED) { ServerLogger::Log(clientid, L"Incremental Backup of "+clientname+L" failed - CONNECT error", LL_ERROR); has_error=true; return false; } Server->Log(clientname+L": Loading filelist...", LL_DEBUG); IFile *tmp=Server->openTemporaryFile(); if(tmp==NULL) return false; rc=fc.GetFile("urbackup/filelist.ub", tmp); if(rc!=ERR_SUCCESS) { ServerLogger::Log(clientid, L"Error getting filelist of "+clientname+L". Errorcode: "+convert(rc), LL_ERROR); has_error=true; return false; } Server->Log(clientname+L" Starting incremental backup...", LL_DEBUG); SBackup last=getLastIncremental(); if(last.incremental==-2) { ServerLogger::Log(clientid, "Error retrieving last backup.", LL_ERROR); has_error=true; return false; } backupid=createBackupSQL(last.incremental+1, clientid, backuppath_single); std::wstring backupfolder=server_settings->getSettings()->backupfolder; std::wstring last_backuppath=backupfolder+os_file_sep()+clientname+os_file_sep()+last.path; std::wstring tmpfilename=tmp->getFilenameW(); Server->destroy(tmp); Server->Log(clientname+L": Calculating file tree differences...", LL_DEBUG); bool error=false; std::vector<size_t> diffs=TreeDiff::diffTrees("urbackup/clientlist_"+nconvert(clientid)+".ub", wnarrow(tmpfilename), error); if(error) { ServerLogger::Log(clientid, "Error while calculating tree diff. Doing full backup.", LL_ERROR); return doFullBackup(); } IFile *clientlist=Server->openFile("urbackup/clientlist_"+nconvert(clientid)+"_new.ub", MODE_WRITE); tmp=Server->openFile(tmpfilename, MODE_READ); ServerRunningUpdater *running_updater=new ServerRunningUpdater(backupid, false); Server->getThreadPool()->execute(running_updater); resetEntryState(); char buffer[4096]; _u32 read; std::wstring curr_path; SFile cf; int depth=0; int line=0; link_logcnt=0; bool indirchange=false; int changelevel; bool r_offline=false; _i64 filelist_size=tmp->Size(); _i64 filelist_currpos=0; int indir_currdepth=0; Server->Log(clientname+L": Calculating tree difference size...", LL_DEBUG); _i64 files_size=getIncrementalSize(tmp, diffs); tmp->Seek(0); _i64 transferred=0; unsigned int laststatsupdate=0; ServerStatus::setServerStatus(status, true); Server->Log(clientname+L": Linking unchanged and loading new files...", LL_DEBUG); bool c_has_error=false; while( (read=tmp->Read(buffer, 4096))>0 ) { filelist_currpos+=read; for(size_t i=0;i<read;++i) { bool b=getNextEntry(buffer[i], cf); if(b) { unsigned int ctime=Server->getTimeMS(); if(ctime-laststatsupdate>status_update_intervall) { laststatsupdate=ctime; if(files_size==0) { status.pcdone=100; } else { status.pcdone=(std::min)(100,(int)(((float)transferred)/((float)files_size/100.f)+0.5f)); } status.hashqueuesize=(_u32)hashpipe->getNumElements(); status.prepare_hashqueuesize=(_u32)hashpipe_prepare->getNumElements(); ServerStatus::setServerStatus(status, true); } if(cf.isdir==true) { if(indirchange==false && hasChange(line, diffs) ) { indirchange=true; changelevel=depth; indir_currdepth=0; if(cf.name!=L"..") { if(r_offline==false ) indir_currdepth=1; } else { --changelevel; } } else if(indirchange==true && r_offline==false) { if(cf.name!=L"..") ++indir_currdepth; else --indir_currdepth; } if(indirchange==false || r_offline==false ) { writeFileRepeat(clientlist, "d\""+Server->ConvertToUTF8(cf.name)+"\"\n"); } else if(cf.name==L".." && indir_currdepth>0) { --indir_currdepth; writeFileRepeat(clientlist, "d\"..\"\n"); } if(cf.name!=L"..") { curr_path+=L"/"+cf.name; std::wstring os_curr_path=curr_path; if(os_file_sep()!=L"/") { for(size_t i=0;i<os_curr_path.size();++i) if(os_curr_path[i]=='/') os_curr_path[i]=os_file_sep()[0]; } if(!os_create_dir(os_file_prefix()+backuppath+os_curr_path)) { ServerLogger::Log(clientid, L"Creating directory \""+backuppath+os_curr_path+L"\" failed.", LL_ERROR); c_has_error=true; break; } ++depth; if(depth==1) { std::wstring t=curr_path; t.erase(0,1); if(r_offline==false) { start_shadowcopy(Server->ConvertToUTF8(t)); } } } else { --depth; if(indirchange==true && depth==changelevel) { indirchange=false; } if(depth==0) { std::wstring t=curr_path; t.erase(0,1); if(r_offline==false) { stop_shadowcopy(Server->ConvertToUTF8(t)); } } curr_path=ExtractFilePath(curr_path); } } else { if(indirchange==true || hasChange(line, diffs)) { if(r_offline==false) { bool b=load_file(cf.name, curr_path, fc); if(!b) { ServerLogger::Log(clientid, L"Client "+clientname+L" went offline.", LL_ERROR); r_offline=true; } else { transferred+=cf.size; writeFileRepeat(clientlist, "f\""+Server->ConvertToUTF8(cf.name)+"\" "+nconvert(cf.size)+" "+nconvert(cf.last_modified)+"\n"); } } } else { std::wstring os_curr_path=curr_path+L"/"+cf.name; if(os_file_sep()!=L"/") { for(size_t i=0;i<os_curr_path.size();++i) if(os_curr_path[i]=='/') os_curr_path[i]=os_file_sep()[0]; } std::wstring srcpath=last_backuppath+os_curr_path; bool f_ok=true; bool b=os_create_hardlink(os_file_prefix()+backuppath+os_curr_path, os_file_prefix()+srcpath); if(!b) { if(link_logcnt<5) { ServerLogger::Log(clientid, L"Creating hardlink from \""+srcpath+L"\" to \""+backuppath+os_curr_path+L"\" failed. Loading file...", LL_WARNING); } else if(link_logcnt==5) { ServerLogger::Log(clientid, L"More warnings of kind: Creating hardlink from \""+srcpath+L"\" to \""+backuppath+os_curr_path+L"\" failed. Loading file... Skipping.", LL_WARNING); } else { Server->Log(L"Creating hardlink from \""+srcpath+L"\" to \""+backuppath+os_curr_path+L"\" failed. Loading file...", LL_WARNING); } ++link_logcnt; if(r_offline==false) { bool b2=load_file(cf.name, curr_path, fc); if(!b2) { ServerLogger::Log(clientid, L"Client "+clientname+L" went offline.", LL_ERROR); r_offline=true; f_ok=false; } } else { f_ok=false; } } if(f_ok) { writeFileRepeat(clientlist, "f\""+Server->ConvertToUTF8(cf.name)+"\" "+nconvert(cf.size)+" "+nconvert(cf.last_modified)+"\n"); } } } ++line; } } if(c_has_error) break; if(read<4096) break; } status.pcdone=100; ServerStatus::setServerStatus(status, true); Server->destroy(clientlist); if(r_offline==false && c_has_error==false) { Server->Log("Client ok. Copying full file...", LL_DEBUG); IFile *clientlist=Server->openFile("urbackup/clientlist_"+nconvert(clientid)+".ub", MODE_WRITE); bool clientlist_copy_err=false; if(clientlist!=NULL) { tmp->Seek(0); _u32 r=0; char buf[4096]; do { r=tmp->Read(buf, 4096); if(r>0) { _u32 written=0; _u32 rc; int tries=50; do { rc=clientlist->Write(buf+written, r-written); written+=rc; if(rc==0) { Server->Log("Failed to write to file... waiting...", LL_WARNING); Server->wait(10000); --tries; } } while(written<r && (rc>0 || tries>0) ); if(rc==0) { ServerLogger::Log(clientid, "Fatal error copying clientlist. Write error.", LL_ERROR); clientlist_copy_err=true; break; } } } while(r>0); Server->Log("Copying done.", LL_DEBUG); Server->Log("Creating symbolic links. -1", LL_DEBUG); std::wstring backupfolder=server_settings->getSettings()->backupfolder; std::wstring currdir=backupfolder+os_file_sep()+clientname+os_file_sep()+L"current"; Server->deleteFile(os_file_prefix()+currdir); os_link_symbolic(os_file_prefix()+backuppath, os_file_prefix()+currdir); Server->Log("Creating symbolic links. -2", LL_DEBUG); currdir=backupfolder+os_file_sep()+L"clients"; if(!os_create_dir(os_file_prefix()+currdir) && !os_directory_exists(os_file_prefix()+currdir)) { Server->Log("Error creating \"clients\" dir for symbolic links", LL_ERROR); } currdir+=os_file_sep()+clientname; Server->deleteFile(os_file_prefix()+currdir); os_link_symbolic(os_file_prefix()+backuppath, os_file_prefix()+currdir); Server->Log("Symbolic links created.", LL_DEBUG); Server->destroy(clientlist); } else { ServerLogger::Log(clientid, "Fatal error copying clientlist. Open error.", LL_ERROR); } if(!clientlist_copy_err) { Server->deleteFile("urbackup/clientlist_"+nconvert(clientid)+"_new.ub"); } } else if(!c_has_error) { Server->Log("Client disconnected while backing up. Copying partial file...", LL_DEBUG); Server->deleteFile("urbackup/clientlist_"+nconvert(clientid)+".ub"); moveFile(L"urbackup/clientlist_"+convert(clientid)+L"_new.ub", L"urbackup/clientlist_"+convert(clientid)+L".ub"); } else { ServerLogger::Log(clientid, "Fatal error during backup. Backup not completed", LL_ERROR); } running_updater->stop(); updateRunning(false); Server->destroy(tmp); Server->deleteFile(tmpfilename); setBackupDone(); if(c_has_error) return false; return !r_offline; } bool BackupServerGet::hasChange(size_t line, const std::vector<size_t> &diffs) { return std::binary_search(diffs.begin(), diffs.end(), line); } void BackupServerGet::hashFile(std::wstring dstpath, IFile *fd) { unsigned int l_backup_id=backupid; CWData data; data.addString(Server->ConvertToUTF8(fd->getFilenameW())); data.addUInt(l_backup_id); data.addChar(r_incremental==true?1:0); data.addString(Server->ConvertToUTF8(dstpath)); ServerLogger::Log(clientid, "GT: Loaded file \""+ExtractFileName(Server->ConvertToUTF8(dstpath))+"\"", LL_DEBUG); Server->destroy(fd); hashpipe_prepare->Write(data.getDataPtr(), data.getDataSize() ); } bool BackupServerGet::constructBackupPath(void) { time_t tt=time(NULL); #ifdef _WIN32 tm lt; tm *t=&lt; localtime_s(t, &tt); #else tm *t=localtime(&tt); #endif char buffer[500]; strftime(buffer, 500, "%y%m%d-%H%M", t); backuppath_single=widen((std::string)buffer); std::wstring backupfolder=server_settings->getSettings()->backupfolder; backuppath=backupfolder+os_file_sep()+clientname+os_file_sep()+backuppath_single; return os_create_dir(os_file_prefix()+backuppath); } std::wstring BackupServerGet::constructImagePath(const std::wstring &letter) { time_t tt=time(NULL); #ifdef _WIN32 tm lt; tm *t=&lt; localtime_s(t, &tt); #else tm *t=localtime(&tt); #endif char buffer[500]; strftime(buffer, 500, "%y%m%d-%H%M", t); std::wstring backupfolder_uncompr=server_settings->getSettings()->backupfolder_uncompr; return backupfolder_uncompr+os_file_sep()+clientname+os_file_sep()+L"Image_"+letter+L"_"+widen((std::string)buffer)+L".vhd"; } void BackupServerGet::updateLastBackup(void) { q_set_last_backup->Bind(clientid); q_set_last_backup->Write(); q_set_last_backup->Reset(); } void BackupServerGet::updateLastImageBackup(void) { q_set_last_image_backup->Bind(clientid); q_set_last_image_backup->Write(); q_set_last_image_backup->Reset(); } std::string BackupServerGet::sendClientMessage(const std::string &msg, const std::wstring &errmsg, unsigned int timeout, bool logerr) { CTCPStack tcpstack; IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { if(logerr) ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed: "+errmsg, LL_ERROR); else Server->Log(L"Connecting to ClientService of \""+clientname+L"\" failed: "+errmsg, LL_DEBUG); return ""; } tcpstack.Send(cc, server_identity+msg); std::string ret; unsigned int starttime=Server->getTimeMS(); bool ok=false; bool herr=false; while(Server->getTimeMS()-starttime<=timeout) { size_t rc=cc->Read(&ret, timeout); if(rc==0) { ServerLogger::Log(clientid, errmsg, LL_ERROR); break; } tcpstack.AddData((char*)ret.c_str(), ret.size()); size_t packetsize; char *pck=tcpstack.getPacket(&packetsize); if(pck!=NULL && packetsize>0) { ret.resize(packetsize); memcpy(&ret[0], pck, packetsize); delete [] pck; Server->destroy(cc); return ret; } } ServerLogger::Log(clientid, L"Timeout: "+errmsg, LL_ERROR); Server->destroy(cc); return ""; } bool BackupServerGet::sendClientMessage(const std::string &msg, const std::string &retok, const std::wstring &errmsg, unsigned int timeout, bool logerr) { CTCPStack tcpstack; IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { if(logerr) ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed: "+errmsg, LL_ERROR); else Server->Log(L"Connecting to ClientService of \""+clientname+L"\" failed: "+errmsg, LL_DEBUG); return false; } tcpstack.Send(cc, server_identity+msg); std::string ret; unsigned int starttime=Server->getTimeMS(); bool ok=false; bool herr=false; while(Server->getTimeMS()-starttime<=timeout) { size_t rc=cc->Read(&ret, timeout); if(rc==0) { if(logerr) ServerLogger::Log(clientid, errmsg, LL_ERROR); else Server->Log(errmsg, LL_ERROR); break; } tcpstack.AddData((char*)ret.c_str(), ret.size()); size_t packetsize; char *pck=tcpstack.getPacket(&packetsize); if(pck!=NULL && packetsize>0) { ret=pck; delete [] pck; if(ret!=retok) { herr=true; if(logerr) ServerLogger::Log(clientid, errmsg, LL_ERROR); else Server->Log(errmsg, LL_ERROR); break; } else { ok=true; break; } } } if(!ok && !herr) { if(logerr) ServerLogger::Log(clientid, L"Timeout: "+errmsg, LL_ERROR); else Server->Log(L"Timeout: "+errmsg, LL_ERROR); } Server->destroy(cc); return ok; } void BackupServerGet::start_shadowcopy(const std::string &path) { sendClientMessage("START SC \""+path+"\"#token="+server_token, "DONE", L"Activating shadow copy on \""+clientname+L"\" failed", shadow_copy_timeout); } void BackupServerGet::stop_shadowcopy(const std::string &path) { sendClientMessage("STOP SC \""+path+"\"#token="+server_token, "DONE", L"Removing shadow copy on \""+clientname+L"\" failed", shadow_copy_timeout); } void BackupServerGet::notifyClientBackupSuccessfull(void) { sendClientMessage("DID BACKUP", "OK", L"Sending status to client failed", 10000); } void BackupServerGet::sendClientBackupIncrIntervall(void) { sendClientMessage("INCRINTERVALL \""+nconvert(server_settings->getSettings()->update_freq_incr)+"\"", "OK", L"Sending incrintervall to client failed", 10000); } bool BackupServerGet::updateCapabilities(void) { std::string cap=sendClientMessage("CAPA", L"Querying capabilities failed", 10000, false); if(cap!="ERR" && !cap.empty()) { str_map params; ParseParamStr(cap, &params); if(params[L"IMAGE"]!=L"1") { Server->Log("Client doesn't have IMAGE capability", LL_DEBUG); can_backup_images=false; } str_map::iterator it=params.find(L"FILESRV"); if(it!=params.end()) { filesrv_protocol_version=watoi(it->second); } } return !cap.empty(); } void BackupServerGet::sendSettings(void) { std::string s_settings; std::vector<std::wstring> settings_names=getSettingsList(); for(size_t i=0;i<settings_names.size();++i) { std::wstring key=settings_names[i]; std::wstring value; if(!settings_client->getValue(key, &value) ) { if(!settings->getValue(key, &value) ) key=L""; else key+=L"_def"; } if(!key.empty()) { s_settings+=Server->ConvertToUTF8(key)+"="+Server->ConvertToUTF8(value)+"\n"; } } escapeClientMessage(s_settings); sendClientMessage("SETTINGS "+s_settings, "OK", L"Sending settings to client failed", 10000); } bool BackupServerGet::getClientSettings(void) { FileClient fc(filesrv_protocol_version); sockaddr_in addr=getClientaddr(); _u32 rc=fc.Connect(&addr); if(rc!=ERR_CONNECTED) { ServerLogger::Log(clientid, L"Getting Client settings of "+clientname+L" failed - CONNECT error", LL_ERROR); return false; } IFile *tmp=Server->openTemporaryFile(); if(tmp==NULL) { ServerLogger::Log(clientid, "Error creating temporary file in BackupServerGet::getClientSettings", LL_ERROR); return false; } rc=fc.GetFile("urbackup/settings.cfg", tmp); if(rc!=ERR_SUCCESS) { ServerLogger::Log(clientid, L"Error getting Client settings of "+clientname+L". Errorcode: "+convert(rc), LL_ERROR); return false; } ISettingsReader *sr=Server->createFileSettingsReader(tmp->getFilename()); std::vector<std::wstring> setting_names=getSettingsList(); bool mod=false; for(size_t i=0;i<setting_names.size();++i) { std::wstring &key=setting_names[i]; std::wstring value; if(sr->getValue(key, &value) ) { bool b=updateClientSetting(key, value); if(b) mod=true; } } Server->destroy(sr); bool b=updateClientSetting(L"client_overwrite", L"true"); if(b) mod=true; std::string tmp_fn=tmp->getFilename(); Server->destroy(tmp); Server->deleteFile(tmp_fn); if(mod) { server_settings->update(); unloadSQL(); prepareSQL(); } return true; } bool BackupServerGet::updateClientSetting(const std::wstring &key, const std::wstring &value) { std::wstring tmp; if(settings_client->getValue(key, &tmp)==false ) { q_insert_setting->Bind(key); q_insert_setting->Bind(value); q_insert_setting->Bind(clientid); q_insert_setting->Write(); q_insert_setting->Reset(); return true; } else if(tmp!=value) { q_update_setting->Bind(value); q_update_setting->Bind(key); q_update_setting->Bind(clientid); q_update_setting->Write(); q_update_setting->Reset(); return true; } return false; } void BackupServerGet::setBackupComplete(void) { q_set_complete->Bind(backupid); q_set_complete->Write(); q_set_complete->Reset(); } void BackupServerGet::setBackupDone(void) { q_set_done->Bind(backupid); q_set_done->Write(); q_set_done->Reset(); } void BackupServerGet::setBackupImageComplete(void) { q_set_image_complete->Bind(backupid); q_set_image_complete->Write(); q_set_image_complete->Reset(); } void BackupServerGet::sendToPipe(const std::string &msg) { pipe->Write(msg); } int BackupServerGet::getPCDone(void) { SStatus st=ServerStatus::getStatus(clientname); if(!st.has_status) return 0; else return st.pcdone; } void BackupServerGet::sendClientLogdata(void) { q_get_unsent_logdata->Bind(clientid); db_results res=q_get_unsent_logdata->Read(); q_get_unsent_logdata->Reset(); for(size_t i=0;i<res.size();++i) { std::string logdata=Server->ConvertToUTF8(res[i][L"logdata"]); escapeClientMessage(logdata); sendClientMessage("2LOGDATA "+wnarrow(res[i][L"created"])+" "+logdata, "OK", L"Sending logdata to client failed", 10000); q_set_logdata_sent->Bind(res[i][L"id"]); q_set_logdata_sent->Write(); q_set_logdata_sent->Reset(); } } void BackupServerGet::saveClientLogdata(int image, int incremental, bool r_success) { int errors=0; int warnings=0; int infos=0; std::wstring logdata=ServerLogger::getLogdata(clientid, errors, warnings, infos); q_save_logdata->Bind(clientid); q_save_logdata->Bind(logdata); q_save_logdata->Bind(errors); q_save_logdata->Bind(warnings); q_save_logdata->Bind(infos); q_save_logdata->Bind(image); q_save_logdata->Bind(incremental); q_save_logdata->Write(); q_save_logdata->Reset(); sendLogdataMail(r_success, image, incremental, errors, warnings, infos, logdata); ServerLogger::reset(clientid); } std::wstring BackupServerGet::getUserRights(int userid, std::string domain) { if(domain!="all") { if(getUserRights(userid, "all")==L"all") return L"all"; } q_get_rights->Bind(userid); q_get_rights->Bind(domain); db_results res=q_get_rights->Read(); q_get_rights->Reset(); if(!res.empty()) { return res[0][L"t_right"]; } else { return L"none"; } } void BackupServerGet::sendLogdataMail(bool r_success, int image, int incremental, int errors, int warnings, int infos, std::wstring &data) { MailServer mail_server=getMailServerSettings(); if(mail_server.servername.empty()) return; if(url_fak==NULL) return; db_results res_users=q_get_users->Read(); q_get_users->Reset(); for(size_t i=0;i<res_users.size();++i) { std::wstring logr=getUserRights(watoi(res_users[i][L"id"]), "logs"); bool has_r=false; if(logr!=L"all") { std::vector<std::wstring> toks; Tokenize(logr, toks, L","); for(size_t j=0;j<toks.size();++j) { if(toks[j]==res_users[i][L"id"]) { has_r=true; } } } else { has_r=true; } if(has_r) { q_get_report_settings->Bind(watoi(res_users[i][L"id"])); db_results res=q_get_report_settings->Read(); q_get_report_settings->Reset(); if(!res.empty()) { std::wstring report_mail=res[0][L"report_mail"]; int report_loglevel=watoi(res[0][L"report_loglevel"]); int report_sendonly=watoi(res[0][L"report_sendonly"]); if( ( ( report_loglevel==0 && infos>0 ) || ( report_loglevel<=1 && warnings>0 ) || ( report_loglevel<=2 && errors>0 ) ) && (report_sendonly==0 || ( report_sendonly==1 && !r_success ) || ( report_sendonly==2 && r_success)) ) { std::vector<std::string> to_addrs; Tokenize(Server->ConvertToUTF8(report_mail), to_addrs, ",;"); std::string subj="UrBackup: "; std::string msg="UrBackup just did "; if(incremental>0) { msg+="an incremental "; subj="Incremental "; } else { msg+="a full "; subj="Full "; } if(image>0) { msg+="image "; subj+="image "; } else { msg+="file "; subj+="file "; } subj+="backup of \""+Server->ConvertToUTF8(clientname)+"\"\n"; msg+="backup of \""+Server->ConvertToUTF8(clientname)+"\".\n"; msg+="\nReport:\n"; msg+="( "+nconvert(infos); if(infos!=1) msg+=" infos, "; else msg+=" info, "; msg+=nconvert(warnings); if(warnings!=1) msg+=" warnings, "; else msg+=" warning, "; msg+=nconvert(errors); if(errors!=1) msg+=" errors"; else msg+=" error"; msg+=" )\n\n"; std::vector<std::wstring> msgs; TokenizeMail(data, msgs, L"\n"); for(size_t j=0;j<msgs.size();++j) { std::wstring ll; if(!msgs[j].empty()) ll=msgs[j][0]; int li=watoi(ll); msgs[j].erase(0, 2); std::wstring tt=getuntil(L"-", msgs[j]); std::wstring m=getafter(L"-", msgs[j]); q_format_unixtime->Bind(tt); db_results ft=q_format_unixtime->Read(); q_format_unixtime->Reset(); if( !ft.empty() ) { tt=ft[0][L"time"]; } std::string lls="info"; if(li==1) lls="warning"; else if(li==2) lls="error"; msg+=Server->ConvertToUTF8(tt)+"("+lls+"): "+Server->ConvertToUTF8(m)+"\n"; } if(!r_success) subj+=" - failed"; else subj+=" - success"; std::string errmsg; bool b=url_fak->sendMail(mail_server, to_addrs, subj, msg, &errmsg); if(!b) { Server->Log("Sending mail failed. "+errmsg, LL_WARNING); } } } } } } MailServer BackupServerGet::getMailServerSettings(void) { ISettingsReader *settings=Server->createDBSettingsReader(Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER), "settings_db.settings", "SELECT value FROM settings WHERE key=? AND clientid=0"); MailServer ms; ms.servername=settings->getValue("mail_servername", ""); ms.port=(unsigned short)watoi(settings->getValue(L"mail_serverport", L"587")); ms.username=settings->getValue("mail_username", ""); ms.password=settings->getValue("mail_password", ""); ms.mailfrom=settings->getValue("mail_from", ""); if(ms.mailfrom.empty()) ms.mailfrom="report@urbackup.org"; ms.ssl_only=(settings->getValue("mail_ssl_only", "false")=="true")?true:false; ms.check_certificate=(settings->getValue("mail_check_certificate", "false")=="true")?true:false; Server->destroy(settings); return ms; } const unsigned int stat_update_skip=20; const unsigned int sector_size=512; const unsigned int sha_size=32; void writeZeroblockdata(void) { const int64 vhd_blocksize=(1024*1024/2); unsigned char *zeroes=new unsigned char[vhd_blocksize]; memset(zeroes, 0, vhd_blocksize); unsigned char dig[sha_size]; sha256(zeroes, vhd_blocksize, dig); IFile *out=Server->openFile("zero.hash", MODE_WRITE); out->Write((char*)dig, sha_size); Server->destroy(out); delete []zeroes; } bool BackupServerGet::doImage(const std::string &pLetter, const std::wstring &pParentvhd, int incremental, int incremental_ref) { CTCPStack tcpstack; IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed - CONNECT error", LL_ERROR); return false; } std::string sletter=pLetter; if(pLetter!="SYSVOL") { sletter=pLetter[0]; } if(pParentvhd.empty()) { tcpstack.Send(cc, server_identity+"FULL IMAGE letter="+pLetter+"&token="+server_token); } else { IFile *hashfile=Server->openFile(os_file_prefix()+pParentvhd+L".hash"); if(hashfile==NULL) { ServerLogger::Log(clientid, "Error opening hashfile", LL_ERROR); Server->Log("Starting image path repair...", LL_INFO); ServerUpdateStats::repairImages(); Server->destroy(cc); return false; } std::string ts=server_identity+"INCR IMAGE letter="+pLetter+"&hashsize="+nconvert(hashfile->Size())+"&token="+server_token; size_t rc=tcpstack.Send(cc, ts); if(rc==0) { ServerLogger::Log(clientid, "Sending 'INCR IMAGE' command failed", LL_ERROR); Server->destroy(cc); Server->destroy(hashfile); return false; } hashfile->Seek(0); char buffer[4096]; for(size_t i=0,hsize=(size_t)hashfile->Size();i<hsize;i+=4096) { size_t tsend=(std::min)((size_t)4096, hsize-i); if(hashfile->Read(buffer, (_u32)tsend)!=tsend) { ServerLogger::Log(clientid, "Reading from hashfile failed", LL_ERROR); Server->destroy(cc); Server->destroy(hashfile); return false; } if(!cc->Write(buffer, tsend)) { ServerLogger::Log(clientid, "Sending hashdata failed", LL_ERROR); Server->destroy(cc); Server->destroy(hashfile); return false; } } Server->destroy(hashfile); } std::wstring imagefn=constructImagePath(widen(sletter)); int64 free_space=os_free_space(os_file_prefix()+ExtractFilePath(imagefn)); if(free_space!=-1 && free_space<minfreespace_image) { ServerLogger::Log(clientid, "Not enough free space. Cleaning up.", LL_INFO); ServerCleanupThread cleanup; if(!cleanup.do_cleanup(minfreespace_image) ) { ServerLogger::Log(clientid, "Could not free space for image. NOT ENOUGH FREE SPACE.", LL_ERROR); Server->destroy(cc); return false; } } { std::string mbrd=getMBR(widen(sletter)); if(mbrd.empty()) { if(pLetter!="SYSVOL") { ServerLogger::Log(clientid, "Error getting MBR data", LL_ERROR); } } else { IFile *mbr_file=Server->openFile(os_file_prefix()+imagefn+L".mbr", MODE_WRITE); if(mbr_file!=NULL) { _u32 w=mbr_file->Write(mbrd); if(w!=mbrd.size()) { Server->Log("Error writing mbr data.", LL_ERROR); Server->destroy(mbr_file); Server->destroy(cc); return false; } Server->destroy(mbr_file); } else { Server->Log("Error creating file for writing MBR data.", LL_ERROR); Server->destroy(cc); return false; } } } if(pParentvhd.empty()) backupid=createBackupImageSQL(0,0, clientid, imagefn, pLetter); else backupid=createBackupImageSQL(incremental, incremental_ref, clientid, imagefn, pLetter); std::string ret; unsigned int starttime=Server->getTimeMS(); bool first=true; char buffer[4096]; unsigned int blocksize=0xFFFFFFFF; unsigned int blockleft=0; int64 currblock=-1; char *blockdata=NULL; int64 drivesize; ServerVHDWriter *vhdfile=NULL; THREADPOOL_TICKET vhdfile_ticket; IVHDFile *r_vhdfile=NULL; IFile *hashfile=NULL; IFile *parenthashfile=NULL; int64 blockcnt=0; int64 numblocks=0; int64 totalblocks=0; int64 mbr_offset=0; _u32 off=0; std::string shadowdrive; int shadow_id=-1; bool persistent=false; unsigned char *zeroblockdata=NULL; int64 nextblock=0; int64 vhd_blocksize=(1024*1024)/2; ServerRunningUpdater *running_updater=new ServerRunningUpdater(backupid, true); Server->getThreadPool()->execute(running_updater); bool has_parent=false; if(!pParentvhd.empty()) has_parent=true; sha256_ctx shactx; sha256_init(&shactx); unsigned int stat_update_cnt=0; while(Server->getTimeMS()-starttime<=image_timeout) { size_t r=cc->Read(&buffer[off], 4096-off, image_recv_timeout); if(r!=0) r+=off; starttime=Server->getTimeMS(); off=0; if(r==0 ) { if(persistent && nextblock!=0) { bool reconnected=false; while(Server->getTimeMS()-starttime<=image_timeout) { ServerStatus::setROnline(clientname, false); if(cc!=NULL) Server->destroy(cc); Server->Log("Trying to reconnect in doImage", LL_DEBUG); cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { std::string msg; if(pipe->Read(&msg, 0)>0) { if(msg.find("address")==0) { IScopedLock lock(clientaddr_mutex); memcpy(&clientaddr, &msg[7], sizeof(sockaddr_in) ); } else { pipe->Write(msg); } Server->wait(60000); } } else { reconnected=true; ServerStatus::setROnline(clientname, true); Server->Log("Reconnected.", LL_DEBUG); break; } } if(!reconnected) { ServerLogger::Log(clientid, "Timeout while trying to reconnect", LL_ERROR); goto do_image_cleanup; } if(pParentvhd.empty()) { tcpstack.Send(cc, server_identity+"FULL IMAGE letter="+pLetter+"&shadowdrive="+shadowdrive+"&start="+nconvert(nextblock)+"&shadowid="+nconvert(shadow_id)); } else { std::string ts="INCR IMAGE letter=C:&shadowdrive="+shadowdrive+"&start="+nconvert(nextblock)+"&shadowid="+nconvert(shadow_id)+"&hashsize="+nconvert(parenthashfile->Size()); size_t rc=tcpstack.Send(cc, server_identity+ts); if(rc==0) { ServerLogger::Log(clientid, "Sending 'INCR IMAGE' command failed", LL_ERROR); goto do_image_cleanup; } parenthashfile->Seek(0); char buffer[4096]; for(size_t i=0,hsize=(size_t)parenthashfile->Size();i<hsize;i+=4096) { size_t tsend=(std::min)((size_t)4096, hsize-i); if(parenthashfile->Read(buffer, (_u32)tsend)!=tsend) { ServerLogger::Log(clientid, "Reading from hashfile failed i="+nconvert(i), LL_ERROR); goto do_image_cleanup; } if(!cc->Write(buffer, tsend)) { ServerLogger::Log(clientid, "Sending hashdata failed", LL_ERROR); goto do_image_cleanup; } } } off=0; starttime=Server->getTimeMS(); blockleft=0; currblock=-1; } else { ServerLogger::Log(clientid, "Pipe to client unexpectedly closed", LL_ERROR); goto do_image_cleanup; } } else { if(first) { first=false; if(r>=sizeof(unsigned int)) { memcpy(&blocksize, buffer, sizeof(unsigned int) ); off+=sizeof(unsigned int); vhd_blocksize/=blocksize; } if(blocksize==0xFFFFFFFF) { off+=sizeof(unsigned int); if(r>sizeof(uint64)) { std::string err; err.resize(r-sizeof(uint64) ); memcpy(&err[0], &buffer[off], r-off); if(pLetter!="SYSVOL") { ServerLogger::Log(clientid, "Request of image backup failed. Reason: "+err, LL_ERROR); } else { ServerLogger::Log(clientid, "Request of SYSVOL failed. Reason: "+err, LL_INFO); } } else { ServerLogger::Log(clientid, "Error on client. No reason given.", LL_ERROR); } goto do_image_cleanup; } bool issmall=false; if(r>=sizeof(unsigned int)+sizeof(int64)) { memcpy(&drivesize, &buffer[off], sizeof(int64) ); off+=sizeof(int64); blockcnt=drivesize/blocksize; totalblocks=blockcnt; zeroblockdata=new unsigned char[blocksize]; memset(zeroblockdata, 0, blocksize); if(!has_parent) r_vhdfile=image_fak->createVHDFile(os_file_prefix()+imagefn, false, drivesize+(int64)mbr_size, (unsigned int)vhd_blocksize*blocksize); else r_vhdfile=image_fak->createVHDFile(os_file_prefix()+imagefn, pParentvhd, false); if(r_vhdfile==NULL) { ServerLogger::Log(clientid, L"Error opening VHD file \""+imagefn+L"\"", LL_ERROR); goto do_image_cleanup; } vhdfile=new ServerVHDWriter(r_vhdfile, blocksize, 5000, clientid); vhdfile_ticket=Server->getThreadPool()->execute(vhdfile); blockdata=vhdfile->getBuffer(); hashfile=Server->openFile(os_file_prefix()+imagefn+L".hash", MODE_WRITE); if(hashfile==NULL) { ServerLogger::Log(clientid, L"Error opening Hashfile \""+imagefn+L".hash\"", LL_ERROR); goto do_image_cleanup; } if(has_parent) { parenthashfile=Server->openFile(os_file_prefix()+pParentvhd+L".hash", MODE_READ); if(parenthashfile==NULL) { ServerLogger::Log(clientid, L"Error opening Parenthashfile \""+pParentvhd+L".hash\"", LL_ERROR); goto do_image_cleanup; } } mbr_offset=writeMBR(vhdfile, drivesize); } else { issmall=true; } if(r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)) { memcpy(&blockcnt, &buffer[off], sizeof(int64) ); off+=sizeof(int64); } else { issmall=true; } if(r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)+1) { char c_persistent=buffer[off]; if(c_persistent!=0) persistent=true; ++off; } else { issmall=true; } unsigned int shadowdrive_size=0; if(r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)+1+sizeof(unsigned int)) { memcpy(&shadowdrive_size, &buffer[off], sizeof(unsigned int)); off+=sizeof(unsigned int); if(shadowdrive_size>0) { if( r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)+1+sizeof(unsigned int)+shadowdrive_size) { shadowdrive.resize(shadowdrive_size); memcpy(&shadowdrive[0], &buffer[off], shadowdrive_size); off+=shadowdrive_size; } else { issmall=true; } } } else { issmall=true; } if(r>=sizeof(unsigned int)+sizeof(int64)+sizeof(int64)+1+sizeof(unsigned int)+shadowdrive_size+sizeof(int)) { memcpy(&shadow_id, &buffer[off], sizeof(int)); off+=sizeof(int); } else { issmall=true; } if(issmall) { ServerLogger::Log(clientid, "First packet to small", LL_ERROR); goto do_image_cleanup; } if(r==off) { off=0; continue; } } while(true) { if(blockleft==0) { if(currblock!=-1) // write current block { ++numblocks; ++stat_update_cnt; if(stat_update_cnt%stat_update_skip==0) { stat_update_cnt=0; if(blockcnt!=0) { if(has_parent) { status.pcdone=(int)(((double)currblock/(double)totalblocks)*100.0+0.5); } else { status.pcdone=(int)(((double)numblocks/(double)blockcnt)*100.0+0.5); } ServerStatus::setServerStatus(status, true); } } nextblock=updateNextblock(nextblock, currblock, &shactx, zeroblockdata, has_parent, vhdfile, hashfile, parenthashfile, blocksize, mbr_offset, vhd_blocksize); sha256_update(&shactx, (unsigned char *)blockdata, blocksize); vhdfile->writeBuffer(mbr_offset+currblock*blocksize, blockdata, blocksize); blockdata=vhdfile->getBuffer(); if(nextblock%vhd_blocksize==0 && nextblock!=0) { //Server->Log("Hash written "+nconvert(currblock), LL_DEBUG); unsigned char dig[sha_size]; sha256_final(&shactx, dig); hashfile->Write((char*)dig, sha_size); sha256_init(&shactx); } if(vhdfile->hasError()) { ServerLogger::Log(clientid, "FATAL ERROR: Could not write to VHD-File", LL_ERROR); goto do_image_cleanup; } currblock=-1; } if(r-off>=sizeof(int64) ) { memcpy(&currblock, &buffer[off], sizeof(int64) ); if(currblock==-123) { int64 t_totalblocks=totalblocks; if(t_totalblocks%vhd_blocksize!=0) t_totalblocks+=vhd_blocksize-t_totalblocks%vhd_blocksize; nextblock=updateNextblock(nextblock, t_totalblocks, &shactx, zeroblockdata, has_parent, vhdfile, hashfile, parenthashfile, blocksize, mbr_offset, vhd_blocksize); if(nextblock%vhd_blocksize==0 && nextblock!=0) { //Server->Log("Hash written "+nconvert(nextblock), LL_INFO); unsigned char dig[sha_size]; sha256_final(&shactx, dig); hashfile->Write((char*)dig, sha_size); } Server->destroy(cc); if(hashfile!=NULL) Server->destroy(hashfile); if(vhdfile!=NULL) { vhdfile->freeBuffer(blockdata); } if(parenthashfile!=NULL) Server->destroy(parenthashfile); bool vhdfile_err=false; status.action_done=true; ServerStatus::setServerStatus(status); if(vhdfile!=NULL) { vhdfile->doExit(); Server->getThreadPool()->waitFor(vhdfile_ticket); vhdfile_err=vhdfile->hasError(); delete vhdfile; vhdfile=NULL; } IFile *t_file=Server->openFile(os_file_prefix()+imagefn, MODE_READ); if(t_file!=NULL) { db->BeginTransaction(); q_set_image_size->Bind(t_file->Size()); q_set_image_size->Bind(backupid); q_set_image_size->Write(); q_set_image_size->Reset(); q_update_images_size->Bind(clientid); q_update_images_size->Bind(t_file->Size()); q_update_images_size->Bind(clientid); q_update_images_size->Write(); q_update_images_size->Reset(); if(vhdfile_err==false) { setBackupImageComplete(); } db->EndTransaction(); Server->destroy(t_file); } running_updater->stop(); updateRunning(true); return !vhdfile_err; } else if(currblock==-124 || #ifndef _WIN32 currblock==0xFFFFFFFFFFFFFFFFLLU) #else currblock==0xFFFFFFFFFFFFFFFF) #endif { if(r-off>sizeof(int64)) { std::string err; err.resize(r-off-sizeof(int64) ); memcpy(&err[0], &buffer[off+sizeof(int64)], r-off-sizeof(int64)); ServerLogger::Log(clientid, "Error on client occured: "+err, LL_ERROR); } Server->destroy(cc); if(vhdfile!=NULL) { vhdfile->freeBuffer(blockdata); vhdfile->doExitNow(); std::vector<THREADPOOL_TICKET> wf;wf.push_back(vhdfile_ticket); Server->getThreadPool()->waitFor(wf); delete vhdfile; vhdfile=NULL; } if(hashfile!=NULL) Server->destroy(hashfile); if(parenthashfile!=NULL) Server->destroy(parenthashfile); running_updater->stop(); return false; } else if(currblock==-125) //ping { off+=sizeof(int64); currblock=-1; } else { off+=sizeof(int64); blockleft=blocksize; } } else if(r-off>0) { char buf2[4096]; memcpy(buf2, &buffer[off], r-off); memcpy(buffer, buf2, r-off); off=(_u32)r-off; break; } else { off=0; break; } } else { unsigned int available=(std::min)(blockleft, (unsigned int)r-off); memcpy(&blockdata[blocksize-blockleft], &buffer[off], available); blockleft-=available; off+=available; if( off>=r ) { off=0; break; } } } } } ServerLogger::Log(clientid, "Timeout while transfering image data", LL_ERROR); do_image_cleanup: Server->destroy(cc); if(vhdfile!=NULL) { if(blockdata!=NULL) vhdfile->freeBuffer(blockdata); vhdfile->doExitNow(); Server->getThreadPool()->waitFor(vhdfile_ticket); delete vhdfile; vhdfile=NULL; } if(hashfile!=NULL) Server->destroy(hashfile); if(parenthashfile!=NULL) Server->destroy(parenthashfile); running_updater->stop(); return false; } unsigned int BackupServerGet::writeMBR(ServerVHDWriter *vhdfile, uint64 volsize) { unsigned char *mbr=(unsigned char *)vhdfile->getBuffer(); unsigned char *mptr=mbr; memcpy(mptr, mbr_code, 440); mptr+=440; int sig=rand(); memcpy(mptr, &sig, sizeof(int)); mptr+=sizeof(int); *mptr=0; ++mptr; *mptr=0; ++mptr; unsigned char partition[16]; partition[0]=0x80; partition[1]=0xfe; partition[2]=0xff; partition[3]=0xff; partition[4]=0x07; //ntfs partition[5]=0xfe; partition[6]=0xff; partition[7]=0xff; partition[8]=0x00; partition[9]=0x04; partition[10]=0x00; partition[11]=0x00; unsigned int sectors=(unsigned int)(volsize/((uint64)sector_size)); memcpy(&partition[12], &sectors, sizeof(unsigned int) ); memcpy(mptr, partition, 16); mptr+=16; for(int i=0;i<3;++i) { memset(mptr, 0, 16); mptr+=16; } *mptr=0x55; ++mptr; *mptr=0xaa; vhdfile->writeBuffer(0, (char*)mbr, 512); for(int i=0;i<1023;++i) { char *buf=vhdfile->getBuffer(); memset(buf, 0, 512); vhdfile->writeBuffer((i+1)*512, buf, 512); } return 1024*512; } int64 BackupServerGet::updateNextblock(int64 nextblock, int64 currblock, sha256_ctx *shactx, unsigned char *zeroblockdata, bool parent_fn, ServerVHDWriter *parentfile, IFile *hashfile, IFile *parenthashfile, unsigned int blocksize, int64 mbr_offset, int64 vhd_blocksize) { unsigned char *blockdata=NULL; if(parent_fn) blockdata=new unsigned char[blocksize]; if(currblock-nextblock>vhd_blocksize) { while(true) { if(!parent_fn) { sha256_update(shactx, zeroblockdata, blocksize); } else { { IScopedLock lock(parentfile->getVHDMutex()); IVHDFile *vhd=parentfile->getVHD(); vhd->Seek(mbr_offset+nextblock*blocksize); size_t read; bool b=vhd->Read((char*)blockdata, blocksize, read); if(!b) Server->Log("Reading from VHD failed", LL_ERROR); } sha256_update(shactx, blockdata, blocksize); } ++nextblock; if(nextblock%vhd_blocksize==0) { unsigned char dig[sha_size]; sha256_final(shactx, dig); hashfile->Write((char*)dig, sha_size); sha256_init(shactx); break; } } while(currblock-nextblock>vhd_blocksize) { if(!parent_fn) { hashfile->Write((char*)zero_hash, sha_size); } else { bool b=parenthashfile->Seek((nextblock/vhd_blocksize)*sha_size); if(!b) { Server->Log("Seeking in parenthashfile failed", LL_ERROR); } char dig[sha_size]; _u32 rc=parenthashfile->Read(dig, sha_size); if(rc!=sha_size) Server->Log("Writing to parenthashfile failed", LL_ERROR); hashfile->Write(dig, sha_size); } nextblock+=vhd_blocksize; } } while(nextblock<currblock) { if(!parent_fn) { sha256_update(shactx, zeroblockdata, blocksize); } else { { IScopedLock lock(parentfile->getVHDMutex()); IVHDFile *vhd=parentfile->getVHD(); vhd->Seek(mbr_offset+nextblock*blocksize); size_t read; bool b=vhd->Read((char*)blockdata, blocksize, read); if(!b) Server->Log("Reading from VHD failed", LL_ERROR); } sha256_update(shactx, blockdata, blocksize); } ++nextblock; if(nextblock%vhd_blocksize==0 && nextblock!=0) { unsigned char dig[sha_size]; sha256_final(shactx, dig); hashfile->Write((char*)dig, sha_size); sha256_init(shactx); } } delete [] blockdata; return nextblock+1; } std::string BackupServerGet::getMBR(const std::wstring &dl) { std::string ret=sendClientMessage("MBR driveletter="+wnarrow(dl), L"Getting MBR for drive "+dl+L" failed", 10000); CRData r(&ret); char b; if(r.getChar(&b) && b==1 ) { char ver; if(r.getChar(&ver) ) { if(ver!=0) { ServerLogger::Log(clientid, L"Server version does not fit", LL_ERROR); } else { return ret; } } else { ServerLogger::Log(clientid, L"Could not read version information in MBR", LL_ERROR); } } else if(dl!=L"SYSVOL") { ServerLogger::Log(clientid, L"Could not read MBR", LL_ERROR); } return ""; } void BackupServerGet::checkClientVersion(void) { std::string version=getFile("urbackup/version.txt"); if(!version.empty()) { std::string r=sendClientMessage("VERSION "+version, L"Sending version to client failed", 10000); if(r=="update") { IFile *sigfile=Server->openFile("urbackup/UrBackupUpdate.sig", MODE_READ); if(sigfile==NULL) { ServerLogger::Log(clientid, "Error opening sigfile", LL_ERROR); return; } IFile *updatefile=Server->openFile("urbackup/UrBackupUpdate.exe", MODE_READ); if(updatefile==NULL) { ServerLogger::Log(clientid, "Error opening updatefile", LL_ERROR); return; } size_t datasize=3*sizeof(unsigned int)+version.size()+(size_t)sigfile->Size()+(size_t)updatefile->Size(); CTCPStack tcpstack; IPipe *cc=Server->ConnectStream(inet_ntoa(getClientaddr().sin_addr), serviceport, 10000); if(cc==NULL) { ServerLogger::Log(clientid, L"Connecting to ClientService of \""+clientname+L"\" failed - CONNECT error", LL_ERROR); return; } std::string msg="CLIENTUPDATE "+nconvert(datasize); tcpstack.Send(cc, server_identity+msg); int timeout=10000; unsigned int c_size=(unsigned int)version.size(); if(!cc->Write((char*)&c_size, sizeof(unsigned int), timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } if(!cc->Write(version, timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } c_size=(unsigned int)sigfile->Size(); if(!cc->Write((char*)&c_size, sizeof(unsigned int), timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } if(!sendFile(cc, sigfile, timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } c_size=(unsigned int)updatefile->Size(); if(!cc->Write((char*)&c_size, sizeof(unsigned int), timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } if(!sendFile(cc, updatefile, timeout) ) { Server->destroy(cc); Server->destroy(sigfile); Server->destroy(updatefile); return; } Server->destroy(sigfile); Server->destroy(updatefile); std::string ret; unsigned int starttime=Server->getTimeMS(); bool ok=false; while(Server->getTimeMS()-starttime<=10000) { size_t rc=cc->Read(&ret, timeout); if(rc==0) { ServerLogger::Log(clientid, "Reading from client failed in update", LL_ERROR); break; } tcpstack.AddData((char*)ret.c_str(), ret.size()); size_t packetsize; char *pck=tcpstack.getPacket(&packetsize); if(pck!=NULL && packetsize>0) { ret.resize(packetsize); memcpy(&ret[0], pck, packetsize); delete [] pck; if(ret=="ok") { ok=true; break; } else { ok=false; ServerLogger::Log(clientid, "Error in update: "+ret, LL_ERROR); break; } } } if(!ok) { ServerLogger::Log(clientid, L"Timeout: In client update", LL_ERROR); } Server->destroy(cc); ServerLogger::Log(clientid, L"Updated client successfully", LL_INFO); } } } bool BackupServerGet::sendFile(IPipe *cc, IFile *f, int timeout) { char buf[4096]; _u32 r; while((r=f->Read(buf, 4096))>0) { if(!cc->Write(buf, r, timeout)) return false; } return true; } sockaddr_in BackupServerGet::getClientaddr(void) { IScopedLock lock(clientaddr_mutex); return clientaddr; } std::string BackupServerGet::strftimeInt(std::string fs) { time_t rawtime; char buffer [100]; time ( &rawtime ); #ifdef _WIN32 struct tm timeinfo; localtime_s(&timeinfo, &rawtime); strftime (buffer,100,fs.c_str(),&timeinfo); #else struct tm *timeinfo; timeinfo = localtime ( &rawtime ); strftime (buffer,100,fs.c_str(),timeinfo); #endif std::string r(buffer); return r; } std::string BackupServerGet::remLeadingZeros(std::string t) { std::string r; bool in=false; for(size_t i=0;i<t.size();++i) { if(!in && t[i]!='0' ) in=true; if(in) { r+=t[i]; } } return r; } bool BackupServerGet::isInBackupWindow(std::vector<STimeSpan> bw) { if(bw.empty()) return true; int dow=atoi(strftimeInt("%w").c_str()); if(dow==0) dow=7; float hm=(float)atoi(remLeadingZeros(strftimeInt("%H")).c_str())+(float)atoi(remLeadingZeros(strftimeInt("%M")).c_str())*(1.f/60.f); for(size_t i=0;i<bw.size();++i) { if(bw[i].dayofweek==dow) { if(hm>=bw[i].start_hour && hm<=bw[i].stop_hour ) { return true; } } } return false; } bool BackupServerGet::isBackupsRunningOkay(void) { IScopedLock lock(running_backup_mutex); if(running_backups<server_settings->getSettings()->max_sim_backups) { return true; } else { return false; } } void BackupServerGet::startBackupRunning(bool file) { IScopedLock lock(running_backup_mutex); ++running_backups; if(file) { ++running_file_backups; } } void BackupServerGet::stopBackupRunning(bool file) { IScopedLock lock(running_backup_mutex); --running_backups; if(file) { --running_file_backups; } } int BackupServerGet::getNumberOfRunningBackups(void) { IScopedLock lock(running_backup_mutex); return running_backups; } int BackupServerGet::getNumberOfRunningFileBackups(void) { IScopedLock lock(running_backup_mutex); return running_file_backups; } void BackupServerGet::writeFileRepeat(IFile *f, const std::string &str) { writeFileRepeat(f, str.c_str(), str.size()); } void BackupServerGet::writeFileRepeat(IFile *f, const char *buf, size_t bsize) { _u32 written=0; _u32 rc; int tries=50; do { rc=f->Write(buf+written, (_u32)(bsize-written)); written+=rc; if(rc==0) { Server->Log("Failed to write to file... waiting...", LL_WARNING); Server->wait(10000); --tries; } } while(written<bsize && (rc>0 || tries>0) ); if(rc==0) { Server->Log("Fatal error writing to file in writeFileRepeat. Write error.", LL_ERROR); } } #endif //CLIENT_ONLY
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // --- ROOT system --- #include <TFile.h> #include <TGeoManager.h> #include <TStreamerInfo.h> // ---- ANALYSIS system ---- #include "AliMCEvent.h" #include "AliAODMCHeader.h" #include "AliGenPythiaEventHeader.h" #include "AliGenEventHeader.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliVTrack.h" #include "AliVParticle.h" #include "AliMixedEvent.h" //#include "AliTriggerAnalysis.h" #include "AliESDVZERO.h" #include "AliVCaloCells.h" #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" #include "AliAODMCParticle.h" #include "AliMultSelection.h" // ---- Detectors ---- #include "AliPHOSGeoUtils.h" #include "AliEMCALGeometry.h" #include "AliEMCALRecoUtils.h" // ---- CaloTrackCorr --- #include "AliCalorimeterUtils.h" #include "AliCaloTrackReader.h" // ---- Jets ---- #include "AliAODJet.h" #include "AliAODJetEventBackground.h" /// \cond CLASSIMP ClassImp(AliCaloTrackReader) ; /// \endcond //________________________________________ /// Constructor. Initialize parameters. //________________________________________ AliCaloTrackReader::AliCaloTrackReader() : TObject(), fEventNumber(-1), //fCurrentFileName(""), fDataType(0), fDebug(0), fFiducialCut(0x0), fCheckFidCut(kFALSE), fComparePtHardAndJetPt(0), fPtHardAndJetPtFactor(0), fComparePtHardAndClusterPt(0),fPtHardAndClusterPtFactor(0), fCTSPtMin(0), fEMCALPtMin(0), fPHOSPtMin(0), fCTSPtMax(0), fEMCALPtMax(0), fPHOSPtMax(0), fEMCALBadChMinDist(0), fPHOSBadChMinDist (0), fEMCALNCellsCut(0), fPHOSNCellsCut(0), fUseEMCALTimeCut(1), fUseParamTimeCut(0), fUseTrackTimeCut(0), fAccessTrackTOF(0), fEMCALTimeCutMin(-10000), fEMCALTimeCutMax(10000), fEMCALParamTimeCutMin(), fEMCALParamTimeCutMax(), fTrackTimeCutMin(-10000), fTrackTimeCutMax(10000), fUseTrackDCACut(0), fAODBranchList(0x0), fCTSTracks(0x0), fEMCALClusters(0x0), fDCALClusters(0x0), fPHOSClusters(0x0), fEMCALCells(0x0), fPHOSCells(0x0), fInputEvent(0x0), fOutputEvent(0x0),fMC(0x0), fFillCTS(0), fFillEMCAL(0), fFillDCAL(0), fFillPHOS(0), fFillEMCALCells(0), fFillPHOSCells(0), fRecalculateClusters(kFALSE),fCorrectELinearity(kTRUE), fSelectEmbeddedClusters(kFALSE), fSmearShowerShape(0), fSmearShowerShapeWidth(0), fRandom(), fSmearingFunction(0), fSmearNLMMin(0), fSmearNLMMax(0), fTrackStatus(0), fSelectSPDHitTracks(0), fTrackMultNPtCut(0), fTrackMultEtaCut(0.9), fDeltaAODFileName(""), fFiredTriggerClassName(""), fEventTriggerMask(0), fMixEventTriggerMask(0), fEventTriggerAtSE(0), fEventTrigMinBias(0), fEventTrigCentral(0), fEventTrigSemiCentral(0), fEventTrigEMCALL0(0), fEventTrigEMCALL1Gamma1(0), fEventTrigEMCALL1Gamma2(0), fEventTrigEMCALL1Jet1(0), fEventTrigEMCALL1Jet2(0), fBitEGA(0), fBitEJE(0), fEventType(-1), fTaskName(""), fCaloUtils(0x0), fWeightUtils(0x0), fEventWeight(1), fMixedEvent(NULL), fNMixedEvent(0), fVertex(NULL), fListMixedTracksEvents(), fListMixedCaloEvents(), fLastMixedTracksEvent(-1), fLastMixedCaloEvent(-1), fWriteOutputDeltaAOD(kFALSE), fEMCALClustersListName(""), fZvtxCut(0.), fAcceptFastCluster(kFALSE), fRemoveLEDEvents(kFALSE), //Trigger rejection fRemoveBadTriggerEvents(0), fTriggerPatchClusterMatch(1), fTriggerPatchTimeWindow(), fTriggerL0EventThreshold(0), fTriggerL1EventThreshold(0), fTriggerL1EventThresholdFix(0), fTriggerClusterBC(0), fTriggerClusterIndex(0), fTriggerClusterId(0), fIsExoticEvent(0), fIsBadCellEvent(0), fIsBadMaxCellEvent(0), fIsTriggerMatch(0), fIsTriggerMatchOpenCut(), fTriggerClusterTimeRecal(kTRUE), fRemoveUnMatchedTriggers(kTRUE), fDoPileUpEventRejection(kFALSE), fDoV0ANDEventSelection(kFALSE), fDoVertexBCEventSelection(kFALSE), fDoRejectNoTrackEvents(kFALSE), fUseEventsWithPrimaryVertex(kFALSE), //fTriggerAnalysis (0x0), fTimeStampEventSelect(0), fTimeStampEventFracMin(0), fTimeStampEventFracMax(0), fTimeStampRunMin(0), fTimeStampRunMax(0), fNPileUpClusters(-1), fNNonPileUpClusters(-1), fNPileUpClustersCut(3), fVertexBC(-200), fRecalculateVertexBC(0), fUseAliCentrality(0), fCentralityClass(""), fCentralityOpt(0), fEventPlaneMethod(""), fFillInputNonStandardJetBranch(kFALSE), fNonStandardJets(new TClonesArray("AliAODJet",100)), fInputNonStandardJetBranchName("jets"), fFillInputBackgroundJetBranch(kFALSE), fBackgroundJets(0x0),fInputBackgroundJetBranchName("jets"), fAcceptEventsWithBit(0), fRejectEventsWithBit(0), fRejectEMCalTriggerEventsWith2Tresholds(0), fMomentum(), fOutputContainer(0x0), fhEMCALClusterTimeE(0), fEnergyHistogramNbins(0), fhNEventsAfterCut(0), fNMCGenerToAccept(0), fMCGenerEventHeaderToAccept("") { for(Int_t i = 0; i < 8; i++) fhEMCALClusterCutsE [i]= 0x0 ; for(Int_t i = 0; i < 7; i++) fhPHOSClusterCutsE [i]= 0x0 ; for(Int_t i = 0; i < 6; i++) fhCTSTrackCutsPt [i]= 0x0 ; for(Int_t j = 0; j < 5; j++) { fMCGenerToAccept [j] = ""; fMCGenerIndexToAccept[j] = -1; } InitParameters(); } //_______________________________________ /// Destructor. //_______________________________________ AliCaloTrackReader::~AliCaloTrackReader() { DeletePointers(); } //_______________________________________ /// Destructor. Called by the destructors /// of this class and derived classes. //_______________________________________ void AliCaloTrackReader::DeletePointers() { delete fFiducialCut ; if(fAODBranchList) { fAODBranchList->Delete(); delete fAODBranchList ; } if(fCTSTracks) { if(fDataType!=kMC)fCTSTracks->Clear() ; else fCTSTracks->Delete() ; delete fCTSTracks ; } if(fEMCALClusters) { if(fDataType!=kMC)fEMCALClusters->Clear("C") ; else fEMCALClusters->Delete() ; delete fEMCALClusters ; } if(fDCALClusters) { if(fDataType!=kMC)fDCALClusters->Clear("C") ; else fDCALClusters->Delete() ; delete fDCALClusters ; } if(fPHOSClusters) { if(fDataType!=kMC)fPHOSClusters->Clear("C") ; else fPHOSClusters->Delete() ; delete fPHOSClusters ; } if(fVertex) { for (Int_t i = 0; i < fNMixedEvent; i++) { delete [] fVertex[i] ; } delete [] fVertex ; } //delete fTriggerAnalysis; if(fNonStandardJets) { if(fDataType!=kMC) fNonStandardJets->Clear("C") ; else fNonStandardJets->Delete() ; delete fNonStandardJets ; } delete fBackgroundJets ; fRejectEventsWithBit.Reset(); fAcceptEventsWithBit.Reset(); if ( fWeightUtils ) delete fWeightUtils ; // Pointers not owned, done by the analysis frame // if(fInputEvent) delete fInputEvent ; // if(fOutputEvent) delete fOutputEvent ; // if(fMC) delete fMC ; // Pointer not owned, deleted by maker // if (fCaloUtils) delete fCaloUtils ; } //____________________________________________________________ /// Accept track if DCA is smaller than function. /// \param pt of track. /// \param dca of track. //____________________________________________________________ Bool_t AliCaloTrackReader::AcceptDCA(Float_t pt, Float_t dca) { Float_t cut = fTrackDCACut[0]+fTrackDCACut[1]/TMath::Power(pt,fTrackDCACut[2]); if(TMath::Abs(dca) < cut) return kTRUE; else return kFALSE; } //_____________________________________________________ /// Accept events that pass the physics selection /// depending on an array of trigger bits set during the configuration. //_____________________________________________________ Bool_t AliCaloTrackReader::AcceptEventWithTriggerBit() { Int_t nAccept = fAcceptEventsWithBit.GetSize(); //printf("N accept %d\n", nAccept); if( nAccept <= 0 ) return kTRUE ; // accept the event UInt_t trigFired = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); for(Int_t ibit = 0; ibit < nAccept; ibit++) { Bool_t accept = (trigFired & fAcceptEventsWithBit.At(ibit)); //printf("accept %d, ibit %d, bit %d \n",accept, ibit,fAcceptEventsWithBit.At(ibit)); if(accept) return kTRUE ; // accept the event } return kFALSE ; // reject the event } //_____________________________________________________ /// Reject particles/clusters depending on the generator /// of origin of the MC label. /// /// \param mcLabel label index of particle originating the cluster or track or mc stack //_____________________________________________________ Bool_t AliCaloTrackReader::AcceptParticleMCLabel(Int_t mcLabel) const { if( !fMC || fNMCGenerToAccept <= 0 ) return kTRUE; TString genName; Int_t genIndex; genIndex = GetCocktailGeneratorAndIndex(mcLabel, genName); //fMC->GetCocktailGenerator(mcLabel,genName); Bool_t generOK = kFALSE; for(Int_t ig = 0; ig < fNMCGenerToAccept; ig++) { if ( fMCGenerToAccept[ig].Contains(genName) ) generOK = kTRUE; if ( generOK && fMCGenerIndexToAccept[ig] >= 0 && fMCGenerToAccept[ig] != genIndex) generOK = kFALSE; } if ( !generOK ) AliDebug(1, Form("skip label %d, gen %s",mcLabel,genName.Data()) ); return generOK; } //_____________________________________________________________________ /// Get the name of the generator that generated a given primary particle /// Copy of AliMCEvent::GetCocktailGeneratorAndIndex(), modified to get the /// the generator index in the cocktail /// /// \param index: mc label index /// \param nameGen: cocktail generator name for this index /// \return cocktail generator index //_____________________________________________________________________ Int_t AliCaloTrackReader::GetCocktailGeneratorAndIndex(Int_t index, TString & nameGen) const { //method that gives the generator for a given particle with label index (or that of the corresponding primary) AliVParticle* mcpart0 = (AliVParticle*) GetMC()->GetTrack(index); Int_t genIndex = -1; if(!mcpart0) { printf("AliMCEvent-BREAK: No valid AliMCParticle at label %i\n",index); return -1; } nameGen = GetGeneratorNameAndIndex(index,genIndex); if(nameGen.Contains("nococktailheader") ) return -1; Int_t lab=index; while(nameGen.IsWhitespace()) { AliVParticle* mcpart = (AliVParticle*) GetMC()->GetTrack(lab); if(!mcpart) { printf("AliMCEvent-BREAK: No valid AliMCParticle at label %i\n",lab); break; } Int_t mother=0; mother = mcpart->GetMother(); if(mother<0) { printf("AliMCEvent - BREAK: Reached primary particle without valid mother\n"); break; } AliVParticle* mcmom = (AliVParticle*) GetMC()->GetTrack(mother); if(!mcmom) { printf("AliMCEvent-BREAK: No valid AliMCParticle mother at label %i\n",mother); break; } lab=mother; nameGen = GetGeneratorNameAndIndex(mother,genIndex); } return genIndex; } //_____________________________________________________________________ /// Get the name of the generator that generated a given primary particle /// Copy of AliMCEvent::GetGenerator(), modified to get the /// the generator index in the cocktail /// /// \param index: mc label index /// \param genIndex: cocktail generator name for this index /// \return cocktail generator name string //_____________________________________________________________________ TString AliCaloTrackReader::GetGeneratorNameAndIndex(Int_t index, Int_t & genIndex) const { Int_t nsumpart = GetMC()->GetNumberOfPrimaries(); genIndex = -1; TList* lh = GetMC()->GetCocktailList(); if(!lh) { TString noheader="nococktailheader"; return noheader; } Int_t nh = lh->GetEntries(); for (Int_t i = nh-1; i >= 0; i--) { AliGenEventHeader* gh = (AliGenEventHeader*)lh->At(i); TString genname = gh->GetName(); Int_t npart=gh->NProduced(); if (i == 0) npart = nsumpart; if(index < nsumpart && index >= (nsumpart-npart)) { genIndex = i ; return genname; } nsumpart-=npart; } TString empty=""; return empty; } //_____________________________________________________ /// Reject events that pass the physics selection /// depending on an array of trigger bits set during the configuration. //_____________________________________________________ Bool_t AliCaloTrackReader::RejectEventWithTriggerBit() { Int_t nReject = fRejectEventsWithBit.GetSize(); //printf("N reject %d\n", nReject); if( nReject <= 0 ) return kTRUE ; // accept the event UInt_t trigFired = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); for(Int_t ibit = 0; ibit < nReject; ibit++) { Bool_t reject = (trigFired & fRejectEventsWithBit.At(ibit)); //printf("reject %d, ibit %d, bit %d \n",reject, ibit,fRejectEventsWithBit.At(ibit)); if(reject) return kFALSE ; // reject the event } return kTRUE ; // accept the event } //_____________________________________________ /// Do different selection of the event /// depending on trigger name, event type, /// goodness of the EMCal trigger ... //_____________________________________________ Bool_t AliCaloTrackReader::CheckEventTriggers() { //----------------------------------------------------------- // Reject events depending on the trigger name //----------------------------------------------------------- AliDebug(1,Form("FiredTriggerClass <%s>, selected class <%s>, compare name %d", GetFiredTriggerClasses().Data(),fFiredTriggerClassName.Data(), GetFiredTriggerClasses().Contains(fFiredTriggerClassName))); if ( fFiredTriggerClassName != "" ) { if ( !GetFiredTriggerClasses().Contains(fFiredTriggerClassName) ) return kFALSE; else AliDebug(1,"Accepted triggered event"); } fhNEventsAfterCut->Fill(1.5); //----------------------------------------------------------- // Reject events depending on the event species type //----------------------------------------------------------- // Event types: // kStartOfRun = 1, // START_OF_RUN // kEndOfRun = 2, // END_OF_RUN // kStartOfRunFiles = 3, // START_OF_RUN_FILES // kEndOfRunFiles = 4, // END_OF_RUN_FILES // kStartOfBurst = 5, // START_OF_BURST // kEndOfBurst = 6, // END_OF_BURST // kPhysicsEvent = 7, // PHYSICS_EVENT // kCalibrationEvent = 8, // CALIBRATION_EVENT // kFormatError = 9, // EVENT_FORMAT_ERROR // kStartOfData = 10, // START_OF_DATA // kEndOfData = 11, // END_OF_DATA // kSystemSoftwareTriggerEvent = 12, // SYSTEM_SOFTWARE_TRIGGER_EVENT // kDetectorSoftwareTriggerEvent = 13 // DETECTOR_SOFTWARE_TRIGGER_EVENT Int_t eventType = 0; if(fInputEvent->GetHeader()) eventType = ((AliVHeader*)fInputEvent->GetHeader())->GetEventType(); AliDebug(3,Form("Event type %d",eventType)); // Select only Physics events in data, eventType = 7, // usually done by physics selection // MC not set, eventType =0, I think, so do not apply a value to fEventType by default // LED events have eventType = 8, implemented a selection cut in the past // but not really useful for EMCal data since LED are not reconstructed (unless wrongly assumed as physics) if ( fEventType >= 0 && eventType != fEventType ) return kFALSE ; AliDebug(1,"Pass event species selection"); fhNEventsAfterCut->Fill(2.5); //----------------------------------------------------------------- // In case of mixing analysis, select here the trigger of the event //----------------------------------------------------------------- UInt_t isTrigger = kFALSE; UInt_t isMB = kFALSE; if(!fEventTriggerAtSE) { // In case of mixing analysis, accept MB events, not only Trigger // Track and cluster arrays filled for MB in order to create the pool in the corresponding analysis // via de method in the base class FillMixedEventPool() AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler *inputHandler = dynamic_cast<AliInputEventHandler*>(manager->GetInputEventHandler()); if(!inputHandler) return kFALSE ; // to content coverity isTrigger = inputHandler->IsEventSelected() & fEventTriggerMask; isMB = inputHandler->IsEventSelected() & fMixEventTriggerMask; if(!isTrigger && !isMB) return kFALSE; //printf("Selected triggered event : %s\n",GetFiredTriggerClasses().Data()); AliDebug(0,"Pass uninteresting triggered events rejection in case of mixing analysis"); fhNEventsAfterCut->Fill(3.5); } //------------------------------------------------------------------------------------- // Reject or accept events depending on the trigger bit //------------------------------------------------------------------------------------- Bool_t okA = AcceptEventWithTriggerBit(); Bool_t okR = RejectEventWithTriggerBit(); //printf("AliCaloTrackReader::FillInputEvent() - Accept event? %d, Reject event %d? \n",okA,okR); if(!okA || !okR) return kFALSE; AliDebug(1,"Pass event bit rejection"); fhNEventsAfterCut->Fill(4.5); //---------------------------------------------------------------------- // Do not count events that were likely triggered by an exotic cluster // or out BC cluster //---------------------------------------------------------------------- // Set a bit with the event kind, MB, L0, L1 ... SetEventTriggerBit(); // In case of Mixing, avoid checking the triggers in the min bias events if(!fEventTriggerAtSE && (isMB && !isTrigger)) return kTRUE; if( (IsEventEMCALL1() || IsEventEMCALL0()) && fTriggerPatchClusterMatch) { if(fRejectEMCalTriggerEventsWith2Tresholds) { // Reject triggered events when there is coincidence on both EMCal trigger thresholds, // but the requested trigger is the low trigger threshold if(IsEventEMCALL1Jet1 () && IsEventEMCALL1Jet2 () && fFiredTriggerClassName.Contains("EJ2")) return kFALSE; if(IsEventEMCALL1Gamma1() && IsEventEMCALL1Gamma2() && fFiredTriggerClassName.Contains("EG2")) return kFALSE; } //Get Patches that triggered TArrayI patches = GetTriggerPatches(fTriggerPatchTimeWindow[0],fTriggerPatchTimeWindow[1]); MatchTriggerCluster(patches); patches.Reset(); // If requested, remove badly triggeed events, but only when the EMCal trigger bit is set if(fRemoveBadTriggerEvents) { AliDebug(1,Form("ACCEPT triggered event? \n exotic? %d - bad cell %d - bad Max cell %d - BC %d - Matched %d\n", fIsExoticEvent,fIsBadCellEvent, fIsBadMaxCellEvent, fTriggerClusterBC,fIsTriggerMatch)); if (fIsExoticEvent) return kFALSE; else if(fIsBadCellEvent) return kFALSE; else if(fRemoveUnMatchedTriggers && !fIsTriggerMatch) return kFALSE ; else if(fTriggerClusterBC != 0) return kFALSE; AliDebug(1,Form("\t *** YES for %s",GetFiredTriggerClasses().Data())); } AliDebug(1,"Pass EMCal triggered event rejection \n"); fhNEventsAfterCut->Fill(5.5); } //------------------------------------------------------------------------------------- // Select events only fired by a certain trigger configuration if it is provided //------------------------------------------------------------------------------------- if (GetFiredTriggerClasses().Contains("FAST") && !GetFiredTriggerClasses().Contains("ALL") && !fAcceptFastCluster) { AliDebug(1,Form("Do not count events from fast cluster, trigger name %s\n",fFiredTriggerClassName.Data())); return kFALSE; fhNEventsAfterCut->Fill(6.5); } //------------------------------------------------------------------------------------- // Reject event if large clusters with large energy // Use only for LHC11a data for the moment, and if input is clusterizer V1 or V1+unfolding // If clusterzer NxN or V2 it does not help //------------------------------------------------------------------------------------- //Int_t run = fInputEvent->GetRunNumber(); if ( fRemoveLEDEvents ) { Bool_t reject = RejectLEDEvents(); if(reject) return kFALSE; AliDebug(1,"Pass LED event rejection"); fhNEventsAfterCut->Fill(7.5); } // Remove LED events // All selection criteria passed, accept the event return kTRUE ; } //________________________________________________ /// Check the MC PYTHIA event, if the requested /// pT-hard is much smaller than the jet pT, then, /// there can be a problem in the tails of the /// distributions and the event should be rejected. //________________________________________________ Bool_t AliCaloTrackReader::ComparePtHardAndJetPt() { //printf("AliCaloTrackReader::ComparePtHardAndJetPt() - GenHeaderName : %s\n",GetGenEventHeader()->ClassName()); if(!strcmp(GetGenEventHeader()->ClassName(), "AliGenPythiaEventHeader")) { TParticle * jet = 0; AliGenPythiaEventHeader* pygeh= (AliGenPythiaEventHeader*) GetGenEventHeader(); Int_t nTriggerJets = pygeh->NTriggerJets(); Float_t ptHard = pygeh->GetPtHard(); AliDebug(1,Form("Njets: %d, pT Hard %f",nTriggerJets, ptHard)); Float_t tmpjet[]={0,0,0,0}; for(Int_t ijet = 0; ijet< nTriggerJets; ijet++) { pygeh->TriggerJet(ijet, tmpjet); jet = new TParticle(94, 21, -1, -1, -1, -1, tmpjet[0],tmpjet[1],tmpjet[2],tmpjet[3], 0,0,0,0); AliDebug(1,Form("jet %d; pycell jet pT %f",ijet, jet->Pt())); //Compare jet pT and pt Hard if(jet->Pt() > fPtHardAndJetPtFactor * ptHard) { AliInfo(Form("Reject jet event with : pT Hard %2.2f, pycell jet pT %2.2f, rejection factor %1.1f\n", ptHard, jet->Pt(), fPtHardAndJetPtFactor)); return kFALSE; } } if(jet) delete jet; } return kTRUE ; } //____________________________________________________ /// Check the MC PYTHIA event, if the requested /// pT-hard is smaller than the calorimeter cluster E, /// there can be a problem in the tails of the /// distributions and the event should be rejected. //____________________________________________________ Bool_t AliCaloTrackReader::ComparePtHardAndClusterPt() { if(!strcmp(GetGenEventHeader()->ClassName(), "AliGenPythiaEventHeader")) { AliGenPythiaEventHeader* pygeh= (AliGenPythiaEventHeader*) GetGenEventHeader(); Float_t ptHard = pygeh->GetPtHard(); Int_t nclusters = fInputEvent->GetNumberOfCaloClusters(); for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = fInputEvent->GetCaloCluster(iclus) ; Float_t ecluster = clus->E(); if(ecluster > fPtHardAndClusterPtFactor*ptHard) { AliInfo(Form("Reject : ecluster %2.2f, calo %d, factor %2.2f, ptHard %f",ecluster,clus->GetType(),fPtHardAndClusterPtFactor,ptHard)); return kFALSE; } } } return kTRUE ; } //___________________________________________________ /// Fill the output list of initialized control histograms. /// Cluster or track spectra histograms, depending on different selection cuts. //___________________________________________________ TList * AliCaloTrackReader::GetCreateControlHistograms() { fhNEventsAfterCut = new TH1I("hNEventsAfterCut", "Number of analyzed events", 19, 0, 19) ; //fhNEventsAfterCut->SetXTitle("Selection"); fhNEventsAfterCut->SetYTitle("# events"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(1 ,"1=Input"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(2 ,"2=Trigger string"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(3 ,"3=Event Type"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(4 ,"4=Mixing Event"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(5 ,"5=Trigger Bit"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(6 ,"6=Good EMC Trigger"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(7 ,"7=!Fast Cluster"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(8 ,"8=!LED"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(9 ,"9=Time stamp"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(10,"10=Z vertex"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(11,"11=Primary vertex"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(12,"12=Pile-up"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(13,"13=V0AND"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(14,"14=Centrality"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(15,"15=GenHeader"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(16,"16=PtHard-Jet"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(17,"17=PtHard-Cluster"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(18,"18=Track multi."); fhNEventsAfterCut->GetXaxis()->SetBinLabel(19,"19=TOF BC"); fOutputContainer->Add(fhNEventsAfterCut); if(fFillEMCAL) { for(Int_t i = 0; i < 8; i++) { TString names[] = {"NoCut", "Corrected", "GoodCluster", "NonLinearity", "EnergyAndFidutial","NCells", "BadDist","Time"}; fhEMCALClusterCutsE[i] = new TH1F(Form("hEMCALReaderClusterCuts_%d_%s",i,names[i].Data()), Form("EMCal %d, %s",i,names[i].Data()), fEnergyHistogramNbins, fEnergyHistogramLimit[0], fEnergyHistogramLimit[1]); fhEMCALClusterCutsE[i]->SetYTitle("# clusters"); fhEMCALClusterCutsE[i]->SetXTitle("#it{E} (GeV)"); fOutputContainer->Add(fhEMCALClusterCutsE[i]); } fhEMCALClusterTimeE = new TH2F ("hEMCALReaderTimeE","time vs #it{E} after cuts (if no calib, shifted -615 ns)", 100,0,100,400,-400,400); fhEMCALClusterTimeE->SetXTitle("#it{E} (GeV)"); fhEMCALClusterTimeE->SetYTitle("#it{time} (ns)"); fOutputContainer->Add(fhEMCALClusterTimeE); } if(fFillPHOS) { for(Int_t i = 0; i < 7; i++) { TString names[] = {"NoCut", "ExcludeCPV", "BorderCut", "FiducialCut", "EnergyCut", "NCells", "BadDist"}; fhPHOSClusterCutsE[i] = new TH1F(Form("hPHOSReaderClusterCuts_%d_%s",i,names[i].Data()), Form("PHOS Cut %d, %s",i,names[i].Data()), fEnergyHistogramNbins, fEnergyHistogramLimit[0], fEnergyHistogramLimit[1]) ; fhPHOSClusterCutsE[i]->SetYTitle("# clusters"); fhPHOSClusterCutsE[i]->SetXTitle("#it{E} (GeV)"); fOutputContainer->Add(fhPHOSClusterCutsE[i]); } } if(fFillCTS) { for(Int_t i = 0; i < 6; i++) { TString names[] = {"NoCut", "Status", "ESD_AOD", "TOF", "DCA","PtAcceptanceMult"}; fhCTSTrackCutsPt[i] = new TH1F(Form("hCTSReaderClusterCuts_%d_%s",i,names[i].Data()), Form("CTS Cut %d, %s",i,names[i].Data()), fEnergyHistogramNbins, fEnergyHistogramLimit[0], fEnergyHistogramLimit[1]) ; fhCTSTrackCutsPt[i]->SetYTitle("# tracks"); fhCTSTrackCutsPt[i]->SetXTitle("#it{p}_{T} (GeV)"); fOutputContainer->Add(fhCTSTrackCutsPt[i]); } } return fOutputContainer ; } //_____________________________________________________ /// Save parameters used for analysis in a string. //_____________________________________________________ TObjString * AliCaloTrackReader::GetListOfParameters() { TString parList ; //this will be list of parameters used for this analysis. const Int_t buffersize = 255; char onePar[buffersize] ; snprintf(onePar,buffersize,"--- Reader ---:") ; parList+=onePar ; snprintf(onePar,buffersize,"Data type: %d; zvertex cut %2.2f; EMC cluster name: <%s> ",fDataType, fZvtxCut, fEMCALClustersListName.Data()) ; parList+=onePar ; snprintf(onePar,buffersize,"Use detector: EMC %d, DCA %d, PHOS %d, CTS %d, EMCcells %d, PHOScells %d ; ", fFillEMCAL,fFillDCAL,fFillPHOS,fFillCTS,fFillEMCALCells,fFillPHOSCells) ; snprintf(onePar,buffersize,"E-pT window: EMC (%2.1f,%2.1f), PHOS (%2.1f,%2.1f), CTS (%2.1f,%2.1f); ", fEMCALPtMin,fEMCALPtMax,fPHOSPtMin,fPHOSPtMax,fCTSPtMin,fCTSPtMax) ; parList+=onePar ; snprintf(onePar,buffersize,"Dist to bad channel: EMC > %2.1f, PHOS > %2.1f; ",fEMCALBadChMinDist,fPHOSBadChMinDist) ; parList+=onePar ; snprintf(onePar,buffersize,"N cells: EMC > %d, PHOS > %d; ",fEMCALNCellsCut,fPHOSNCellsCut) ; parList+=onePar ; snprintf(onePar,buffersize,"EMC time cut single window (%2.2f,%2.2f); ",fEMCALTimeCutMin,fEMCALTimeCutMax) ; parList+=onePar ; snprintf(onePar,buffersize,"Check: calo fid cut %d; ",fCheckFidCut) ; parList+=onePar ; snprintf(onePar,buffersize,"Track: status %d, SPD hit %d; ",(Int_t) fTrackStatus, fSelectSPDHitTracks) ; parList+=onePar ; snprintf(onePar,buffersize,"multip. eta cut %1.1f; npt cuts %d;",fTrackMultEtaCut, fTrackMultNPtCut) ; parList+=onePar ; if(fUseTrackDCACut) { snprintf(onePar,buffersize,"DCA cut ON, param (%2.4f,%2.4f,%2.4f); ",fTrackDCACut[0],fTrackDCACut[1],fTrackDCACut[2]) ; parList+=onePar ; } snprintf(onePar,buffersize,"Recalculate Clusters = %d, E linearity = %d; ",fRecalculateClusters, fCorrectELinearity) ; parList+=onePar ; snprintf(onePar,buffersize,"SE trigger sel. %d, not? trigger Mask? %d, MB Trigger Mask for mixed %d; ", fEventTriggerAtSE, fEventTriggerMask,fMixEventTriggerMask); parList+=onePar ; snprintf(onePar,buffersize,"Select fired trigger %s; Remove Bad trigger event %d, unmatched %d; Accept fastcluster %d, Reject LED %d ", fFiredTriggerClassName.Data(), fRemoveBadTriggerEvents, fRemoveUnMatchedTriggers, fAcceptFastCluster, fRemoveLEDEvents); parList+=onePar ; if(fNMCGenerToAccept) { snprintf(onePar,buffersize,"Accept only labels from: "); parList+=onePar ; for(Int_t i = 0; i< fNMCGenerToAccept; i++) parList+=(fMCGenerToAccept[i]+" ") ; snprintf(onePar,buffersize,"; "); parList+=onePar ; } if(fSmearShowerShape) { snprintf(onePar,buffersize,"EMC M02 smear ON, function %d, param %2.4f, %d<=NLM<=%d; ", fSmearingFunction,fSmearShowerShapeWidth,fSmearNLMMin,fSmearNLMMax) ; parList+=onePar ; } if(fComparePtHardAndJetPt) { snprintf(onePar,buffersize,"jet pt / pt hard < %2.1f; ",fPtHardAndJetPtFactor); parList+=onePar ; } if(fComparePtHardAndClusterPt) { snprintf(onePar,buffersize,"cluster pt / pt hard < %2.2f",fPtHardAndClusterPtFactor); parList+=onePar ; } snprintf(onePar,buffersize,"Centrality: Class %s, Option %d, Bin [%d,%d]; New centrality %d; Event plane method %s; ", fCentralityClass.Data(),fCentralityOpt,fCentralityBin[0], fCentralityBin[1],fUseAliCentrality,fEventPlaneMethod.Data()) ; parList+=onePar ; return new TObjString(parList) ; } //______________________________________________ /// \return pointer to header (AliHeader) //______________________________________________ AliHeader* AliCaloTrackReader::GetHeader() const { if(fMC) { return fMC->Header(); } else { AliInfo("Header is not available"); return 0x0 ; } } //_________________________________________________________ /// \return list of particles in AOD, /// Implemented in AliCaloTrackAODReader. //_________________________________________________________ TClonesArray* AliCaloTrackReader::GetAODMCParticles() const { AliInfo("Input are not AODs"); return NULL ; } //________________________________________________________ /// \return MC header in AOD. /// Implemented in AliCaloTrackAODReader. //________________________________________________________ AliAODMCHeader* AliCaloTrackReader::GetAODMCHeader() const { AliInfo("Input are not AODs"); return NULL ; } //___________________________________________________________ /// \return vertex Bunch Cross Number. /// In old AODs BC not stored, recalculate it here, /// loop over the global track and select those which have /// small DCA to primary vertex (e.g. primary). /// If at least one of these primaries has valid BC != 0, then /// this vertex is a pile-up candidate. /// Execute after CTS filtering. //___________________________________________________________ Int_t AliCaloTrackReader::GetVertexBC(const AliVVertex * vtx) { Int_t vertexBC=vtx->GetBC(); if(!fRecalculateVertexBC) return vertexBC; // Value not available, recalculate it. Double_t bz = fInputEvent->GetMagneticField(); Bool_t bc0 = kFALSE; Int_t ntr = GetCTSTracks()->GetEntriesFast(); //printf("N Tracks %d\n",ntr); for(Int_t i = 0 ; i < ntr ; i++) { AliVTrack * track = (AliVTrack*) (GetCTSTracks()->At(i)); //Check if has TOF info, if not skip ULong_t status = track->GetStatus(); Bool_t okTOF = (status & AliVTrack::kTOFout) == AliVTrack::kTOFout ; vertexBC = track->GetTOFBunchCrossing(bz); Float_t pt = track->Pt(); if(!okTOF) continue; // Get DCA x, y Double_t dca[2] = {1e6,1e6}; Double_t covar[3] = {1e6,1e6,1e6}; track->PropagateToDCA(vtx,bz,100.,dca,covar); if(AcceptDCA(pt,dca[0])) { if (vertexBC !=0 && fVertexBC != AliVTrack::kTOFBCNA) return vertexBC; else if(vertexBC == 0) bc0 = kTRUE; } } if( bc0 ) vertexBC = 0 ; else vertexBC = AliVTrack::kTOFBCNA ; return vertexBC; } //_____________________________ /// /// Return track ID, different for ESD and AODs. /// See AliCaloTrackAODReader for AOD correspondent /// /// \return track ID /// \param track: pointer to track //_____________________________ Int_t AliCaloTrackReader::GetTrackID(AliVTrack* track) { return track->GetID(); } //_____________________________ /// Init the reader. /// Method to be called in AliAnaCaloTrackCorrMaker. //_____________________________ void AliCaloTrackReader::Init() { // Activate debug level in AliAnaWeights if( fWeightUtils->GetDebug() >= 0 ) (AliAnalysisManager::GetAnalysisManager())->AddClassDebug(fWeightUtils->ClassName(), fWeightUtils->GetDebug()); } //_______________________________________ /// Initialize the parameters with default. //_______________________________________ void AliCaloTrackReader::InitParameters() { fDataType = kESD ; fCTSPtMin = 0.1 ; fEMCALPtMin = 0.1 ; fPHOSPtMin = 0.1 ; fCTSPtMax = 1000. ; fEMCALPtMax = 1000. ; fPHOSPtMax = 1000. ; fEMCALBadChMinDist = 0; // open, 2; // standard fPHOSBadChMinDist = 0; // open, 2; // standard fEMCALNCellsCut = 0; // open, 1; // standard fPHOSNCellsCut = 0; // open, 2; // standard //Track DCA cuts // dca_xy cut = 0.0105+0.0350/TMath::Power(pt,1.1); fTrackDCACut[0] = 0.0105; fTrackDCACut[1] = 0.0350; fTrackDCACut[2] = 1.1; //Do not filter the detectors input by default. fFillEMCAL = kFALSE; fFillDCAL = kFALSE; fFillPHOS = kFALSE; fFillCTS = kFALSE; fFillEMCALCells = kFALSE; fFillPHOSCells = kFALSE; fDeltaAODFileName = "deltaAODPartCorr.root"; fFiredTriggerClassName = ""; fEventTriggerMask = AliVEvent::kAny; fMixEventTriggerMask = AliVEvent::kAnyINT; fEventTriggerAtSE = kTRUE; // Use only events that pass event selection at SE base class fAcceptFastCluster = kTRUE; fEventType = -1; //We want tracks fitted in the detectors: //fTrackStatus=AliESDtrack::kTPCrefit; //fTrackStatus|=AliESDtrack::kITSrefit; fTrackStatus = 0; fV0ADC[0] = 0; fV0ADC[1] = 0; fV0Mul[0] = 0; fV0Mul[1] = 0; fZvtxCut = 10.; fNMixedEvent = 1; fPtHardAndJetPtFactor = 7.; fPtHardAndClusterPtFactor = 1.; //Centrality fUseAliCentrality = kFALSE; fCentralityClass = "V0M"; fCentralityOpt = 100; fCentralityBin[0] = fCentralityBin[1]=-1; fEventPlaneMethod = "V0"; // Allocate memory (not sure this is the right place) fCTSTracks = new TObjArray(); fEMCALClusters = new TObjArray(); fDCALClusters = new TObjArray(); fPHOSClusters = new TObjArray(); //fTriggerAnalysis = new AliTriggerAnalysis; fAODBranchList = new TList ; fOutputContainer = new TList ; fEnergyHistogramNbins = 200; fEnergyHistogramLimit[0] = 0 ; fEnergyHistogramLimit[1] = 100; fPileUpParamSPD[0] = 3 ; fPileUpParamSPD[1] = 0.8 ; fPileUpParamSPD[2] = 3.0 ; fPileUpParamSPD[3] = 2.0 ; fPileUpParamSPD[4] = 5.0; // Parametrized time cut (LHC11d) fEMCALParamTimeCutMin[0] =-5; fEMCALParamTimeCutMin[1] =-1 ; fEMCALParamTimeCutMin[2] = 3.5 ; fEMCALParamTimeCutMin[3] = 1. ; fEMCALParamTimeCutMax[0] = 5; fEMCALParamTimeCutMax[1] = 50; fEMCALParamTimeCutMax[2] = 0.45; fEMCALParamTimeCutMax[3] = 1.25; // Parametrized time cut (LHC11c) //fEMCALParamTimeCutMin[0] =-5; fEMCALParamTimeCutMin[1] =-1 ; fEMCALParamTimeCutMin[2] = 1.87; fEMCALParamTimeCutMin[3] = 0.4; //fEMCALParamTimeCutMax[0] = 3.5; fEMCALParamTimeCutMax[1] = 50; fEMCALParamTimeCutMax[2] = 0.15; fEMCALParamTimeCutMax[3] = 1.6; fTimeStampRunMin = -1; fTimeStampRunMax = 1e12; fTimeStampEventFracMin = -1; fTimeStampEventFracMax = 2; for(Int_t i = 0; i < 19; i++) { fEMCalBCEvent [i] = 0; fEMCalBCEventCut[i] = 0; fTrackBCEvent [i] = 0; fTrackBCEventCut[i] = 0; } // Trigger match-rejection fTriggerPatchTimeWindow[0] = 8; fTriggerPatchTimeWindow[1] = 9; fTriggerClusterBC = -10000 ; fTriggerL0EventThreshold = -1; fTriggerL1EventThreshold = -1; fTriggerClusterIndex = -1; fTriggerClusterId = -1; //Jets fInputNonStandardJetBranchName = "jets"; fFillInputNonStandardJetBranch = kFALSE; if(!fNonStandardJets) fNonStandardJets = new TClonesArray("AliAODJet",100); fInputBackgroundJetBranchName = "jets"; fFillInputBackgroundJetBranch = kFALSE; if(!fBackgroundJets) fBackgroundJets = new AliAODJetEventBackground(); fSmearShowerShapeWidth = 0.005; fSmearNLMMin = 1; fSmearNLMMax = 1; fWeightUtils = new AliAnaWeights() ; fEventWeight = 1 ; fTrackMultNPtCut = 8; fTrackMultPtCut[0] = 0.15; fTrackMultPtCut[1] = 0.5; fTrackMultPtCut[2] = 1.0; fTrackMultPtCut[3] = 2.0 ; fTrackMultPtCut[4] = 4.0; fTrackMultPtCut[5] = 6.0; fTrackMultPtCut[6] = 8.0 ; fTrackMultPtCut[7] = 10.; fTrackMultPtCut[8] = 15.0; fTrackMultPtCut[9] = 20.; } //__________________________________________________________________________ /// Select the cluster depending on a time window, either a simple /// range or a parametrization depending on the energy. //__________________________________________________________________________ Bool_t AliCaloTrackReader::IsInTimeWindow(Double_t tof, Float_t energy) const { // Parametrized cut depending on E if(fUseParamTimeCut) { Float_t minCut= fEMCALParamTimeCutMin[0]+fEMCALParamTimeCutMin[1]*TMath::Exp(-(energy-fEMCALParamTimeCutMin[2])/fEMCALParamTimeCutMin[3]); Float_t maxCut= fEMCALParamTimeCutMax[0]+fEMCALParamTimeCutMax[1]*TMath::Exp(-(energy-fEMCALParamTimeCutMax[2])/fEMCALParamTimeCutMax[3]); //printf("tof %f, minCut %f, maxCut %f\n",tof,minCut,maxCut); if( tof < minCut || tof > maxCut ) return kFALSE ; } //In any case, the time should to be larger than the fixed window ... if( tof < fEMCALTimeCutMin || tof > fEMCALTimeCutMax ) return kFALSE ; return kTRUE ; } //________________________________________________ /// Check if event is from pile-up determined by SPD. /// Default values: (3, 0.8, 3., 2., 5.). //________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromSPD() const { return fInputEvent->IsPileupFromSPD((Int_t) fPileUpParamSPD[0] , fPileUpParamSPD[1] , fPileUpParamSPD[2] , fPileUpParamSPD[3] , fPileUpParamSPD[4] ); //printf("Param : %d, %2.2f, %2.2f, %2.2f, %2.2f\n",(Int_t) fPileUpParamSPD[0], fPileUpParamSPD[1], fPileUpParamSPD[2], fPileUpParamSPD[3], fPileUpParamSPD[4]); } //__________________________________________________ /// Check if event is from pile-up determined by EMCal //__________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromEMCal() const { if(fNPileUpClusters > fNPileUpClustersCut) return kTRUE ; else return kFALSE; } //________________________________________________________ /// Check if event is from pile-up determined by SPD and EMCal. //________________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromSPDAndEMCal() const { if( IsPileUpFromSPD() && IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //_______________________________________________________ /// Check if event is from pile-up determined by SPD or EMCal. //_______________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromSPDOrEMCal() const { if( IsPileUpFromSPD() || IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //___________________________________________________________ /// Check if event is from pile-up determined by SPD and not by EMCal. //___________________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromSPDAndNotEMCal() const { if( IsPileUpFromSPD() && !IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //___________________________________________________________ /// Check if event is from pile-up determined by EMCal, not by SPD. //___________________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromEMCalAndNotSPD() const { if( !IsPileUpFromSPD() && IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //______________________________________________________________ /// Check if event not from pile-up determined neither by SPD nor by EMCal. //______________________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromNotSPDAndNotEMCal() const { if( !IsPileUpFromSPD() && !IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //___________________________________________________________________________________ /// Event and tracks/clusters filtering method. Main steps: /// * Accept/reject the event looking to the triggers, vertex, pile-up, time stamps, /// PYTHIA pT hard, centrality etc. /// * Filter the tracks and calorimeter clusters, even correct the clusters if requested /// and put them in lists. /// /// Called by the analysis maker. //___________________________________________________________________________________ Bool_t AliCaloTrackReader::FillInputEvent(Int_t iEntry, const char * /*curFileName*/) { fEventNumber = iEntry; fTriggerClusterIndex = -1; fTriggerClusterId = -1; fIsTriggerMatch = kFALSE; fTriggerClusterBC = -10000; fIsExoticEvent = kFALSE; fIsBadCellEvent = kFALSE; fIsBadMaxCellEvent = kFALSE; fIsTriggerMatchOpenCut[0] = kFALSE ; fIsTriggerMatchOpenCut[1] = kFALSE ; fIsTriggerMatchOpenCut[2] = kFALSE ; //fCurrentFileName = TString(currentFileName); if(!fInputEvent) { AliInfo("Input event not available, skip event analysis"); return kFALSE; } fhNEventsAfterCut->Fill(0.5); //----------------------------------------------- // Select the event depending on the trigger type // and other event characteristics // like the goodness of the EMCal trigger //----------------------------------------------- Bool_t accept = CheckEventTriggers(); if(!accept) return kFALSE; AliDebug(1,"Pass Event trigger selection"); //------------------------------------------------------ // Event rejection depending on time stamp //------------------------------------------------------ if(fDataType==kESD && fTimeStampEventSelect) { AliESDEvent* esd = dynamic_cast<AliESDEvent*> (fInputEvent); if(esd) { Int_t timeStamp = esd->GetTimeStamp(); Float_t timeStampFrac = 1.*(timeStamp-fTimeStampRunMin) / (fTimeStampRunMax-fTimeStampRunMin); //printf("stamp0 %d, max0 %d, frac %f\n", timeStamp-fTimeStampRunMin,fTimeStampRunMax-fTimeStampRunMin, timeStampFrac); if(timeStampFrac < fTimeStampEventFracMin || timeStampFrac > fTimeStampEventFracMax) return kFALSE; } AliDebug(1,"Pass Time Stamp rejection"); fhNEventsAfterCut->Fill(8.5); } //------------------------------------------------------ // Event rejection depending on vertex, pileup, v0and //------------------------------------------------------ FillVertexArray(); //Reject events with Z vertex too large, only for SE analysis, if not, cut on the analysis code if(!GetMixedEvent() && TMath::Abs(fVertex[0][2]) > fZvtxCut) return kFALSE; fhNEventsAfterCut->Fill(9.5); if(fUseEventsWithPrimaryVertex) { if( !CheckForPrimaryVertex() ) return kFALSE; // algorithm in ESD/AOD Readers if( TMath::Abs(fVertex[0][0] ) < 1.e-6 && TMath::Abs(fVertex[0][1] ) < 1.e-6 && TMath::Abs(fVertex[0][2] ) < 1.e-6 ) return kFALSE; } AliDebug(1,"Pass primary vertex rejection"); fhNEventsAfterCut->Fill(10.5); //printf("Reader : IsPileUp %d, Multi %d\n",IsPileUpFromSPD(),fInputEvent->IsPileupFromSPDInMultBins()); if(fDoPileUpEventRejection) { // Do not analyze events with pileup Bool_t bPileup = IsPileUpFromSPD(); //IsPileupFromSPDInMultBins() // method to try //printf("pile-up %d, %d, %2.2f, %2.2f, %2.2f, %2.2f\n",bPileup, (Int_t) fPileUpParamSPD[0], fPileUpParamSPD[1], fPileUpParamSPD[2], fPileUpParamSPD[3], fPileUpParamSPD[4]); if(bPileup) return kFALSE; AliDebug(1,"Pass Pile-Up event rejection"); fhNEventsAfterCut->Fill(11.5); } if(fDoV0ANDEventSelection) { AliVVZERO* v0 = fInputEvent->GetVZEROData(); Bool_t bV0AND = ((v0->GetV0ADecision()==1) && (v0->GetV0CDecision()==1)); //bV0AND = fTriggerAnalysis->IsOfflineTriggerFired((AliESDEvent*)fInputEvent, AliTriggerAnalysis::kV0AND); //printf("V0AND event? %d\n",bV0AND); if(!bV0AND) { AliDebug(1,"Reject event by V0AND"); return kFALSE; } AliDebug(1,"Pass V0AND event rejection"); fhNEventsAfterCut->Fill(12.5); } //------------------------------------------------------ // Check if there is a centrality value, PbPb analysis, // and if a centrality bin selection is requested //------------------------------------------------------ //If we need a centrality bin, we select only those events in the corresponding bin. Int_t cen = -1; if ( fCentralityBin[0] >= 0 && fCentralityBin[1] >= 0 ) { cen = GetEventCentrality(); if(cen > fCentralityBin[1] || cen <= fCentralityBin[0]) return kFALSE; //reject events out of bin. AliDebug(1,"Pass centrality rejection"); fhNEventsAfterCut->Fill(13.5); } //---------------------------------------------------------------- // Reject the event if the event header name is not // the one requested among the possible generators. // Needed in case of cocktail MC generation with multiple options. //---------------------------------------------------------------- if(fMCGenerEventHeaderToAccept!="" && !GetGenEventHeader()) return kFALSE; fhNEventsAfterCut->Fill(14.5); //--------------------------------------------------------------------------- // In case of analysis of events with jets, skip those with jet pt > 5 pt hard // To be used on for MC data in pT hard bins //--------------------------------------------------------------------------- if(fComparePtHardAndJetPt) { if(!ComparePtHardAndJetPt()) return kFALSE ; AliDebug(1,"Pass Pt Hard - Jet rejection"); fhNEventsAfterCut->Fill(15.5); } if(fComparePtHardAndClusterPt) { if(!ComparePtHardAndClusterPt()) return kFALSE ; AliDebug(1,"Pass Pt Hard - Cluster rejection"); fhNEventsAfterCut->Fill(16.5); } //------------------------------------------------------------------ // Recover the weight assigned to the event, if provided // right now only for pT-hard bins and centrality depedent weights //------------------------------------------------------------------ if ( fWeightUtils->IsWeightSettingOn() ) { fWeightUtils->SetCentrality(cen); fWeightUtils->SetPythiaEventHeader(((AliGenPythiaEventHeader*)GetGenEventHeader())); fEventWeight = fWeightUtils->GetWeight(); } //------------------------------------------------------- // Get the main vertex BC, in case not available // it is calculated in FillCTS checking the BC of tracks //------------------------------------------------------ fVertexBC = fInputEvent->GetPrimaryVertex()->GetBC(); //----------------------------------------------- // Fill the arrays with cluster/tracks/cells data //----------------------------------------------- if(fFillCTS) { FillInputCTS(); //Accept events with at least one track if(fTrackMult[0] == 0 && fDoRejectNoTrackEvents) return kFALSE ; fhNEventsAfterCut->Fill(17.5); AliDebug(1,"Pass rejection of null track events"); } if(fDoVertexBCEventSelection) { if(fVertexBC != 0 && fVertexBC != AliVTrack::kTOFBCNA) return kFALSE ; AliDebug(1,"Pass rejection of events with vertex at BC!=0"); fhNEventsAfterCut->Fill(18.5); } if(fFillEMCALCells) FillInputEMCALCells(); if(fFillPHOSCells) FillInputPHOSCells(); if(fFillEMCAL || fFillDCAL) FillInputEMCAL(); if(fFillPHOS) FillInputPHOS(); FillInputVZERO(); //one specified jet branch if(fFillInputNonStandardJetBranch) FillInputNonStandardJets(); if(fFillInputBackgroundJetBranch) FillInputBackgroundJets(); AliDebug(1,"Event accepted for analysis"); return kTRUE ; } //__________________________________________________ /// \return Current event centrality bin. /// Different percentile options and centrality class can be requested. //__________________________________________________ Int_t AliCaloTrackReader::GetEventCentrality() const { if(fUseAliCentrality) { if ( !GetCentrality() ) return -1; AliDebug(1,Form("Cent. Percentile: V0M %2.2f, CL0 %2.2f, CL1 %2.2f; selected class %s", GetCentrality()->GetCentralityPercentile("V0M"), GetCentrality()->GetCentralityPercentile("CL0"), GetCentrality()->GetCentralityPercentile("CL1"), fCentralityClass.Data())); if (fCentralityOpt == 100) return (Int_t) GetCentrality()->GetCentralityPercentile(fCentralityClass); // 100 bins max else if(fCentralityOpt == 10) return GetCentrality()->GetCentralityClass10(fCentralityClass);// 10 bins max else if(fCentralityOpt == 20) return GetCentrality()->GetCentralityClass5(fCentralityClass); // 20 bins max else { AliInfo(Form("Unknown centrality option %d, use 10, 20 or 100\n",fCentralityOpt)); return -1; } } else { if ( !GetMultSelCen() ) return -1; AliDebug(1,Form("Mult. Percentile: V0M %2.2f, CL0 %2.2f, CL1 %2.2f; selected class %s", GetMultSelCen()->GetMultiplicityPercentile("V0M",1), GetMultSelCen()->GetMultiplicityPercentile("CL0",1), GetMultSelCen()->GetMultiplicityPercentile("CL1",1), fCentralityClass.Data())); return GetMultSelCen()->GetMultiplicityPercentile(fCentralityClass, kTRUE); // returns centrality only for events used in calibration // equivalent to //GetMultSelCen()->GetMultiplicityPercentile("V0M", kFALSE); // returns centrality for any event //Int_t qual = GetMultSelCen()->GetEvSelCode(); if (qual ! = 0) cent = qual; } } //_____________________________________________________ /// \return Current event plane angle. /// Different methods options can be requested. //_____________________________________________________ Double_t AliCaloTrackReader::GetEventPlaneAngle() const { if( !GetEventPlane() ) return -1000; Float_t ep = GetEventPlane()->GetEventplane(GetEventPlaneMethod(), GetInputEvent()); if(GetEventPlaneMethod()=="Q" && (ep < 0 || ep > TMath::Pi())) { AliDebug(1,Form("Bad EP for <Q> method : %f\n",ep)); return -1000; } else if(GetEventPlaneMethod().Contains("V0") ) { if((ep > TMath::Pi()/2 || ep < -TMath::Pi()/2)) { AliDebug(1,Form("Bad EP for <%s> method : %f\n",GetEventPlaneMethod().Data(), ep)); return -1000; } ep+=TMath::Pi()/2; // put same range as for <Q> method } AliDebug(3,Form("Event plane angle %f",ep)); // if(fDebug > 0 ) // { // if (ep > TMath::Pi()) printf("AliCaloTrackReader::GetEventPlaneAngle() - Too large angle = %f\n",ep); // else if(ep < 0 ) printf("AliCaloTrackReader::GetEventPlaneAngle() - Negative angle = %f\n" ,ep); // } return ep; } //__________________________________________________________ /// \return Vertex position to be used for single event analysis. //__________________________________________________________ void AliCaloTrackReader::GetVertex(Double_t vertex[3]) const { vertex[0] = fVertex[0][0]; vertex[1] = fVertex[0][1]; vertex[2] = fVertex[0][2]; } //__________________________________________________________________________ /// \return Vertex position for mixed event, recover the vertex in a particular event. //__________________________________________________________________________ void AliCaloTrackReader::GetVertex(Double_t vertex[3], Int_t evtIndex) const { vertex[0] = fVertex[evtIndex][0]; vertex[1] = fVertex[evtIndex][1]; vertex[2] = fVertex[evtIndex][2]; } //________________________________________ /// Fill data member fVertex. /// In case of Mixed event, multiple vertices. //________________________________________ void AliCaloTrackReader::FillVertexArray() { // Delete previous vertex if(fVertex) { for (Int_t i = 0; i < fNMixedEvent; i++) { delete [] fVertex[i] ; } delete [] fVertex ; } fVertex = new Double_t*[fNMixedEvent] ; for (Int_t i = 0; i < fNMixedEvent; i++) { fVertex[i] = new Double_t[3] ; fVertex[i][0] = 0.0 ; fVertex[i][1] = 0.0 ; fVertex[i][2] = 0.0 ; } if (!fMixedEvent) { // Single event analysis if(fDataType!=kMC) { if(fInputEvent->GetPrimaryVertex()) { fInputEvent->GetPrimaryVertex()->GetXYZ(fVertex[0]); } else { AliWarning("NULL primary vertex"); fVertex[0][0]=0.; fVertex[0][1]=0.; fVertex[0][2]=0.; }//Primary vertex pointer do not exist } else {// MC read event fVertex[0][0]=0.; fVertex[0][1]=0.; fVertex[0][2]=0.; } AliDebug(1,Form("Single Event Vertex : %f,%f,%f\n",fVertex[0][0],fVertex[0][1],fVertex[0][2])); } else { // MultiEvent analysis for (Int_t iev = 0; iev < fNMixedEvent; iev++) { if (fMixedEvent->GetVertexOfEvent(iev)) fMixedEvent->GetVertexOfEvent(iev)->GetXYZ(fVertex[iev]); else AliWarning("No vertex found"); AliDebug(1,Form("Multi Event %d Vertex : %f,%f,%f",iev,fVertex[iev][0],fVertex[iev][1],fVertex[iev][2])); } } } //_____________________________________ /// Fill the array with Central Tracking System (CTS) /// filtered tracks. To select the tracks, kinematic cuts, DCA, /// re-fit status and timing cuts are applied. /// Other more ESD/AOD dependent cuts are applied in *SelectTrack()* method, /// see AliCaloTrackAODReader and AliCaloTrackESDReader. //_____________________________________ void AliCaloTrackReader::FillInputCTS() { AliDebug(1,"Begin"); Double_t pTrack[3] = {0,0,0}; Int_t nTracks = fInputEvent->GetNumberOfTracks() ; Int_t nstatus = 0; Double_t bz = GetInputEvent()->GetMagneticField(); for(Int_t i = 0; i < 19; i++) { fTrackBCEvent [i] = 0; fTrackBCEventCut[i] = 0; } for(Int_t iptCut = 0; iptCut < fTrackMultNPtCut; iptCut++ ) { fTrackMult [iptCut] = 0; fTrackSumPt[iptCut] = 0; } Bool_t bc0 = kFALSE; if(fRecalculateVertexBC) fVertexBC = AliVTrack::kTOFBCNA; for (Int_t itrack = 0; itrack < nTracks; itrack++) {////////////// track loop AliVTrack * track = (AliVTrack*)fInputEvent->GetTrack(itrack) ; // retrieve track from esd if ( !AcceptParticleMCLabel( TMath::Abs(track->GetLabel()) ) ) continue ; fhCTSTrackCutsPt[0]->Fill(track->Pt()); //Select tracks under certain conditions, TPCrefit, ITSrefit ... check the set bits ULong_t status = track->GetStatus(); if (fTrackStatus && !((status & fTrackStatus) == fTrackStatus)) continue ; fhCTSTrackCutsPt[1]->Fill(track->Pt()); nstatus++; //------------------------- // Select the tracks depending on cuts of AOD or ESD if(!SelectTrack(track, pTrack)) continue ; fhCTSTrackCutsPt[2]->Fill(track->Pt()); //------------------------- // TOF cuts Bool_t okTOF = ( (status & AliVTrack::kTOFout) == AliVTrack::kTOFout ) ; Double_t tof = -1000; Int_t trackBC = -1000 ; if(fAccessTrackTOF) { if(okTOF) { trackBC = track->GetTOFBunchCrossing(bz); SetTrackEventBC(trackBC+9); tof = track->GetTOFsignal()*1e-3; //After selecting tracks with small DCA, pointing to vertex, set vertex BC depeding on tracks BC if(fRecalculateVertexBC) { if (trackBC != 0 && trackBC != AliVTrack::kTOFBCNA) fVertexBC = trackBC; else if(trackBC == 0) bc0 = kTRUE; } //In any case, the time should to be larger than the fixed window ... if( fUseTrackTimeCut && (trackBC !=0 || tof < fTrackTimeCutMin || tof > fTrackTimeCutMax) ) { //printf("Remove track time %f and bc = %d\n",tof,trackBC); continue ; } //else printf("Accept track time %f and bc = %d\n",tof,trackBC); } } fhCTSTrackCutsPt[3]->Fill(track->Pt()); //--------------------- // DCA cuts // fMomentum.SetPxPyPzE(pTrack[0],pTrack[1],pTrack[2],0); if(fUseTrackDCACut) { Float_t dcaTPC =-999; //In case of AODs, TPC tracks cannot be propagated back to primary vertex, if( fDataType == kAOD ) dcaTPC = ((AliAODTrack*) track)->DCA(); //normal way to get the dca, cut on dca_xy if(dcaTPC==-999) { Double_t dca[2] = {1e6,1e6}; Double_t covar[3] = {1e6,1e6,1e6}; Bool_t okDCA = track->PropagateToDCA(fInputEvent->GetPrimaryVertex(),bz,100.,dca,covar); if( okDCA) okDCA = AcceptDCA(fMomentum.Pt(),dca[0]); if(!okDCA) { //printf("AliCaloTrackReader::FillInputCTS() - Reject track pt %2.2f, dca_xy %2.4f\n",fMomentum.Pt(),dca[0]); continue ; } } }// DCA cuts fhCTSTrackCutsPt[4]->Fill(track->Pt()); //------------------------- // Kinematic/acceptance cuts // // Count the tracks in eta < 0.9 and different pT cuts Float_t ptTrack = fMomentum.Pt(); if(TMath::Abs(track->Eta())< fTrackMultEtaCut) { for(Int_t iptCut = 0; iptCut < fTrackMultNPtCut; iptCut++ ) { if(ptTrack > fTrackMultPtCut[iptCut]) { fTrackMult [iptCut]++; fTrackSumPt[iptCut]+=ptTrack; } } } if(fCTSPtMin > ptTrack || fCTSPtMax < ptTrack) continue ; // Check effect of cuts on track BC if(fAccessTrackTOF && okTOF) SetTrackEventBCcut(trackBC+9); if(fCheckFidCut && !fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kCTS)) continue; fhCTSTrackCutsPt[5]->Fill(track->Pt()); // ------------------------------ // Add selected tracks to array AliDebug(2,Form("Selected tracks pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); fCTSTracks->Add(track); // TODO, check if remove if (fMixedEvent) track->SetID(itrack); }// track loop if( fRecalculateVertexBC && (fVertexBC == 0 || fVertexBC == AliVTrack::kTOFBCNA)) { if( bc0 ) fVertexBC = 0 ; else fVertexBC = AliVTrack::kTOFBCNA ; } AliDebug(1,Form("CTS entries %d, input tracks %d, pass status %d, multipliticy %d", fCTSTracks->GetEntriesFast(), nTracks, nstatus, fTrackMult[0]));//fCTSTracksNormalInputEntries); } //_______________________________________________________________________________ /// Correct, if requested, and select here the EMCal cluster. /// If selected add it to the EMCal clusters array. /// The actions taken are: /// /// * If requested, recalibrate and recalculate most of the cluster parameters (careful not to be done if tender applied or other tasks executed after) /// * Select clusters without bad channels, exotic channels or close to borders /// * If requested, correct cluster non linearity (careful not to be done if tender applied or other tasks executed after) /// * Select clusters within an energy window and passing fiducial cuts /// * Select clusters within a time window /// * Select clusters with a minimum number of cells and not too close to a bad channel /// * Smear the shower shape, to be done only for MC /// * Besides, some counters on the number of clusters with time in different BC are stored /// /// \param clus: AliVCaloCluster pointer /// \param iclus: cluster index, only needed in case of mixing frame (not used recently) /// /// Method called by *FillInputEMCAL()* //_______________________________________________________________________________ void AliCaloTrackReader::FillInputEMCALAlgorithm(AliVCluster * clus, Int_t iclus) { // Accept clusters with the proper label, only applicable for MC if ( clus->GetLabel() >= 0 ) // -1 corresponds to noisy MC { if ( !AcceptParticleMCLabel(clus->GetLabel()) ) return ; } // TODO, not sure if needed anymore Int_t vindex = 0 ; if (fMixedEvent) vindex = fMixedEvent->EventIndexForCaloCluster(iclus); clus->GetMomentum(fMomentum, fVertex[vindex]); // No correction/cut applied yet fhEMCALClusterCutsE[0]->Fill(clus->E()); //if( (fDebug > 2 && fMomentum.E() > 0.1) || fDebug > 10 ) AliDebug(2,Form("Input cluster E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); //--------------------------- // Embedding case // TO BE REVISED if(fSelectEmbeddedClusters) { if(clus->GetNLabels()==0 || clus->GetLabel() < 0) return; //else printf("Embedded cluster, %d, n label %d label %d \n",iclus,clus->GetNLabels(),clus->GetLabel()); } //-------------------------------------- // Apply some corrections in the cluster // if(fRecalculateClusters) { //Recalibrate the cluster energy if(GetCaloUtils()->IsRecalibrationOn()) { Float_t energy = GetCaloUtils()->RecalibrateClusterEnergy(clus, GetEMCALCells()); clus->SetE(energy); //printf("Recalibrated Energy %f\n",clus->E()); GetCaloUtils()->RecalculateClusterShowerShapeParameters(GetEMCALCells(),clus); GetCaloUtils()->RecalculateClusterPID(clus); } // recalculate E //Recalculate distance to bad channels, if new list of bad channels provided GetCaloUtils()->RecalculateClusterDistanceToBadChannel(GetEMCALCells(),clus); //Recalculate cluster position if(GetCaloUtils()->IsRecalculationOfClusterPositionOn()) { GetCaloUtils()->RecalculateClusterPosition(GetEMCALCells(),clus); //clus->GetPosition(pos); //printf("After Corrections: e %f, x %f, y %f, z %f\n",clus->E(),pos[0],pos[1],pos[2]); } // Recalculate TOF if(GetCaloUtils()->GetEMCALRecoUtils()->IsTimeRecalibrationOn()) { Double_t tof = clus->GetTOF(); Float_t frac =-1; Int_t absIdMax = GetCaloUtils()->GetMaxEnergyCell(fEMCALCells, clus,frac); GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTime(absIdMax,fInputEvent->GetBunchCrossNumber(),tof); //additional L1 phase shift if(GetCaloUtils()->GetEMCALRecoUtils()->IsL1PhaseInTimeRecalibrationOn()) { GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTimeL1Phase(GetCaloUtils()->GetEMCALGeometry()->GetSuperModuleNumber(absIdMax), fInputEvent->GetBunchCrossNumber(), tof); } clus->SetTOF(tof); }// Time recalibration } // Check effect of corrections fhEMCALClusterCutsE[1]->Fill(clus->E()); //----------------------------------------------------------------- // Reject clusters with bad channels, close to borders and exotic // Bool_t goodCluster = GetCaloUtils()->GetEMCALRecoUtils()->IsGoodCluster(clus, GetCaloUtils()->GetEMCALGeometry(), GetEMCALCells(),fInputEvent->GetBunchCrossNumber()); if(!goodCluster) { //if( (fDebug > 2 && fMomentum.E() > 0.1) || fDebug > 10 ) AliDebug(1,Form("Bad cluster E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); return; } // Check effect of bad cluster removal fhEMCALClusterCutsE[2]->Fill(clus->E()); //Float_t pos[3]; //clus->GetPosition(pos); //printf("Before Corrections: e %f, x %f, y %f, z %f\n",clus->E(),pos[0],pos[1],pos[2]); //-------------------------------------- // Correct non linearity or smear energy // if(fCorrectELinearity && GetCaloUtils()->IsCorrectionOfClusterEnergyOn()) { GetCaloUtils()->CorrectClusterEnergy(clus) ; //if( (fDebug > 5 && fMomentum.E() > 0.1) || fDebug > 10 ) AliDebug(5,Form("Correct Non Lin: Old E %3.2f, New E %3.2f", fMomentum.E(),clus->E())); // In case of MC analysis, to match resolution/calibration in real data // Not needed anymore, just leave for MC studies on systematics if( GetCaloUtils()->GetEMCALRecoUtils()->IsClusterEnergySmeared() ) { Float_t rdmEnergy = GetCaloUtils()->GetEMCALRecoUtils()->SmearClusterEnergy(clus); //if( (fDebug > 5 && fMomentum.E() > 0.1) || fDebug > 10 ) AliDebug(5,Form("Smear energy: Old E %3.2f, New E %3.2f",clus->E(),rdmEnergy)); clus->SetE(rdmEnergy); } } clus->GetMomentum(fMomentum, fVertex[vindex]); // Check effect linearity correction, energy smearing fhEMCALClusterCutsE[3]->Fill(clus->E()); // Check the event BC depending on EMCal clustr before final cuts Double_t tof = clus->GetTOF()*1e9; Int_t bc = TMath::Nint(tof/50) + 9; //printf("tof %2.2f, bc+5=%d\n",tof,bc); SetEMCalEventBC(bc); //-------------------------------------- // Apply some kinematical/acceptance cuts // if(fEMCALPtMin > clus->E() || fEMCALPtMax < clus->E()) return ; // Select cluster fiducial region // Bool_t bEMCAL = kFALSE; Bool_t bDCAL = kFALSE; if(fCheckFidCut) { if(fFillEMCAL && fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kEMCAL)) bEMCAL = kTRUE ; if(fFillDCAL && fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kDCAL )) bDCAL = kTRUE ; } else { bEMCAL = kTRUE; } //--------------------------------------------------------------------- // Mask all cells in collumns facing ALICE thick material if requested // if(GetCaloUtils()->GetNMaskCellColumns()) { Int_t absId = -1; Int_t iSupMod = -1; Int_t iphi = -1; Int_t ieta = -1; Bool_t shared = kFALSE; GetCaloUtils()->GetEMCALRecoUtils()->GetMaxEnergyCell(GetCaloUtils()->GetEMCALGeometry(), GetEMCALCells(),clus,absId,iSupMod,ieta,iphi,shared); AliDebug(2,Form("Masked collumn: cluster E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); if(GetCaloUtils()->MaskFrameCluster(iSupMod, ieta)) return; } // Check effect of energy and fiducial cuts fhEMCALClusterCutsE[4]->Fill(clus->E()); //---------------------------------------------------- // Apply N cells cut // if(clus->GetNCells() <= fEMCALNCellsCut && fDataType != AliCaloTrackReader::kMC) return ; // Check effect of n cells cut fhEMCALClusterCutsE[5]->Fill(clus->E()); //---------------------------------------------------- // Apply distance to bad channel cut // Double_t distBad = clus->GetDistanceToBadChannel() ; //Distance to bad channel if(distBad < 0.) distBad=9999. ; //workout strange convension dist = -1. ; if(distBad < fEMCALBadChMinDist) return ; // Check effect distance to bad channel cut fhEMCALClusterCutsE[6]->Fill(clus->E()); //------------------------------------------ // Apply time cut, count EMCal BC before cut // SetEMCalEventBCcut(bc); // Shift time in case of no calibration with rough factor Double_t tofShift = tof; if(tof > 400) tofShift-=615; fhEMCALClusterTimeE->Fill(clus->E(),tofShift); if(!IsInTimeWindow(tof,clus->E())) { fNPileUpClusters++ ; if(fUseEMCALTimeCut) { AliDebug(2,Form("Out of time window E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f, time %e", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta(),tof)); return ; } } else fNNonPileUpClusters++; // Check effect of time cut fhEMCALClusterCutsE[7]->Fill(clus->E()); //---------------------------------------------------- // Smear the SS to try to match data and simulations, // do it only for simulations. // Int_t nMaxima = GetCaloUtils()->GetNumberOfLocalMaxima(clus, GetEMCALCells()); // Int_t nMaxima = clus->GetNExMax(); // For Run2 if( fSmearShowerShape && clus->GetNCells() > 2 && nMaxima >= fSmearNLMMin && nMaxima <= fSmearNLMMax ) { AliDebug(2,Form("Smear shower shape - Original: %2.4f\n", clus->GetM02())); if(fSmearingFunction == kSmearingLandau) { clus->SetM02( clus->GetM02() + fRandom.Landau(0, fSmearShowerShapeWidth) ); } else if(fSmearingFunction == kSmearingLandauShift) { if(iclus%3 == 0 && clus->GetM02() > 0.1) clus->SetM02( clus->GetM02() + fRandom.Landau(0.05, fSmearShowerShapeWidth) ); //fSmearShowerShapeWidth = 0.035 } else if (fSmearingFunction == kNoSmearing) { clus->SetM02( clus->GetM02() ); } //clus->SetM02( fRandom.Landau(clus->GetM02(), fSmearShowerShapeWidth) ); AliDebug(2,Form("Width %2.4f Smeared : %2.4f\n", fSmearShowerShapeWidth,clus->GetM02())); } //-------------------------------------------------------- // Fill the corresponding array with the selected clusters // Usually just filling EMCal array with upper or lower clusters is enough, // but maybe we want to do EMCal-DCal correlations. //if((fDebug > 2 && fMomentum.E() > 0.1) || fDebug > 10) AliDebug(2,Form("Selected clusters (EMCAL%d, DCAL%d), E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", bEMCAL,bDCAL,fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); if (bEMCAL) fEMCALClusters->Add(clus); else if(bDCAL ) fDCALClusters ->Add(clus); // TODO, not sure if needed anymore if (fMixedEvent) clus->SetID(iclus) ; } //_______________________________________ /// Fill the array with EMCAL clusters. /// Source of clusters can be different, /// external branch, output of some other /// analysis task or the standard. /// External branch is requested when providing /// its name in *fEMCALClustersListName*. //_______________________________________ void AliCaloTrackReader::FillInputEMCAL() { AliDebug(1,"Begin"); // First recalibrate cells, time or energy // if(GetCaloUtils()->IsRecalibrationOn()) // GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCells(GetCaloUtils()->GetEMCALGeometry(), // GetEMCALCells(), // fInputEvent->GetBunchCrossNumber()); fNPileUpClusters = 0; // Init counter fNNonPileUpClusters = 0; // Init counter for(Int_t i = 0; i < 19; i++) { fEMCalBCEvent [i] = 0; fEMCalBCEventCut[i] = 0; } //Loop to select clusters in fiducial cut and fill container with aodClusters if(fEMCALClustersListName=="") { Int_t nclusters = fInputEvent->GetNumberOfCaloClusters(); for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = 0; if ( (clus = fInputEvent->GetCaloCluster(iclus)) ) { if (clus->IsEMCAL()) { FillInputEMCALAlgorithm(clus, iclus); }//EMCAL cluster }// cluster exists }// cluster loop //Recalculate track matching GetCaloUtils()->RecalculateClusterTrackMatching(fInputEvent,0x0,fMC); }//Get the clusters from the input event else { TClonesArray * clusterList = 0x0; if (fInputEvent->FindListObject(fEMCALClustersListName)) { clusterList = dynamic_cast<TClonesArray*> (fInputEvent->FindListObject(fEMCALClustersListName)); } else if(fOutputEvent) { clusterList = dynamic_cast<TClonesArray*> (fOutputEvent->FindListObject(fEMCALClustersListName)); } if(!clusterList) { AliWarning(Form("Wrong name of list with clusters? <%s>",fEMCALClustersListName.Data())); return; } Int_t nclusters = clusterList->GetEntriesFast(); for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = dynamic_cast<AliVCluster*> (clusterList->At(iclus)); //printf("E %f\n",clus->E()); if (clus) FillInputEMCALAlgorithm(clus, iclus); else AliWarning("Null cluster in list!"); }// cluster loop // Recalculate the pile-up time, in case long time clusters removed during clusterization //printf("Input event INIT : Pile-up clusters %d, NO pile-up %d\n",fNPileUpClusters,fNNonPileUpClusters); fNPileUpClusters = 0; // Init counter fNNonPileUpClusters = 0; // Init counter for(Int_t i = 0; i < 19; i++) { fEMCalBCEvent [i] = 0; fEMCalBCEventCut[i] = 0; } for (Int_t iclus = 0; iclus < fInputEvent->GetNumberOfCaloClusters(); iclus++) { AliVCluster * clus = 0; if ( (clus = fInputEvent->GetCaloCluster(iclus)) ) { if (clus->IsEMCAL()) { Float_t frac =-1; Int_t absIdMax = GetCaloUtils()->GetMaxEnergyCell(fEMCALCells, clus,frac); Double_t tof = clus->GetTOF(); GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTime(absIdMax,fInputEvent->GetBunchCrossNumber(),tof); //additional L1 phase shift if(GetCaloUtils()->GetEMCALRecoUtils()->IsL1PhaseInTimeRecalibrationOn()) { GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTimeL1Phase(GetCaloUtils()->GetEMCALGeometry()->GetSuperModuleNumber(absIdMax), fInputEvent->GetBunchCrossNumber(), tof); } tof*=1e9; //printf("Input event cluster : AbsIdMax %d, E %2.2f, time %2.2f \n", absIdMax,clus->E(),tof); //Reject clusters with bad channels, close to borders and exotic; if(!GetCaloUtils()->GetEMCALRecoUtils()->IsGoodCluster(clus,GetCaloUtils()->GetEMCALGeometry(),GetEMCALCells(),fInputEvent->GetBunchCrossNumber())) continue; Int_t bc = TMath::Nint(tof/50) + 9; SetEMCalEventBC(bc); if(fEMCALPtMin > clus->E() || fEMCALPtMax < clus->E()) continue ; clus->GetMomentum(fMomentum, fVertex[0]); if(fCheckFidCut && !fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kEMCAL)) return ; SetEMCalEventBCcut(bc); if(!IsInTimeWindow(tof,clus->E())) fNPileUpClusters++ ; else fNNonPileUpClusters++; } } } //printf("Input event : Pile-up clusters %d, NO pile-up %d\n",fNPileUpClusters,fNNonPileUpClusters); // Recalculate track matching, not necessary if already done in the reclusterization task. // in case it was not done ... GetCaloUtils()->RecalculateClusterTrackMatching(fInputEvent,clusterList,fMC); } AliDebug(1,Form("EMCal selected clusters %d", fEMCALClusters->GetEntriesFast())); AliDebug(2,Form("\t n pile-up clusters %d, n non pile-up %d", fNPileUpClusters,fNNonPileUpClusters)); } //_______________________________________ /// Fill the array with PHOS filtered clusters. //_______________________________________ void AliCaloTrackReader::FillInputPHOS() { AliDebug(1,"Begin"); // Loop to select clusters in fiducial cut and fill container with aodClusters Int_t nclusters = fInputEvent->GetNumberOfCaloClusters(); TString genName; for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = fInputEvent->GetCaloCluster(iclus) ; if ( !clus ) continue ; if ( !clus->IsPHOS() ) continue ; if(clus->GetLabel() >=0 ) // -1 corresponds to noisy MC { if ( !AcceptParticleMCLabel(clus->GetLabel()) ) continue ; } fhPHOSClusterCutsE[0]->Fill(clus->E()); // Skip CPV input if( clus->GetType() == AliVCluster::kPHOSCharged ) continue ; fhPHOSClusterCutsE[1]->Fill(clus->E()); //--------------------------------------------- // Old feature, try to rely on PHOS tender // if(fRecalculateClusters) { // Recalibrate the cluster energy if(GetCaloUtils()->IsRecalibrationOn()) { Float_t energy = GetCaloUtils()->RecalibrateClusterEnergy(clus, (AliAODCaloCells*)GetPHOSCells()); clus->SetE(energy); } } //---------------------------------------------------------------------------------- // Check if the cluster contains any bad channel and if close to calorimeter borders // // Old feature, try to rely on PHOS tender if( GetCaloUtils()->ClusterContainsBadChannel(kPHOS,clus->GetCellsAbsId(), clus->GetNCells())) continue; if(!GetCaloUtils()->CheckCellFiducialRegion(clus, fInputEvent->GetPHOSCells())) continue; // TODO, add exotic cut??? fhPHOSClusterCutsE[2]->Fill(clus->E()); // TODO Dead code? remove? Int_t vindex = 0 ; if (fMixedEvent) vindex = fMixedEvent->EventIndexForCaloCluster(iclus); clus->GetMomentum(fMomentum, fVertex[vindex]); //---------------------------------------------------------------------------------- // Remove clusters close to borders // if (fCheckFidCut && !fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kPHOS) ) continue ; fhPHOSClusterCutsE[3]->Fill(clus->E()); //---------------------------------------------------------------------------------- // Remove clusters with too low energy // if (fPHOSPtMin > fMomentum.E() || fPHOSPtMax < fMomentum.E() ) continue ; fhPHOSClusterCutsE[4]->Fill(clus->E()); //---------------------------------------------------- // Apply N cells cut // if(clus->GetNCells() <= fPHOSNCellsCut && fDataType != AliCaloTrackReader::kMC) return ; // Check effect of n cells cut fhPHOSClusterCutsE[5]->Fill(clus->E()); //---------------------------------------------------- // Apply distance to bad channel cut // Double_t distBad = clus->GetDistanceToBadChannel() ; //Distance to bad channel if(distBad < 0.) distBad=9999. ; //workout strange convension dist = -1. ; if(distBad < fPHOSBadChMinDist) return ; // Check effect distance to bad channel cut fhPHOSClusterCutsE[6]->Fill(clus->E()); // TODO, add time cut //---------------------------------------------------------------------------------- // Add selected clusters to array // //if(fDebug > 2 && fMomentum.E() > 0.1) AliDebug(2,Form("Selected clusters E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); fPHOSClusters->Add(clus); // TODO Dead code? remove? if (fMixedEvent) clus->SetID(iclus) ; } // esd/aod cluster loop AliDebug(1,Form("PHOS selected clusters %d",fPHOSClusters->GetEntriesFast())) ; } //____________________________________________ /// Connects the array with EMCAL cells and the pointer. //____________________________________________ void AliCaloTrackReader::FillInputEMCALCells() { fEMCALCells = fInputEvent->GetEMCALCells(); } //___________________________________________ /// Connects the array with PHOS cells and the pointer. //___________________________________________ void AliCaloTrackReader::FillInputPHOSCells() { fPHOSCells = fInputEvent->GetPHOSCells(); } //_______________________________________ /// Fill VZERO information in data member, /// add all the channels information. //_______________________________________ void AliCaloTrackReader::FillInputVZERO() { AliVVZERO* v0 = fInputEvent->GetVZEROData(); //printf("Init V0: ADC (%d,%d), Multiplicity (%d,%d) \n",fV0ADC[0],fV0ADC[1],fV0Mul[0],fV0Mul[1]); if (v0) { AliESDVZERO* esdV0 = dynamic_cast<AliESDVZERO*> (v0); for (Int_t i = 0; i < 32; i++) { if(esdV0) {//Only available in ESDs fV0ADC[0] += (Int_t)esdV0->GetAdcV0C(i); fV0ADC[1] += (Int_t)esdV0->GetAdcV0A(i); } fV0Mul[0] += (Int_t)v0->GetMultiplicityV0C(i); fV0Mul[1] += (Int_t)v0->GetMultiplicityV0A(i); } AliDebug(1,Form("ADC (%d,%d), Multiplicity (%d,%d)",fV0ADC[0],fV0ADC[1],fV0Mul[0],fV0Mul[1])); } else { AliDebug(1,"Cannot retrieve V0 ESD! Run w/ null V0 charges"); } } //_________________________________________________ /// Fill array with non standard jets /// /// Author: Adam T. Matyja //_________________________________________________ void AliCaloTrackReader::FillInputNonStandardJets() { AliDebug(2,"Begin"); // //check if branch name is given if(!fInputNonStandardJetBranchName.Length()) { fInputEvent->Print(); AliFatal("No non-standard jet branch name specified. Specify among existing ones."); } fNonStandardJets = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(fInputNonStandardJetBranchName.Data())); if(!fNonStandardJets) { //check if jet branch exist; exit if not fInputEvent->Print(); AliFatal(Form("%s:%d no reconstructed jet array with name %s in AOD", (char*)__FILE__,__LINE__,fInputNonStandardJetBranchName.Data())); } else { AliDebug(1,Form("AOD input jets %d", fNonStandardJets->GetEntriesFast())); } } //_________________________________________________ /// Fill array with Background jets /// /// Author: Adam T. Matyja //_________________________________________________ void AliCaloTrackReader::FillInputBackgroundJets() { AliDebug(1,"Begin"); // //check if branch name is given if(!fInputBackgroundJetBranchName.Length()) { fInputEvent->Print(); AliFatal("No background jet branch name specified. Specify among existing ones."); } fBackgroundJets = (AliAODJetEventBackground*)(fInputEvent->FindListObject(fInputBackgroundJetBranchName.Data())); if(!fBackgroundJets) { //check if jet branch exist; exit if not fInputEvent->Print(); AliFatal(Form("%s:%d no reconstructed jet array with name %s in AOD", (char*)__FILE__,__LINE__,fInputBackgroundJetBranchName.Data())); } else { AliDebug(1,"FillInputBackgroundJets"); fBackgroundJets->Print(""); } } //____________________________________________________________________ /// Recover the patches that triggered, either L0 or L1. /// /// \param tmin: minimum L0 time bin cut /// \param tmax: maximum L0 time bin cut /// \return TArrayI, array with patches index //____________________________________________________________________ TArrayI AliCaloTrackReader::GetTriggerPatches(Int_t tmin, Int_t tmax ) { // init some variables Int_t trigtimes[30], globCol, globRow,ntimes, i; Int_t absId = -1; //[100]; Int_t nPatch = 0; TArrayI patches(0); // get object pointer AliVCaloTrigger *caloTrigger = GetInputEvent()->GetCaloTrigger( "EMCAL" ); if(!caloTrigger) { AliError("Trigger patches input (AliVCaloTrigger) not available in data!"); return patches; } //printf("CaloTrigger Entries %d\n",caloTrigger->GetEntries() ); // class is not empty if( caloTrigger->GetEntries() > 0 ) { // must reset before usage, or the class will fail caloTrigger->Reset(); // go throuth the trigger channels while( caloTrigger->Next() ) { // get position in global 2x2 tower coordinates caloTrigger->GetPosition( globCol, globRow ); //L0 if(IsEventEMCALL0()) { // get dimension of time arrays caloTrigger->GetNL0Times( ntimes ); // no L0s in this channel // presence of the channel in the iterator still does not guarantee that L0 was produced!! if( ntimes < 1 ) continue; // get timing array caloTrigger->GetL0Times( trigtimes ); //printf("Get L0 patch : n times %d - trigger time window %d - %d\n",ntimes, tmin,tmax); // go through the array for( i = 0; i < ntimes; i++ ) { // check if in cut - 8,9 shall be accepted in 2011 if( trigtimes[i] >= tmin && trigtimes[i] <= tmax ) { //printf("Accepted trigger time %d \n",trigtimes[i]); //if(nTrig > 99) continue; GetCaloUtils()->GetEMCALGeometry()->GetAbsFastORIndexFromPositionInEMCAL(globCol,globRow, absId); //printf("pass the time cut globCol %d, globRow %d absId %d\n",globCol,globRow, absId); patches.Set(nPatch+1); patches.AddAt(absId,nPatch++); } } // trigger time array }//L0 else if(IsEventEMCALL1()) // L1 { Int_t bit = 0; caloTrigger->GetTriggerBits(bit); Int_t sum = 0; caloTrigger->GetL1TimeSum(sum); //fBitEGA-=2; Bool_t isEGA1 = ((bit >> fBitEGA ) & 0x1) && IsEventEMCALL1Gamma1() ; Bool_t isEGA2 = ((bit >> (fBitEGA+1)) & 0x1) && IsEventEMCALL1Gamma2() ; Bool_t isEJE1 = ((bit >> fBitEJE ) & 0x1) && IsEventEMCALL1Jet1 () ; Bool_t isEJE2 = ((bit >> (fBitEJE+1)) & 0x1) && IsEventEMCALL1Jet2 () ; //if((bit>> fBitEGA )&0x1) printf("Trig Bit %d - bit %d - EG1 %d - EG2 %d\n",fBitEGA ,bit,IsEventEMCALL1Gamma1(),IsEventEMCALL1Gamma2()); //if((bit>>(fBitEGA+1))&0x1) printf("Trig Bit %d - bit %d - EG1 %d - EG2 %d\n",fBitEGA+1,bit,IsEventEMCALL1Gamma1(),IsEventEMCALL1Gamma2()); if(!isEGA1 && !isEJE1 && !isEGA2 && !isEJE2) continue; Int_t patchsize = -1; if (isEGA1 || isEGA2) patchsize = 2; else if (isEJE1 || isEJE2) patchsize = 16; //printf("**** Get L1 Patch: Bit %x, sum %d, patchsize %d, EGA1 %d, EGA2 %d, EJE1 %d, EJE2 %d, EGA bit %d, EJE bit %d, Trigger Gamma %d, Trigger Jet %d\n", // bit,sum,patchsize,isEGA1,isEGA2,isEJE1,isEJE2,fBitEGA,fBitEJE,IsEventEMCALL1Gamma(),IsEventEMCALL1Jet()); // add 2x2 (EGA) or 16x16 (EJE) patches for(Int_t irow=0; irow < patchsize; irow++) { for(Int_t icol=0; icol < patchsize; icol++) { GetCaloUtils()->GetEMCALGeometry()->GetAbsFastORIndexFromPositionInEMCAL(globCol+icol,globRow+irow, absId); //printf("pass the time cut globCol %d, globRow %d absId %d\n",globCol,globRow, absId); patches.Set(nPatch+1); patches.AddAt(absId,nPatch++); } } } // L1 } // trigger iterator } // go through triggers if(patches.GetSize()<=0) AliInfo(Form("No patch found! for triggers: %s and selected <%s>", GetFiredTriggerClasses().Data(),fFiredTriggerClassName.Data())); //else printf(">>>>> N patches %d, test %d,first %d, last %d\n",patches.GetSize(), nPatch, patches.At(0), patches.At(patches.GetSize()-1)); return patches; } //____________________________________________________________ /// Finds the cluster that triggered. /// It compares the cells of the trigger patches and /// high energy clusters. //____________________________________________________________ void AliCaloTrackReader::MatchTriggerCluster(TArrayI patches) { // Init info from previous event fTriggerClusterIndex = -1; fTriggerClusterId = -1; fTriggerClusterBC = -10000; fIsExoticEvent = kFALSE; fIsBadCellEvent = kFALSE; fIsBadMaxCellEvent = kFALSE; fIsTriggerMatch = kFALSE; fIsTriggerMatchOpenCut[0] = kFALSE; fIsTriggerMatchOpenCut[1] = kFALSE; fIsTriggerMatchOpenCut[2] = kFALSE; // Do only analysis for triggered events if(!IsEventEMCALL1() && !IsEventEMCALL0()) { fTriggerClusterBC = 0; return; } //printf("***** Try to match trigger to cluster %d **** L0 %d, L1 %d\n",fTriggerPatchClusterMatch,IsEventEMCALL0(),IsEventEMCALL1()); //Recover the list of clusters TClonesArray * clusterList = 0; if (fInputEvent->FindListObject(fEMCALClustersListName)) { clusterList = dynamic_cast<TClonesArray*> (fInputEvent->FindListObject(fEMCALClustersListName)); } else if(fOutputEvent) { clusterList = dynamic_cast<TClonesArray*> (fOutputEvent->FindListObject(fEMCALClustersListName)); } // Get number of clusters and of trigger patches Int_t nclusters = fInputEvent->GetNumberOfCaloClusters(); if(clusterList) nclusters = clusterList->GetEntriesFast(); Int_t nPatch = patches.GetSize(); Float_t exoDiffTime = GetCaloUtils()->GetEMCALRecoUtils()->GetExoticCellDiffTimeCut(); //Init some variables used in the cluster loop Float_t tofPatchMax = 100000; Float_t ePatchMax =-1; Float_t tofMax = 100000; Float_t eMax =-1; Int_t clusMax =-1; Int_t idclusMax =-1; Bool_t badClMax = kFALSE; Bool_t badCeMax = kFALSE; Bool_t exoMax = kFALSE; // Int_t absIdMaxTrig= -1; Int_t absIdMaxMax = -1; Int_t nOfHighECl = 0 ; // // Check what is the trigger threshold // set minimu energym of candidate for trigger cluster // SetEMCALTriggerThresholds(); Float_t triggerThreshold = fTriggerL1EventThreshold; if(IsEventEMCALL0()) triggerThreshold = fTriggerL0EventThreshold; Float_t minE = triggerThreshold / 2.; // This method is not really suitable for JET trigger // but in case, reduce the energy cut since we do not trigger on high energy particle if(IsEventEMCALL1Jet() || minE < 1) minE = 1; AliDebug(1,Form("IsL1Trigger %d, IsL1JetTrigger? %d, IsL0Trigger %d, L1 threshold %2.1f, L0 threshold %2.1f, Min cluster E %2.2f",IsEventEMCALL1Jet(), IsEventEMCALL1(), IsEventEMCALL0(), fTriggerL1EventThreshold,fTriggerL0EventThreshold,minE)); // // Loop on the clusters, check if there is any that falls into one of the patches // for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = 0; if(clusterList) clus = (AliVCluster*) clusterList->At(iclus); else clus = fInputEvent->GetCaloCluster(iclus); if ( !clus ) continue ; if ( !clus->IsEMCAL() ) continue ; //Skip clusters with too low energy to be triggering if ( clus->E() < minE ) continue ; Float_t frac = -1; Int_t absIdMax = GetCaloUtils()->GetMaxEnergyCell(fInputEvent->GetEMCALCells(), clus,frac); Bool_t badCluster = GetCaloUtils()->GetEMCALRecoUtils()->ClusterContainsBadChannel(GetCaloUtils()->GetEMCALGeometry(), clus->GetCellsAbsId(),clus->GetNCells()); UShort_t cellMax[] = {(UShort_t) absIdMax}; Bool_t badCell = GetCaloUtils()->GetEMCALRecoUtils()->ClusterContainsBadChannel(GetCaloUtils()->GetEMCALGeometry(),cellMax,1); // if cell is bad, it can happen that time calibration is not available, // when calculating if it is exotic, this can make it to be exotic by default // open it temporarily for this cluster if(badCell) GetCaloUtils()->GetEMCALRecoUtils()->SetExoticCellDiffTimeCut(10000000); Bool_t exotic = GetCaloUtils()->GetEMCALRecoUtils()->IsExoticCluster(clus, fInputEvent->GetEMCALCells()); // Set back the time cut on exotics if(badCell) GetCaloUtils()->GetEMCALRecoUtils()->SetExoticCellDiffTimeCut(exoDiffTime); // Energy threshold for exotic Ecross typically at 4 GeV, // for lower energy, check that there are more than 1 cell in the cluster if(!exotic && clus->GetNCells() < 2) exotic = kTRUE; Float_t energy = clus->E(); Int_t idclus = clus->GetID(); Double_t tof = clus->GetTOF(); if(GetCaloUtils()->GetEMCALRecoUtils()->IsTimeRecalibrationOn() && fTriggerClusterTimeRecal){ GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTime(absIdMax,fInputEvent->GetBunchCrossNumber(),tof); //additional L1 phase shift if(GetCaloUtils()->GetEMCALRecoUtils()->IsL1PhaseInTimeRecalibrationOn()){ GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTimeL1Phase(GetCaloUtils()->GetEMCALGeometry()->GetSuperModuleNumber(absIdMax), fInputEvent->GetBunchCrossNumber(), tof); } } tof *=1.e9; //printf("cluster %d, ID %d, E %2.2f, tof %2.2f, AbsId max %d, exotic %d, bad Cluster %d, bad Cell %d\n", // iclus,idclus, energy,tof,absIdMax, exotic, badCluster,badCell); // Find the highest energy cluster, avobe trigger threshold // in the event in case no match to trigger is found if( energy > eMax ) { tofMax = tof; eMax = energy; badClMax = badCluster; badCeMax = badCell; exoMax = exotic; clusMax = iclus; idclusMax = idclus; absIdMaxMax = absIdMax; } // count the good clusters in the event avobe the trigger threshold // to check the exotic events if(!badCluster && !exotic) nOfHighECl++; // Find match to trigger if(fTriggerPatchClusterMatch && nPatch>0) { for(Int_t iabsId =0; iabsId < nPatch; iabsId++) { Int_t absIDCell[4]; GetCaloUtils()->GetEMCALGeometry()->GetCellIndexFromFastORIndex(patches.At(iabsId), absIDCell); //if(tof > 75 ) printf("E %2.2f TOF %2.2f Trigger patch %d, cells : %d, %d, %d, %d\n", // clus->E(),tof,patches.At(iabsId), absIDCell[0],absIDCell[1],absIDCell[2],absIDCell[3]); for(Int_t ipatch = 0; ipatch < 4; ipatch++) { if(absIdMax == absIDCell[ipatch]) { //printf("*** Patches : absId %d, E %2.1f, tof %f \n",absIdMax,clus->E(), tof); if(energy > ePatchMax) { tofPatchMax = tof; ePatchMax = energy; fIsBadCellEvent = badCluster; fIsBadMaxCellEvent = badCell; fIsExoticEvent = exotic; fTriggerClusterIndex = iclus; fTriggerClusterId = idclus; fIsTriggerMatch = kTRUE; // absIdMaxTrig = absIdMax; } } }// cell patch loop }// trigger patch loop } // Do trigger patch matching }// Cluster loop // If there was no match, assign as trigger // the highest energy cluster in the event if(!fIsTriggerMatch) { tofPatchMax = tofMax; ePatchMax = eMax; fIsBadCellEvent = badClMax; fIsBadMaxCellEvent = badCeMax; fIsExoticEvent = exoMax; fTriggerClusterIndex = clusMax; fTriggerClusterId = idclusMax; } Double_t tofPatchMaxUS = TMath::Abs(tofPatchMax); if (tofPatchMaxUS < 28 ) fTriggerClusterBC = 0 ; else if(tofPatchMaxUS < 75 ) fTriggerClusterBC = 1 ; else if(tofPatchMaxUS < 125) fTriggerClusterBC = 2 ; else if(tofPatchMaxUS < 175) fTriggerClusterBC = 3 ; else if(tofPatchMaxUS < 225) fTriggerClusterBC = 4 ; else if(tofPatchMaxUS < 275) fTriggerClusterBC = 5 ; else { //printf("AliCaloTrackReader::MatchTriggerCluster() - Large BC - tof %2.3f - Index %d\n",tofPatchMaxUS,fTriggerClusterIndex); if(fTriggerClusterIndex >= 0) fTriggerClusterBC = 6 ; else { fTriggerClusterIndex = -2; fTriggerClusterId = -2; } } if(tofPatchMax < 0) fTriggerClusterBC*=-1; // printf("AliCaloTrackReader::MatchTriggerCluster(TArrayI patches) - Trigger cluster: index %d, ID %d, E = %2.2f, tof = %2.2f (BC = %d), bad cluster? %d, bad cell? %d, exotic? %d, patch match? %d, n High E cluster %d, absId Max %d\n", // fTriggerClusterIndex, fTriggerClusterId,ePatchMax, tofPatchMax, // fTriggerClusterBC, fIsBadCellEvent,fIsBadMaxCellEvent,fIsExoticEvent, fIsTriggerMatch, nOfHighECl,absIdMaxMax); // // if(!fIsTriggerMatch) printf("\t highest energy cluster: index %d, ID %d, E = %2.2f, tof = %2.2f, bad cluster? %d, bad cell? %d, exotic? %d\n", // clusMax, idclusMax, eMax,tofMax, badClMax, badCeMax,exoMax); //Redo matching but open cuts if(!fIsTriggerMatch && fTriggerClusterId >= 0) { // Open time patch time TArrayI patchOpen = GetTriggerPatches(7,10); Int_t patchAbsIdOpenTime = -1; for(Int_t iabsId =0; iabsId < patchOpen.GetSize(); iabsId++) { Int_t absIDCell[4]; patchAbsIdOpenTime = patchOpen.At(iabsId); GetCaloUtils()->GetEMCALGeometry()->GetCellIndexFromFastORIndex(patchAbsIdOpenTime, absIDCell); //if(tof > 75 ) printf("E %2.2f TOF %2.2f Trigger patch %d, cells : %d, %d, %d, %d\n", // clus->E(),tof,patches.At(iabsId), absIDCell[0],absIDCell[1],absIDCell[2],absIDCell[3]); for(Int_t ipatch = 0; ipatch < 4; ipatch++) { if(absIdMaxMax == absIDCell[ipatch]) { fIsTriggerMatchOpenCut[0] = kTRUE; break; } }// cell patch loop }// trigger patch loop // Check neighbour patches Int_t patchAbsId = -1; Int_t globalCol = -1; Int_t globalRow = -1; GetCaloUtils()->GetEMCALGeometry()->GetFastORIndexFromCellIndex(absIdMaxMax, patchAbsId); GetCaloUtils()->GetEMCALGeometry()->GetPositionInEMCALFromAbsFastORIndex(patchAbsId,globalCol,globalRow); // Check patches with strict time cut Int_t patchAbsIdNeigh = -1; for(Int_t icol = globalCol-1; icol <= globalCol+1; icol++) { if(icol < 0 || icol > 47) continue; for(Int_t irow = globalRow; irow <= globalRow+1; irow++) { if(irow < 0 || irow > 63) continue; GetCaloUtils()->GetEMCALGeometry()->GetAbsFastORIndexFromPositionInEMCAL(icol, irow, patchAbsIdNeigh); if ( patchAbsIdNeigh < 0 ) continue; for(Int_t iabsId =0; iabsId < patches.GetSize(); iabsId++) { if(patchAbsIdNeigh == patches.At(iabsId)) { fIsTriggerMatchOpenCut[1] = kTRUE; break; } }// trigger patch loop }// row }// col // Check patches with open time cut Int_t patchAbsIdNeighOpenTime = -1; for(Int_t icol = globalCol-1; icol <= globalCol+1; icol++) { if(icol < 0 || icol > 47) continue; for(Int_t irow = globalRow; irow <= globalRow+1; irow++) { if(irow < 0 || irow > 63) continue; GetCaloUtils()->GetEMCALGeometry()->GetAbsFastORIndexFromPositionInEMCAL(icol, irow, patchAbsIdNeighOpenTime); if ( patchAbsIdNeighOpenTime < 0 ) continue; for(Int_t iabsId =0; iabsId < patchOpen.GetSize(); iabsId++) { if(patchAbsIdNeighOpenTime == patchOpen.At(iabsId)) { fIsTriggerMatchOpenCut[2] = kTRUE; break; } }// trigger patch loop }// row }// col // printf("No match, new match: Open time %d-%d, open Neigh %d-%d, both open %d-%d\n",fIsTriggerMatchOpenCut[0],patchAbsIdOpenTime, // fIsTriggerMatchOpenCut[1],patchAbsIdNeigh, // fIsTriggerMatchOpenCut[2],patchAbsIdNeighOpenTime); patchOpen.Reset(); }// No trigger match found //printf("Trigger BC %d, Id %d, Index %d\n",fTriggerClusterBC,fTriggerClusterId,fTriggerClusterIndex); } //_________________________________________________________ /// Recover the EMCal L1 trigger threshold from data. /// Set the EMCal L0 threshold depending on the run number. /// Set the threshold only if requested. //_________________________________________________________ void AliCaloTrackReader::SetEMCALTriggerThresholds() { if(!fTriggerL1EventThresholdFix) { // get object pointer AliVCaloTrigger *caloTrigger = GetInputEvent()->GetCaloTrigger( "EMCAL" ); if ( fBitEGA == 6 ) { if (IsEventEMCALL1Gamma1()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(1); else if(IsEventEMCALL1Gamma2()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(3); else if(IsEventEMCALL1Jet1 ()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(0); else if(IsEventEMCALL1Jet2 ()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(2); // printf("L1 trigger Threshold Jet1 %f, Gamma1 %f, Jet2 %f, Gamma2 %f\n", // 0.07874*caloTrigger->GetL1Threshold(0), // 0.07874*caloTrigger->GetL1Threshold(1), // 0.07874*caloTrigger->GetL1Threshold(2), // 0.07874*caloTrigger->GetL1Threshold(3)); } else { // Old AOD data format, in such case, order of thresholds different!!! if (IsEventEMCALL1Gamma1()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(0); else if(IsEventEMCALL1Gamma2()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(2); else if(IsEventEMCALL1Jet1 ()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(1); else if(IsEventEMCALL1Jet2 ()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(3); // printf("L1 trigger Threshold Jet1 %f, Gamma1 %f, Jet2 %f, Gamma2 %f\n", // 0.07874*caloTrigger->GetL1Threshold(1), // 0.07874*caloTrigger->GetL1Threshold(0), // 0.07874*caloTrigger->GetL1Threshold(3), // 0.07874*caloTrigger->GetL1Threshold(2)); } } // Set L0 threshold, if not set by user if( IsEventEMCALL0() && fTriggerL0EventThreshold < 0) { // Revise for periods > LHC11d Int_t runNumber = fInputEvent->GetRunNumber(); if (runNumber < 146861) fTriggerL0EventThreshold = 3. ; // LHC11a else if(runNumber < 154000) fTriggerL0EventThreshold = 4. ; // LHC11b,c else if(runNumber < 165000) fTriggerL0EventThreshold = 5.5; // LHC11c,d,e else if(runNumber < 194000) fTriggerL0EventThreshold = 2 ; // LHC12 else if(runNumber < 197400) fTriggerL0EventThreshold = 3 ; // LHC13def else if(runNumber < 197400) fTriggerL0EventThreshold = 2 ; // LHC13g else if(runNumber < 244300) fTriggerL0EventThreshold = 5 ; // LHC15 in, phys 1, 5 in phys2 else if(runNumber < 266400) fTriggerL0EventThreshold = 2.5; // LHC16ir else fTriggerL0EventThreshold = 3.5; // LHC16s } } //________________________________________________________ /// Print some relevant parameters set for the analysis //________________________________________________________ void AliCaloTrackReader::Print(const Option_t * opt) const { if(! opt) return; printf("***** Print: %s %s ******\n", GetName(), GetTitle() ) ; printf("Task name : %s\n", fTaskName.Data()) ; printf("Data type : %d\n", fDataType) ; printf("CTS Min pT : %2.1f GeV/c\n", fCTSPtMin) ; printf("EMCAL Min pT : %2.1f GeV/c\n", fEMCALPtMin) ; printf("PHOS Min pT : %2.1f GeV/c\n", fPHOSPtMin) ; printf("CTS Max pT : %2.1f GeV/c\n", fCTSPtMax) ; printf("EMCAL Max pT : %2.1f GeV/c\n", fEMCALPtMax) ; printf("PHOS Max pT : %2.1f GeV/c\n", fPHOSPtMax) ; printf("EMCAL Bad Dist > %2.1f \n" , fEMCALBadChMinDist) ; printf("PHOS Bad Dist > %2.1f \n" , fPHOSBadChMinDist) ; printf("EMCAL N cells > %d \n" , fEMCALNCellsCut) ; printf("PHOS N cells > %d \n" , fPHOSNCellsCut) ; printf("EMCAL Time Cut: %3.1f < TOF < %3.1f\n", fEMCALTimeCutMin, fEMCALTimeCutMax); printf("Use CTS = %d\n", fFillCTS) ; printf("Use EMCAL = %d\n", fFillEMCAL) ; printf("Use DCAL = %d\n", fFillDCAL) ; printf("Use PHOS = %d\n", fFillPHOS) ; printf("Use EMCAL Cells = %d\n", fFillEMCALCells) ; printf("Use PHOS Cells = %d\n", fFillPHOSCells) ; printf("Track status = %d\n", (Int_t) fTrackStatus) ; printf("Track Mult Eta Cut = %2.2f\n", fTrackMultEtaCut) ; printf("Track Mult Pt Cuts:") ; for(Int_t icut = 0; icut < fTrackMultNPtCut; icut++) printf(" %2.2f GeV;",fTrackMultPtCut[icut]); printf(" \n") ; printf("Write delta AOD = %d\n", fWriteOutputDeltaAOD) ; printf("Recalculate Clusters = %d, E linearity = %d\n", fRecalculateClusters, fCorrectELinearity) ; printf("Use Triggers selected in SE base class %d; If not what Trigger Mask? %d; MB Trigger Mask for mixed %d \n", fEventTriggerAtSE, fEventTriggerMask,fMixEventTriggerMask); if(fComparePtHardAndJetPt) printf("Compare jet pt and pt hard to accept event, factor = %2.2f",fPtHardAndJetPtFactor); if(fComparePtHardAndClusterPt) printf("Compare cluster pt and pt hard to accept event, factor = %2.2f",fPtHardAndClusterPtFactor); printf("Delta AOD File Name = %s\n", fDeltaAODFileName.Data()) ; printf("Centrality: Class %s, Option %d, Bin [%d,%d] \n", fCentralityClass.Data(),fCentralityOpt,fCentralityBin[0], fCentralityBin[1]) ; printf(" \n") ; } //__________________________________________ /// LED Events in period LHC11a contaminated /// EMCAL clusters sample, simple method /// to reject such events. //__________________________________________ Bool_t AliCaloTrackReader::RejectLEDEvents() { // Count number of cells with energy larger than 0.1 in SM3, cut on this number Int_t ncellsSM3 = 0; for(Int_t icell = 0; icell < fInputEvent->GetEMCALCells()->GetNumberOfCells(); icell++) { Int_t absID = fInputEvent->GetEMCALCells()->GetCellNumber(icell); Int_t sm = GetCaloUtils()->GetEMCALGeometry()->GetSuperModuleNumber(absID); if(fInputEvent->GetEMCALCells()->GetAmplitude(icell) > 0.1 && sm==3) ncellsSM3++; } Int_t ncellcut = 21; if(GetFiredTriggerClasses().Contains("EMC")) ncellcut = 35; if(ncellsSM3 >= ncellcut) { AliDebug(1,Form("Reject event with ncells in SM3 %d, cut %d, trig %s", ncellsSM3,ncellcut,GetFiredTriggerClasses().Data())); return kTRUE; } return kFALSE; } //_________________________________________________________ /// MC label for Cells not remapped after ESD filtering, do it here. /// Needed for old MC/data productions done with AliRoot older /// than v5-02-Rev09 (more or less, not sure) //_________________________________________________________ void AliCaloTrackReader::RemapMCLabelForAODs(Int_t & label) { if(label < 0) return ; AliAODEvent * evt = dynamic_cast<AliAODEvent*> (fInputEvent) ; if(!evt) return ; TClonesArray * arr = dynamic_cast<TClonesArray*>(evt->FindListObject("mcparticles")) ; if(!arr) return ; if(label < arr->GetEntriesFast()) { AliAODMCParticle * particle = dynamic_cast<AliAODMCParticle *>(arr->At(label)); if(!particle) return ; if(label == particle->Label()) return ; // label already OK //else printf("AliCaloTrackReader::RemapMCLabelForAODs() - Label %d - AOD stack %d \n",label, particle->Label()); } //else printf("AliCaloTrackReader::RemapMCLabelForAODs() - Label %d > AOD labels %d \n",label, arr->GetEntriesFast()); // loop on the particles list and check if there is one with the same label for(Int_t ind = 0; ind < arr->GetEntriesFast(); ind++ ) { AliAODMCParticle * particle = dynamic_cast<AliAODMCParticle *>(arr->At(ind)); if(!particle) continue ; if(label == particle->Label()) { label = ind; //printf("AliAnalysisTaskEMCALClusterize::RemapMCLabelForAODs() - New Label Index %d \n",label); return; } } label = -1; //printf("AliCaloTrackReader::RemapMCLabelForAODs() - Label not found set to -1 \n"); } //___________________________________ /// Reset lists, called in AliAnaCaloTrackCorrMaker. //___________________________________ void AliCaloTrackReader::ResetLists() { if(fCTSTracks) fCTSTracks -> Clear(); if(fEMCALClusters) fEMCALClusters -> Clear("C"); if(fPHOSClusters) fPHOSClusters -> Clear("C"); fV0ADC[0] = 0; fV0ADC[1] = 0; fV0Mul[0] = 0; fV0Mul[1] = 0; if(fNonStandardJets) fNonStandardJets -> Clear("C"); fBackgroundJets->Reset(); } //___________________________________________ /// Tag event depending on trigger name. /// Set also the L1 bit defining the EGA or EJE triggers. /// depending on the trigger class version, if not set by user. //___________________________________________ void AliCaloTrackReader::SetEventTriggerBit() { fEventTrigMinBias = kFALSE; fEventTrigCentral = kFALSE; fEventTrigSemiCentral = kFALSE; fEventTrigEMCALL0 = kFALSE; fEventTrigEMCALL1Gamma1 = kFALSE; fEventTrigEMCALL1Gamma2 = kFALSE; fEventTrigEMCALL1Jet1 = kFALSE; fEventTrigEMCALL1Jet2 = kFALSE; AliDebug(1,Form("Select trigger mask bit %d - Trigger Event %s - Select <%s>", fEventTriggerMask,GetFiredTriggerClasses().Data(),fFiredTriggerClassName.Data())); if(fEventTriggerMask <=0 )// in case no mask set { // EMC triggered event? Which type? if( GetFiredTriggerClasses().Contains("-B-") || GetFiredTriggerClasses().Contains("-S-") || GetFiredTriggerClasses().Contains("-I-") ) { if ( GetFiredTriggerClasses().Contains("EGA" ) || GetFiredTriggerClasses().Contains("EG1" ) ) { fEventTrigEMCALL1Gamma1 = kTRUE; if( GetFiredTriggerClasses().Contains("EG1" ) && !fFiredTriggerClassName.Contains("EG1") ) fEventTrigEMCALL1Gamma1 = kFALSE; } else if( GetFiredTriggerClasses().Contains("EG2" ) ) { fEventTrigEMCALL1Gamma2 = kTRUE; if( !fFiredTriggerClassName.Contains("EG2") ) fEventTrigEMCALL1Gamma2 = kFALSE; } else if( GetFiredTriggerClasses().Contains("EJE" ) || GetFiredTriggerClasses().Contains("EJ1" ) ) { fEventTrigEMCALL1Jet1 = kTRUE; if( GetFiredTriggerClasses().Contains("EJ1" ) && !fFiredTriggerClassName.Contains("EJ1") ) fEventTrigEMCALL1Jet1 = kFALSE; } else if( GetFiredTriggerClasses().Contains("EJ2" ) ) { fEventTrigEMCALL1Jet2 = kTRUE; if( !fFiredTriggerClassName.Contains("EJ2") ) fEventTrigEMCALL1Jet2 = kFALSE; } else if( GetFiredTriggerClasses().Contains("CEMC") && !GetFiredTriggerClasses().Contains("EGA" ) && !GetFiredTriggerClasses().Contains("EJE" ) && !GetFiredTriggerClasses().Contains("EG1" ) && !GetFiredTriggerClasses().Contains("EJ1" ) && !GetFiredTriggerClasses().Contains("EG2" ) && !GetFiredTriggerClasses().Contains("EJ2" ) ) { fEventTrigEMCALL0 = kTRUE; } //Min bias event trigger? if (GetFiredTriggerClasses().Contains("CCENT_R2-B-NOPF-ALLNOTRD")) { fEventTrigCentral = kTRUE; } else if(GetFiredTriggerClasses().Contains("CSEMI_R1-B-NOPF-ALLNOTRD")) { fEventTrigSemiCentral = kTRUE; } else if((GetFiredTriggerClasses().Contains("CINT") || GetFiredTriggerClasses().Contains("CPBI2_B1") ) && GetFiredTriggerClasses().Contains("-NOPF-ALLNOTRD") ) { fEventTrigMinBias = kTRUE; } } } else { // EMC L1 Gamma if ( fEventTriggerMask & AliVEvent::kEMCEGA ) { //printf("EGA trigger bit\n"); if (GetFiredTriggerClasses().Contains("EG")) { if (GetFiredTriggerClasses().Contains("EGA")) fEventTrigEMCALL1Gamma1 = kTRUE; else { if(GetFiredTriggerClasses().Contains("EG1")) fEventTrigEMCALL1Gamma1 = kTRUE; if(GetFiredTriggerClasses().Contains("EG2")) fEventTrigEMCALL1Gamma2 = kTRUE; } } } // EMC L1 Jet else if( fEventTriggerMask & AliVEvent::kEMCEJE ) { //printf("EGA trigger bit\n"); if (GetFiredTriggerClasses().Contains("EJ")) { if (GetFiredTriggerClasses().Contains("EJE")) fEventTrigEMCALL1Jet1 = kTRUE; else { if(GetFiredTriggerClasses().Contains("EJ1")) fEventTrigEMCALL1Jet1 = kTRUE; if(GetFiredTriggerClasses().Contains("EJ2")) fEventTrigEMCALL1Jet2 = kTRUE; } } } // EMC L0 else if((fEventTriggerMask & AliVEvent::kEMC7) || (fEventTriggerMask & AliVEvent::kEMC1) ) { //printf("L0 trigger bit\n"); fEventTrigEMCALL0 = kTRUE; } // Min Bias Pb-Pb else if( fEventTriggerMask & AliVEvent::kCentral ) { //printf("MB semi central trigger bit\n"); fEventTrigSemiCentral = kTRUE; } // Min Bias Pb-Pb else if( fEventTriggerMask & AliVEvent::kSemiCentral ) { //printf("MB central trigger bit\n"); fEventTrigCentral = kTRUE; } // Min Bias pp, PbPb, pPb else if((fEventTriggerMask & AliVEvent::kMB ) || (fEventTriggerMask & AliVEvent::kINT7) || (fEventTriggerMask & AliVEvent::kINT8) || (fEventTriggerMask & AliVEvent::kAnyINT) ) { //printf("MB trigger bit\n"); fEventTrigMinBias = kTRUE; } } AliDebug(1,Form("Event bits: \n \t MB %d, Cen %d, Sem %d, L0 %d, L1G1 %d, L1G2 %d, L1J1 %d, L1J2 %d", fEventTrigMinBias, fEventTrigCentral, fEventTrigSemiCentral, fEventTrigEMCALL0 , fEventTrigEMCALL1Gamma1, fEventTrigEMCALL1Gamma2, fEventTrigEMCALL1Jet1 , fEventTrigEMCALL1Jet2)); // L1 trigger bit if( fBitEGA == 0 && fBitEJE == 0 ) { // Init the trigger bit once, correct depending on AliESD(AOD)CaloTrigger header version // Simpler way to do it ... // if( fInputEvent->GetRunNumber() < 172000 ) // reader->SetEventTriggerL1Bit(4,5); // current LHC11 data // else // reader->SetEventTriggerL1Bit(6,8); // LHC12-13 data // Old values fBitEGA = 4; fBitEJE = 5; TFile* file = AliAnalysisManager::GetAnalysisManager()->GetTree()->GetCurrentFile(); const TList *clist = file->GetStreamerInfoCache(); if(clist) { TStreamerInfo *cinfo = (TStreamerInfo*)clist->FindObject("AliESDCaloTrigger"); Int_t verid = 5; // newer ESD header version if(!cinfo) { cinfo = (TStreamerInfo*)clist->FindObject("AliAODCaloTrigger"); verid = 3; // newer AOD header version } if(cinfo) { Int_t classversionid = cinfo->GetClassVersion(); //printf("********* Header class version %d *********** \n",classversionid); if (classversionid >= verid) { fBitEGA = 6; fBitEJE = 8; } } else AliInfo("AliCaloTrackReader()::SetEventTriggerBit() - Streamer info for trigger class not available, bit not changed"); } else AliInfo("AliCaloTrackReader::SetEventTriggerBit() - Streamer list not available!, bit not changed"); } // set once the EJE, EGA trigger bit } //____________________________________________________________ /// Define here the input event and mixed event. /// Called in AliAnaCaloTrackCorrMaker. //____________________________________________________________ void AliCaloTrackReader::SetInputEvent(AliVEvent* const input) { fInputEvent = input; fMixedEvent = dynamic_cast<AliMixedEvent*>(GetInputEvent()) ; if (fMixedEvent) fNMixedEvent = fMixedEvent->GetNumberOfEvents() ; //Delete previous vertex if(fVertex) { for (Int_t i = 0; i < fNMixedEvent; i++) { delete [] fVertex[i] ; } delete [] fVertex ; } fVertex = new Double_t*[fNMixedEvent] ; for (Int_t i = 0; i < fNMixedEvent; i++) { fVertex[i] = new Double_t[3] ; fVertex[i][0] = 0.0 ; fVertex[i][1] = 0.0 ; fVertex[i][2] = 0.0 ; } } move vz cut after primary vertex cut, split primary vertex cut counter and null vertex counter, plus cosmetics /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // --- ROOT system --- #include <TFile.h> #include <TGeoManager.h> #include <TStreamerInfo.h> // ---- ANALYSIS system ---- #include "AliMCEvent.h" #include "AliAODMCHeader.h" #include "AliGenPythiaEventHeader.h" #include "AliGenEventHeader.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliVTrack.h" #include "AliVParticle.h" #include "AliMixedEvent.h" //#include "AliTriggerAnalysis.h" #include "AliESDVZERO.h" #include "AliVCaloCells.h" #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" #include "AliAODMCParticle.h" #include "AliMultSelection.h" // ---- Detectors ---- #include "AliPHOSGeoUtils.h" #include "AliEMCALGeometry.h" #include "AliEMCALRecoUtils.h" // ---- CaloTrackCorr --- #include "AliCalorimeterUtils.h" #include "AliCaloTrackReader.h" // ---- Jets ---- #include "AliAODJet.h" #include "AliAODJetEventBackground.h" /// \cond CLASSIMP ClassImp(AliCaloTrackReader) ; /// \endcond //________________________________________ /// Constructor. Initialize parameters. //________________________________________ AliCaloTrackReader::AliCaloTrackReader() : TObject(), fEventNumber(-1), //fCurrentFileName(""), fDataType(0), fDebug(0), fFiducialCut(0x0), fCheckFidCut(kFALSE), fComparePtHardAndJetPt(0), fPtHardAndJetPtFactor(0), fComparePtHardAndClusterPt(0),fPtHardAndClusterPtFactor(0), fCTSPtMin(0), fEMCALPtMin(0), fPHOSPtMin(0), fCTSPtMax(0), fEMCALPtMax(0), fPHOSPtMax(0), fEMCALBadChMinDist(0), fPHOSBadChMinDist (0), fEMCALNCellsCut(0), fPHOSNCellsCut(0), fUseEMCALTimeCut(1), fUseParamTimeCut(0), fUseTrackTimeCut(0), fAccessTrackTOF(0), fEMCALTimeCutMin(-10000), fEMCALTimeCutMax(10000), fEMCALParamTimeCutMin(), fEMCALParamTimeCutMax(), fTrackTimeCutMin(-10000), fTrackTimeCutMax(10000), fUseTrackDCACut(0), fAODBranchList(0x0), fCTSTracks(0x0), fEMCALClusters(0x0), fDCALClusters(0x0), fPHOSClusters(0x0), fEMCALCells(0x0), fPHOSCells(0x0), fInputEvent(0x0), fOutputEvent(0x0),fMC(0x0), fFillCTS(0), fFillEMCAL(0), fFillDCAL(0), fFillPHOS(0), fFillEMCALCells(0), fFillPHOSCells(0), fRecalculateClusters(kFALSE),fCorrectELinearity(kTRUE), fSelectEmbeddedClusters(kFALSE), fSmearShowerShape(0), fSmearShowerShapeWidth(0), fRandom(), fSmearingFunction(0), fSmearNLMMin(0), fSmearNLMMax(0), fTrackStatus(0), fSelectSPDHitTracks(0), fTrackMultNPtCut(0), fTrackMultEtaCut(0.9), fDeltaAODFileName(""), fFiredTriggerClassName(""), fEventTriggerMask(0), fMixEventTriggerMask(0), fEventTriggerAtSE(0), fEventTrigMinBias(0), fEventTrigCentral(0), fEventTrigSemiCentral(0), fEventTrigEMCALL0(0), fEventTrigEMCALL1Gamma1(0), fEventTrigEMCALL1Gamma2(0), fEventTrigEMCALL1Jet1(0), fEventTrigEMCALL1Jet2(0), fBitEGA(0), fBitEJE(0), fEventType(-1), fTaskName(""), fCaloUtils(0x0), fWeightUtils(0x0), fEventWeight(1), fMixedEvent(NULL), fNMixedEvent(0), fVertex(NULL), fListMixedTracksEvents(), fListMixedCaloEvents(), fLastMixedTracksEvent(-1), fLastMixedCaloEvent(-1), fWriteOutputDeltaAOD(kFALSE), fEMCALClustersListName(""), fZvtxCut(0.), fAcceptFastCluster(kFALSE), fRemoveLEDEvents(kFALSE), //Trigger rejection fRemoveBadTriggerEvents(0), fTriggerPatchClusterMatch(1), fTriggerPatchTimeWindow(), fTriggerL0EventThreshold(0), fTriggerL1EventThreshold(0), fTriggerL1EventThresholdFix(0), fTriggerClusterBC(0), fTriggerClusterIndex(0), fTriggerClusterId(0), fIsExoticEvent(0), fIsBadCellEvent(0), fIsBadMaxCellEvent(0), fIsTriggerMatch(0), fIsTriggerMatchOpenCut(), fTriggerClusterTimeRecal(kTRUE), fRemoveUnMatchedTriggers(kTRUE), fDoPileUpEventRejection(kFALSE), fDoV0ANDEventSelection(kFALSE), fDoVertexBCEventSelection(kFALSE), fDoRejectNoTrackEvents(kFALSE), fUseEventsWithPrimaryVertex(kFALSE), //fTriggerAnalysis (0x0), fTimeStampEventSelect(0), fTimeStampEventFracMin(0), fTimeStampEventFracMax(0), fTimeStampRunMin(0), fTimeStampRunMax(0), fNPileUpClusters(-1), fNNonPileUpClusters(-1), fNPileUpClustersCut(3), fVertexBC(-200), fRecalculateVertexBC(0), fUseAliCentrality(0), fCentralityClass(""), fCentralityOpt(0), fEventPlaneMethod(""), fFillInputNonStandardJetBranch(kFALSE), fNonStandardJets(new TClonesArray("AliAODJet",100)), fInputNonStandardJetBranchName("jets"), fFillInputBackgroundJetBranch(kFALSE), fBackgroundJets(0x0),fInputBackgroundJetBranchName("jets"), fAcceptEventsWithBit(0), fRejectEventsWithBit(0), fRejectEMCalTriggerEventsWith2Tresholds(0), fMomentum(), fOutputContainer(0x0), fhEMCALClusterTimeE(0), fEnergyHistogramNbins(0), fhNEventsAfterCut(0), fNMCGenerToAccept(0), fMCGenerEventHeaderToAccept("") { for(Int_t i = 0; i < 8; i++) fhEMCALClusterCutsE [i]= 0x0 ; for(Int_t i = 0; i < 7; i++) fhPHOSClusterCutsE [i]= 0x0 ; for(Int_t i = 0; i < 6; i++) fhCTSTrackCutsPt [i]= 0x0 ; for(Int_t j = 0; j < 5; j++) { fMCGenerToAccept [j] = ""; fMCGenerIndexToAccept[j] = -1; } InitParameters(); } //_______________________________________ /// Destructor. //_______________________________________ AliCaloTrackReader::~AliCaloTrackReader() { DeletePointers(); } //_______________________________________ /// Destructor. Called by the destructors /// of this class and derived classes. //_______________________________________ void AliCaloTrackReader::DeletePointers() { delete fFiducialCut ; if(fAODBranchList) { fAODBranchList->Delete(); delete fAODBranchList ; } if(fCTSTracks) { if(fDataType!=kMC)fCTSTracks->Clear() ; else fCTSTracks->Delete() ; delete fCTSTracks ; } if(fEMCALClusters) { if(fDataType!=kMC)fEMCALClusters->Clear("C") ; else fEMCALClusters->Delete() ; delete fEMCALClusters ; } if(fDCALClusters) { if(fDataType!=kMC)fDCALClusters->Clear("C") ; else fDCALClusters->Delete() ; delete fDCALClusters ; } if(fPHOSClusters) { if(fDataType!=kMC)fPHOSClusters->Clear("C") ; else fPHOSClusters->Delete() ; delete fPHOSClusters ; } if(fVertex) { for (Int_t i = 0; i < fNMixedEvent; i++) { delete [] fVertex[i] ; } delete [] fVertex ; } //delete fTriggerAnalysis; if(fNonStandardJets) { if(fDataType!=kMC) fNonStandardJets->Clear("C") ; else fNonStandardJets->Delete() ; delete fNonStandardJets ; } delete fBackgroundJets ; fRejectEventsWithBit.Reset(); fAcceptEventsWithBit.Reset(); if ( fWeightUtils ) delete fWeightUtils ; // Pointers not owned, done by the analysis frame // if(fInputEvent) delete fInputEvent ; // if(fOutputEvent) delete fOutputEvent ; // if(fMC) delete fMC ; // Pointer not owned, deleted by maker // if (fCaloUtils) delete fCaloUtils ; } //____________________________________________________________ /// Accept track if DCA is smaller than function. /// \param pt of track. /// \param dca of track. //____________________________________________________________ Bool_t AliCaloTrackReader::AcceptDCA(Float_t pt, Float_t dca) { Float_t cut = fTrackDCACut[0]+fTrackDCACut[1]/TMath::Power(pt,fTrackDCACut[2]); if(TMath::Abs(dca) < cut) return kTRUE; else return kFALSE; } //_____________________________________________________ /// Accept events that pass the physics selection /// depending on an array of trigger bits set during the configuration. //_____________________________________________________ Bool_t AliCaloTrackReader::AcceptEventWithTriggerBit() { Int_t nAccept = fAcceptEventsWithBit.GetSize(); //printf("N accept %d\n", nAccept); if( nAccept <= 0 ) return kTRUE ; // accept the event UInt_t trigFired = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); for(Int_t ibit = 0; ibit < nAccept; ibit++) { Bool_t accept = (trigFired & fAcceptEventsWithBit.At(ibit)); //printf("accept %d, ibit %d, bit %d \n",accept, ibit,fAcceptEventsWithBit.At(ibit)); if(accept) return kTRUE ; // accept the event } return kFALSE ; // reject the event } //_____________________________________________________ /// Reject particles/clusters depending on the generator /// of origin of the MC label. /// /// \param mcLabel label index of particle originating the cluster or track or mc stack //_____________________________________________________ Bool_t AliCaloTrackReader::AcceptParticleMCLabel(Int_t mcLabel) const { if( !fMC || fNMCGenerToAccept <= 0 ) return kTRUE; TString genName; Int_t genIndex; genIndex = GetCocktailGeneratorAndIndex(mcLabel, genName); //fMC->GetCocktailGenerator(mcLabel,genName); Bool_t generOK = kFALSE; for(Int_t ig = 0; ig < fNMCGenerToAccept; ig++) { if ( fMCGenerToAccept[ig].Contains(genName) ) generOK = kTRUE; if ( generOK && fMCGenerIndexToAccept[ig] >= 0 && fMCGenerToAccept[ig] != genIndex) generOK = kFALSE; } if ( !generOK ) AliDebug(1, Form("skip label %d, gen %s",mcLabel,genName.Data()) ); return generOK; } //_____________________________________________________________________ /// Get the name of the generator that generated a given primary particle /// Copy of AliMCEvent::GetCocktailGeneratorAndIndex(), modified to get the /// the generator index in the cocktail /// /// \param index: mc label index /// \param nameGen: cocktail generator name for this index /// \return cocktail generator index //_____________________________________________________________________ Int_t AliCaloTrackReader::GetCocktailGeneratorAndIndex(Int_t index, TString & nameGen) const { //method that gives the generator for a given particle with label index (or that of the corresponding primary) AliVParticle* mcpart0 = (AliVParticle*) GetMC()->GetTrack(index); Int_t genIndex = -1; if(!mcpart0) { printf("AliMCEvent-BREAK: No valid AliMCParticle at label %i\n",index); return -1; } nameGen = GetGeneratorNameAndIndex(index,genIndex); if(nameGen.Contains("nococktailheader") ) return -1; Int_t lab=index; while(nameGen.IsWhitespace()) { AliVParticle* mcpart = (AliVParticle*) GetMC()->GetTrack(lab); if(!mcpart) { printf("AliMCEvent-BREAK: No valid AliMCParticle at label %i\n",lab); break; } Int_t mother=0; mother = mcpart->GetMother(); if(mother<0) { printf("AliMCEvent - BREAK: Reached primary particle without valid mother\n"); break; } AliVParticle* mcmom = (AliVParticle*) GetMC()->GetTrack(mother); if(!mcmom) { printf("AliMCEvent-BREAK: No valid AliMCParticle mother at label %i\n",mother); break; } lab=mother; nameGen = GetGeneratorNameAndIndex(mother,genIndex); } return genIndex; } //_____________________________________________________________________ /// Get the name of the generator that generated a given primary particle /// Copy of AliMCEvent::GetGenerator(), modified to get the /// the generator index in the cocktail /// /// \param index: mc label index /// \param genIndex: cocktail generator name for this index /// \return cocktail generator name string //_____________________________________________________________________ TString AliCaloTrackReader::GetGeneratorNameAndIndex(Int_t index, Int_t & genIndex) const { Int_t nsumpart = GetMC()->GetNumberOfPrimaries(); genIndex = -1; TList* lh = GetMC()->GetCocktailList(); if(!lh) { TString noheader="nococktailheader"; return noheader; } Int_t nh = lh->GetEntries(); for (Int_t i = nh-1; i >= 0; i--) { AliGenEventHeader* gh = (AliGenEventHeader*)lh->At(i); TString genname = gh->GetName(); Int_t npart=gh->NProduced(); if (i == 0) npart = nsumpart; if(index < nsumpart && index >= (nsumpart-npart)) { genIndex = i ; return genname; } nsumpart-=npart; } TString empty=""; return empty; } //_____________________________________________________ /// Reject events that pass the physics selection /// depending on an array of trigger bits set during the configuration. //_____________________________________________________ Bool_t AliCaloTrackReader::RejectEventWithTriggerBit() { Int_t nReject = fRejectEventsWithBit.GetSize(); //printf("N reject %d\n", nReject); if( nReject <= 0 ) return kTRUE ; // accept the event UInt_t trigFired = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); for(Int_t ibit = 0; ibit < nReject; ibit++) { Bool_t reject = (trigFired & fRejectEventsWithBit.At(ibit)); //printf("reject %d, ibit %d, bit %d \n",reject, ibit,fRejectEventsWithBit.At(ibit)); if(reject) return kFALSE ; // reject the event } return kTRUE ; // accept the event } //_____________________________________________ /// Do different selection of the event /// depending on trigger name, event type, /// goodness of the EMCal trigger ... //_____________________________________________ Bool_t AliCaloTrackReader::CheckEventTriggers() { //----------------------------------------------------------- // Reject events depending on the trigger name //----------------------------------------------------------- AliDebug(1,Form("FiredTriggerClass <%s>, selected class <%s>, compare name %d", GetFiredTriggerClasses().Data(),fFiredTriggerClassName.Data(), GetFiredTriggerClasses().Contains(fFiredTriggerClassName))); if ( fFiredTriggerClassName != "" ) { if ( !GetFiredTriggerClasses().Contains(fFiredTriggerClassName) ) return kFALSE; AliDebug(1,"Accepted triggered event"); fhNEventsAfterCut->Fill(1.5); } //----------------------------------------------------------- // Reject events depending on the event species type //----------------------------------------------------------- // Event types: // kStartOfRun = 1, // START_OF_RUN // kEndOfRun = 2, // END_OF_RUN // kStartOfRunFiles = 3, // START_OF_RUN_FILES // kEndOfRunFiles = 4, // END_OF_RUN_FILES // kStartOfBurst = 5, // START_OF_BURST // kEndOfBurst = 6, // END_OF_BURST // kPhysicsEvent = 7, // PHYSICS_EVENT // kCalibrationEvent = 8, // CALIBRATION_EVENT // kFormatError = 9, // EVENT_FORMAT_ERROR // kStartOfData = 10, // START_OF_DATA // kEndOfData = 11, // END_OF_DATA // kSystemSoftwareTriggerEvent = 12, // SYSTEM_SOFTWARE_TRIGGER_EVENT // kDetectorSoftwareTriggerEvent = 13 // DETECTOR_SOFTWARE_TRIGGER_EVENT Int_t eventType = 0; if(fInputEvent->GetHeader()) eventType = ((AliVHeader*)fInputEvent->GetHeader())->GetEventType(); AliDebug(3,Form("Event type %d",eventType)); // Select only Physics events in data, eventType = 7, // usually done by physics selection // MC not set, eventType =0, I think, so do not apply a value to fEventType by default // LED events have eventType = 8, implemented a selection cut in the past // but not really useful for EMCal data since LED are not reconstructed (unless wrongly assumed as physics) if ( fEventType >= 0 && eventType != fEventType ) return kFALSE ; AliDebug(1,"Pass event species selection"); fhNEventsAfterCut->Fill(2.5); //----------------------------------------------------------------- // In case of mixing analysis, select here the trigger of the event //----------------------------------------------------------------- UInt_t isTrigger = kFALSE; UInt_t isMB = kFALSE; if(!fEventTriggerAtSE) { // In case of mixing analysis, accept MB events, not only Trigger // Track and cluster arrays filled for MB in order to create the pool in the corresponding analysis // via de method in the base class FillMixedEventPool() AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler *inputHandler = dynamic_cast<AliInputEventHandler*>(manager->GetInputEventHandler()); if(!inputHandler) return kFALSE ; // to content coverity isTrigger = inputHandler->IsEventSelected() & fEventTriggerMask; isMB = inputHandler->IsEventSelected() & fMixEventTriggerMask; if(!isTrigger && !isMB) return kFALSE; //printf("Selected triggered event : %s\n",GetFiredTriggerClasses().Data()); AliDebug(0,"Pass uninteresting triggered events rejection in case of mixing analysis"); fhNEventsAfterCut->Fill(3.5); } //------------------------------------------------------------------------------------- // Reject or accept events depending on the trigger bit //------------------------------------------------------------------------------------- Bool_t okA = AcceptEventWithTriggerBit(); Bool_t okR = RejectEventWithTriggerBit(); //printf("AliCaloTrackReader::FillInputEvent() - Accept event? %d, Reject event %d? \n",okA,okR); if(!okA || !okR) return kFALSE; AliDebug(1,"Pass event bit rejection"); fhNEventsAfterCut->Fill(4.5); //---------------------------------------------------------------------- // Do not count events that were likely triggered by an exotic cluster // or out BC cluster //---------------------------------------------------------------------- // Set a bit with the event kind, MB, L0, L1 ... SetEventTriggerBit(); // In case of Mixing, avoid checking the triggers in the min bias events if(!fEventTriggerAtSE && (isMB && !isTrigger)) return kTRUE; if( (IsEventEMCALL1() || IsEventEMCALL0()) && fTriggerPatchClusterMatch) { if(fRejectEMCalTriggerEventsWith2Tresholds) { // Reject triggered events when there is coincidence on both EMCal trigger thresholds, // but the requested trigger is the low trigger threshold if(IsEventEMCALL1Jet1 () && IsEventEMCALL1Jet2 () && fFiredTriggerClassName.Contains("EJ2")) return kFALSE; if(IsEventEMCALL1Gamma1() && IsEventEMCALL1Gamma2() && fFiredTriggerClassName.Contains("EG2")) return kFALSE; } //Get Patches that triggered TArrayI patches = GetTriggerPatches(fTriggerPatchTimeWindow[0],fTriggerPatchTimeWindow[1]); MatchTriggerCluster(patches); patches.Reset(); // If requested, remove badly triggeed events, but only when the EMCal trigger bit is set if(fRemoveBadTriggerEvents) { AliDebug(1,Form("ACCEPT triggered event? \n exotic? %d - bad cell %d - bad Max cell %d - BC %d - Matched %d\n", fIsExoticEvent,fIsBadCellEvent, fIsBadMaxCellEvent, fTriggerClusterBC,fIsTriggerMatch)); if (fIsExoticEvent) return kFALSE; else if(fIsBadCellEvent) return kFALSE; else if(fRemoveUnMatchedTriggers && !fIsTriggerMatch) return kFALSE ; else if(fTriggerClusterBC != 0) return kFALSE; AliDebug(1,Form("\t *** YES for %s",GetFiredTriggerClasses().Data())); } AliDebug(1,"Pass EMCal triggered event rejection \n"); fhNEventsAfterCut->Fill(5.5); } //------------------------------------------------------------------------------------- // Select events only fired by a certain trigger configuration if it is provided //------------------------------------------------------------------------------------- if (GetFiredTriggerClasses().Contains("FAST") && !GetFiredTriggerClasses().Contains("ALL") && !fAcceptFastCluster) { AliDebug(1,Form("Do not count events from fast cluster, trigger name %s\n",fFiredTriggerClassName.Data())); return kFALSE; fhNEventsAfterCut->Fill(6.5); } //------------------------------------------------------------------------------------- // Reject event if large clusters with large energy // Use only for LHC11a data for the moment, and if input is clusterizer V1 or V1+unfolding // If clusterzer NxN or V2 it does not help //------------------------------------------------------------------------------------- //Int_t run = fInputEvent->GetRunNumber(); if ( fRemoveLEDEvents ) { Bool_t reject = RejectLEDEvents(); if(reject) return kFALSE; AliDebug(1,"Pass LED event rejection"); fhNEventsAfterCut->Fill(7.5); } // Remove LED events // All selection criteria passed, accept the event return kTRUE ; } //________________________________________________ /// Check the MC PYTHIA event, if the requested /// pT-hard is much smaller than the jet pT, then, /// there can be a problem in the tails of the /// distributions and the event should be rejected. //________________________________________________ Bool_t AliCaloTrackReader::ComparePtHardAndJetPt() { //printf("AliCaloTrackReader::ComparePtHardAndJetPt() - GenHeaderName : %s\n",GetGenEventHeader()->ClassName()); if(!strcmp(GetGenEventHeader()->ClassName(), "AliGenPythiaEventHeader")) { TParticle * jet = 0; AliGenPythiaEventHeader* pygeh= (AliGenPythiaEventHeader*) GetGenEventHeader(); Int_t nTriggerJets = pygeh->NTriggerJets(); Float_t ptHard = pygeh->GetPtHard(); AliDebug(1,Form("Njets: %d, pT Hard %f",nTriggerJets, ptHard)); Float_t tmpjet[]={0,0,0,0}; for(Int_t ijet = 0; ijet< nTriggerJets; ijet++) { pygeh->TriggerJet(ijet, tmpjet); jet = new TParticle(94, 21, -1, -1, -1, -1, tmpjet[0],tmpjet[1],tmpjet[2],tmpjet[3], 0,0,0,0); AliDebug(1,Form("jet %d; pycell jet pT %f",ijet, jet->Pt())); //Compare jet pT and pt Hard if(jet->Pt() > fPtHardAndJetPtFactor * ptHard) { AliInfo(Form("Reject jet event with : pT Hard %2.2f, pycell jet pT %2.2f, rejection factor %1.1f\n", ptHard, jet->Pt(), fPtHardAndJetPtFactor)); return kFALSE; } } if(jet) delete jet; } return kTRUE ; } //____________________________________________________ /// Check the MC PYTHIA event, if the requested /// pT-hard is smaller than the calorimeter cluster E, /// there can be a problem in the tails of the /// distributions and the event should be rejected. //____________________________________________________ Bool_t AliCaloTrackReader::ComparePtHardAndClusterPt() { if(!strcmp(GetGenEventHeader()->ClassName(), "AliGenPythiaEventHeader")) { AliGenPythiaEventHeader* pygeh= (AliGenPythiaEventHeader*) GetGenEventHeader(); Float_t ptHard = pygeh->GetPtHard(); Int_t nclusters = fInputEvent->GetNumberOfCaloClusters(); for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = fInputEvent->GetCaloCluster(iclus) ; Float_t ecluster = clus->E(); if(ecluster > fPtHardAndClusterPtFactor*ptHard) { AliInfo(Form("Reject : ecluster %2.2f, calo %d, factor %2.2f, ptHard %f",ecluster,clus->GetType(),fPtHardAndClusterPtFactor,ptHard)); return kFALSE; } } } return kTRUE ; } //___________________________________________________ /// Fill the output list of initialized control histograms. /// Cluster or track spectra histograms, depending on different selection cuts. //___________________________________________________ TList * AliCaloTrackReader::GetCreateControlHistograms() { fhNEventsAfterCut = new TH1I("hNEventsAfterCut", "Number of analyzed events", 20, 0, 20) ; //fhNEventsAfterCut->SetXTitle("Selection"); fhNEventsAfterCut->SetYTitle("# events"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(1 ,"1=Input"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(2 ,"2=Trigger string"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(3 ,"3=Event Type"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(4 ,"4=Mixing Event"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(5 ,"5=Trigger Bit"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(6 ,"6=Good EMC Trigger"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(7 ,"7=!Fast Cluster"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(8 ,"8=!LED"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(9 ,"9=Time stamp"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(10,"10=Primary vertex"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(11,"11=Null 3 vertex"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(12,"12=Z vertex window"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(13,"13=Pile-up"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(14,"14=V0AND"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(15,"15=Centrality"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(16,"16=GenHeader"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(17,"17=PtHard-Jet"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(18,"18=PtHard-Cluster"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(19,"19=N Track>0"); fhNEventsAfterCut->GetXaxis()->SetBinLabel(20,"20=TOF BC"); fOutputContainer->Add(fhNEventsAfterCut); if(fFillEMCAL) { for(Int_t i = 0; i < 8; i++) { TString names[] = { "NoCut", "Corrected", "GoodCluster", "NonLinearity", "EnergyAndFidutial", "NCells", "BadDist", "Time" } ; fhEMCALClusterCutsE[i] = new TH1F(Form("hEMCALReaderClusterCuts_%d_%s",i,names[i].Data()), Form("EMCal %d, %s",i,names[i].Data()), fEnergyHistogramNbins, fEnergyHistogramLimit[0], fEnergyHistogramLimit[1]); fhEMCALClusterCutsE[i]->SetYTitle("# clusters"); fhEMCALClusterCutsE[i]->SetXTitle("#it{E} (GeV)"); fOutputContainer->Add(fhEMCALClusterCutsE[i]); } fhEMCALClusterTimeE = new TH2F ("hEMCALReaderTimeE","time vs #it{E} after cuts (if no calib, shifted -615 ns)", 100,0,100,400,-400,400); fhEMCALClusterTimeE->SetXTitle("#it{E} (GeV)"); fhEMCALClusterTimeE->SetYTitle("#it{time} (ns)"); fOutputContainer->Add(fhEMCALClusterTimeE); } if(fFillPHOS) { for(Int_t i = 0; i < 7; i++) { TString names[] = {"NoCut", "ExcludeCPV", "BorderCut", "FiducialCut", "EnergyCut", "NCells", "BadDist"}; fhPHOSClusterCutsE[i] = new TH1F(Form("hPHOSReaderClusterCuts_%d_%s",i,names[i].Data()), Form("PHOS Cut %d, %s",i,names[i].Data()), fEnergyHistogramNbins, fEnergyHistogramLimit[0], fEnergyHistogramLimit[1]) ; fhPHOSClusterCutsE[i]->SetYTitle("# clusters"); fhPHOSClusterCutsE[i]->SetXTitle("#it{E} (GeV)"); fOutputContainer->Add(fhPHOSClusterCutsE[i]); } } if(fFillCTS) { for(Int_t i = 0; i < 6; i++) { TString names[] = {"NoCut", "Status", "ESD_AOD", "TOF", "DCA","PtAcceptanceMult"}; fhCTSTrackCutsPt[i] = new TH1F(Form("hCTSReaderClusterCuts_%d_%s",i,names[i].Data()), Form("CTS Cut %d, %s",i,names[i].Data()), fEnergyHistogramNbins, fEnergyHistogramLimit[0], fEnergyHistogramLimit[1]) ; fhCTSTrackCutsPt[i]->SetYTitle("# tracks"); fhCTSTrackCutsPt[i]->SetXTitle("#it{p}_{T} (GeV)"); fOutputContainer->Add(fhCTSTrackCutsPt[i]); } } return fOutputContainer ; } //_____________________________________________________ /// Save parameters used for analysis in a string. //_____________________________________________________ TObjString * AliCaloTrackReader::GetListOfParameters() { TString parList ; //this will be list of parameters used for this analysis. const Int_t buffersize = 255; char onePar[buffersize] ; snprintf(onePar,buffersize,"--- Reader ---:") ; parList+=onePar ; snprintf(onePar,buffersize,"Data type: %d; zvertex cut %2.2f; EMC cluster name: <%s> ",fDataType, fZvtxCut, fEMCALClustersListName.Data()) ; parList+=onePar ; snprintf(onePar,buffersize,"Use detector: EMC %d, DCA %d, PHOS %d, CTS %d, EMCcells %d, PHOScells %d ; ", fFillEMCAL,fFillDCAL,fFillPHOS,fFillCTS,fFillEMCALCells,fFillPHOSCells) ; snprintf(onePar,buffersize,"E-pT window: EMC (%2.1f,%2.1f), PHOS (%2.1f,%2.1f), CTS (%2.1f,%2.1f); ", fEMCALPtMin,fEMCALPtMax,fPHOSPtMin,fPHOSPtMax,fCTSPtMin,fCTSPtMax) ; parList+=onePar ; snprintf(onePar,buffersize,"Dist to bad channel: EMC > %2.1f, PHOS > %2.1f; ",fEMCALBadChMinDist,fPHOSBadChMinDist) ; parList+=onePar ; snprintf(onePar,buffersize,"N cells: EMC > %d, PHOS > %d; ",fEMCALNCellsCut,fPHOSNCellsCut) ; parList+=onePar ; snprintf(onePar,buffersize,"EMC time cut single window (%2.2f,%2.2f); ",fEMCALTimeCutMin,fEMCALTimeCutMax) ; parList+=onePar ; snprintf(onePar,buffersize,"Check: calo fid cut %d; ",fCheckFidCut) ; parList+=onePar ; snprintf(onePar,buffersize,"Track: status %d, SPD hit %d; ",(Int_t) fTrackStatus, fSelectSPDHitTracks) ; parList+=onePar ; snprintf(onePar,buffersize,"multip. eta cut %1.1f; npt cuts %d;",fTrackMultEtaCut, fTrackMultNPtCut) ; parList+=onePar ; if(fUseTrackDCACut) { snprintf(onePar,buffersize,"DCA cut ON, param (%2.4f,%2.4f,%2.4f); ",fTrackDCACut[0],fTrackDCACut[1],fTrackDCACut[2]) ; parList+=onePar ; } snprintf(onePar,buffersize,"Recalculate Clusters = %d, E linearity = %d; ",fRecalculateClusters, fCorrectELinearity) ; parList+=onePar ; snprintf(onePar,buffersize,"SE trigger sel. %d, not? trigger Mask? %d, MB Trigger Mask for mixed %d; ", fEventTriggerAtSE, fEventTriggerMask,fMixEventTriggerMask); parList+=onePar ; snprintf(onePar,buffersize,"Select fired trigger %s; Remove Bad trigger event %d, unmatched %d; Accept fastcluster %d, Reject LED %d ", fFiredTriggerClassName.Data(), fRemoveBadTriggerEvents, fRemoveUnMatchedTriggers, fAcceptFastCluster, fRemoveLEDEvents); parList+=onePar ; if(fNMCGenerToAccept) { snprintf(onePar,buffersize,"Accept only labels from: "); parList+=onePar ; for(Int_t i = 0; i< fNMCGenerToAccept; i++) parList+=(fMCGenerToAccept[i]+" ") ; snprintf(onePar,buffersize,"; "); parList+=onePar ; } if(fSmearShowerShape) { snprintf(onePar,buffersize,"EMC M02 smear ON, function %d, param %2.4f, %d<=NLM<=%d; ", fSmearingFunction,fSmearShowerShapeWidth,fSmearNLMMin,fSmearNLMMax) ; parList+=onePar ; } if(fComparePtHardAndJetPt) { snprintf(onePar,buffersize,"jet pt / pt hard < %2.1f; ",fPtHardAndJetPtFactor); parList+=onePar ; } if(fComparePtHardAndClusterPt) { snprintf(onePar,buffersize,"cluster pt / pt hard < %2.2f",fPtHardAndClusterPtFactor); parList+=onePar ; } snprintf(onePar,buffersize,"Centrality: Class %s, Option %d, Bin [%d,%d]; New centrality %d; Event plane method %s; ", fCentralityClass.Data(),fCentralityOpt,fCentralityBin[0], fCentralityBin[1],fUseAliCentrality,fEventPlaneMethod.Data()) ; parList+=onePar ; return new TObjString(parList) ; } //______________________________________________ /// \return pointer to header (AliHeader) //______________________________________________ AliHeader* AliCaloTrackReader::GetHeader() const { if(fMC) { return fMC->Header(); } else { AliInfo("Header is not available"); return 0x0 ; } } //_________________________________________________________ /// \return list of particles in AOD, /// Implemented in AliCaloTrackAODReader. //_________________________________________________________ TClonesArray* AliCaloTrackReader::GetAODMCParticles() const { AliInfo("Input are not AODs"); return NULL ; } //________________________________________________________ /// \return MC header in AOD. /// Implemented in AliCaloTrackAODReader. //________________________________________________________ AliAODMCHeader* AliCaloTrackReader::GetAODMCHeader() const { AliInfo("Input are not AODs"); return NULL ; } //___________________________________________________________ /// \return vertex Bunch Cross Number. /// In old AODs BC not stored, recalculate it here, /// loop over the global track and select those which have /// small DCA to primary vertex (e.g. primary). /// If at least one of these primaries has valid BC != 0, then /// this vertex is a pile-up candidate. /// Execute after CTS filtering. //___________________________________________________________ Int_t AliCaloTrackReader::GetVertexBC(const AliVVertex * vtx) { Int_t vertexBC=vtx->GetBC(); if(!fRecalculateVertexBC) return vertexBC; // Value not available, recalculate it. Double_t bz = fInputEvent->GetMagneticField(); Bool_t bc0 = kFALSE; Int_t ntr = GetCTSTracks()->GetEntriesFast(); //printf("N Tracks %d\n",ntr); for(Int_t i = 0 ; i < ntr ; i++) { AliVTrack * track = (AliVTrack*) (GetCTSTracks()->At(i)); //Check if has TOF info, if not skip ULong_t status = track->GetStatus(); Bool_t okTOF = (status & AliVTrack::kTOFout) == AliVTrack::kTOFout ; vertexBC = track->GetTOFBunchCrossing(bz); Float_t pt = track->Pt(); if(!okTOF) continue; // Get DCA x, y Double_t dca[2] = {1e6,1e6}; Double_t covar[3] = {1e6,1e6,1e6}; track->PropagateToDCA(vtx,bz,100.,dca,covar); if(AcceptDCA(pt,dca[0])) { if (vertexBC !=0 && fVertexBC != AliVTrack::kTOFBCNA) return vertexBC; else if(vertexBC == 0) bc0 = kTRUE; } } if( bc0 ) vertexBC = 0 ; else vertexBC = AliVTrack::kTOFBCNA ; return vertexBC; } //_____________________________ /// /// Return track ID, different for ESD and AODs. /// See AliCaloTrackAODReader for AOD correspondent /// /// \return track ID /// \param track: pointer to track //_____________________________ Int_t AliCaloTrackReader::GetTrackID(AliVTrack* track) { return track->GetID(); } //_____________________________ /// Init the reader. /// Method to be called in AliAnaCaloTrackCorrMaker. //_____________________________ void AliCaloTrackReader::Init() { // Activate debug level in AliAnaWeights if( fWeightUtils->GetDebug() >= 0 ) (AliAnalysisManager::GetAnalysisManager())->AddClassDebug(fWeightUtils->ClassName(), fWeightUtils->GetDebug()); } //_______________________________________ /// Initialize the parameters with default. //_______________________________________ void AliCaloTrackReader::InitParameters() { fDataType = kESD ; fCTSPtMin = 0.1 ; fEMCALPtMin = 0.1 ; fPHOSPtMin = 0.1 ; fCTSPtMax = 1000. ; fEMCALPtMax = 1000. ; fPHOSPtMax = 1000. ; fEMCALBadChMinDist = 0; // open, 2; // standard fPHOSBadChMinDist = 0; // open, 2; // standard fEMCALNCellsCut = 0; // open, 1; // standard fPHOSNCellsCut = 0; // open, 2; // standard //Track DCA cuts // dca_xy cut = 0.0105+0.0350/TMath::Power(pt,1.1); fTrackDCACut[0] = 0.0105; fTrackDCACut[1] = 0.0350; fTrackDCACut[2] = 1.1; //Do not filter the detectors input by default. fFillEMCAL = kFALSE; fFillDCAL = kFALSE; fFillPHOS = kFALSE; fFillCTS = kFALSE; fFillEMCALCells = kFALSE; fFillPHOSCells = kFALSE; fDeltaAODFileName = "deltaAODPartCorr.root"; fFiredTriggerClassName = ""; fEventTriggerMask = AliVEvent::kAny; fMixEventTriggerMask = AliVEvent::kAnyINT; fEventTriggerAtSE = kTRUE; // Use only events that pass event selection at SE base class fAcceptFastCluster = kTRUE; fEventType = -1; //We want tracks fitted in the detectors: //fTrackStatus=AliESDtrack::kTPCrefit; //fTrackStatus|=AliESDtrack::kITSrefit; fTrackStatus = 0; fV0ADC[0] = 0; fV0ADC[1] = 0; fV0Mul[0] = 0; fV0Mul[1] = 0; fZvtxCut = 10.; fNMixedEvent = 1; fPtHardAndJetPtFactor = 7.; fPtHardAndClusterPtFactor = 1.; //Centrality fUseAliCentrality = kFALSE; fCentralityClass = "V0M"; fCentralityOpt = 100; fCentralityBin[0] = fCentralityBin[1]=-1; fEventPlaneMethod = "V0"; // Allocate memory (not sure this is the right place) fCTSTracks = new TObjArray(); fEMCALClusters = new TObjArray(); fDCALClusters = new TObjArray(); fPHOSClusters = new TObjArray(); //fTriggerAnalysis = new AliTriggerAnalysis; fAODBranchList = new TList ; fOutputContainer = new TList ; fEnergyHistogramNbins = 200; fEnergyHistogramLimit[0] = 0 ; fEnergyHistogramLimit[1] = 100; fPileUpParamSPD[0] = 3 ; fPileUpParamSPD[1] = 0.8 ; fPileUpParamSPD[2] = 3.0 ; fPileUpParamSPD[3] = 2.0 ; fPileUpParamSPD[4] = 5.0; // Parametrized time cut (LHC11d) fEMCALParamTimeCutMin[0] =-5; fEMCALParamTimeCutMin[1] =-1 ; fEMCALParamTimeCutMin[2] = 3.5 ; fEMCALParamTimeCutMin[3] = 1. ; fEMCALParamTimeCutMax[0] = 5; fEMCALParamTimeCutMax[1] = 50; fEMCALParamTimeCutMax[2] = 0.45; fEMCALParamTimeCutMax[3] = 1.25; // Parametrized time cut (LHC11c) //fEMCALParamTimeCutMin[0] =-5; fEMCALParamTimeCutMin[1] =-1 ; fEMCALParamTimeCutMin[2] = 1.87; fEMCALParamTimeCutMin[3] = 0.4; //fEMCALParamTimeCutMax[0] = 3.5; fEMCALParamTimeCutMax[1] = 50; fEMCALParamTimeCutMax[2] = 0.15; fEMCALParamTimeCutMax[3] = 1.6; fTimeStampRunMin = -1; fTimeStampRunMax = 1e12; fTimeStampEventFracMin = -1; fTimeStampEventFracMax = 2; for(Int_t i = 0; i < 19; i++) { fEMCalBCEvent [i] = 0; fEMCalBCEventCut[i] = 0; fTrackBCEvent [i] = 0; fTrackBCEventCut[i] = 0; } // Trigger match-rejection fTriggerPatchTimeWindow[0] = 8; fTriggerPatchTimeWindow[1] = 9; fTriggerClusterBC = -10000 ; fTriggerL0EventThreshold = -1; fTriggerL1EventThreshold = -1; fTriggerClusterIndex = -1; fTriggerClusterId = -1; //Jets fInputNonStandardJetBranchName = "jets"; fFillInputNonStandardJetBranch = kFALSE; if(!fNonStandardJets) fNonStandardJets = new TClonesArray("AliAODJet",100); fInputBackgroundJetBranchName = "jets"; fFillInputBackgroundJetBranch = kFALSE; if(!fBackgroundJets) fBackgroundJets = new AliAODJetEventBackground(); fSmearShowerShapeWidth = 0.005; fSmearNLMMin = 1; fSmearNLMMax = 1; fWeightUtils = new AliAnaWeights() ; fEventWeight = 1 ; fTrackMultNPtCut = 8; fTrackMultPtCut[0] = 0.15; fTrackMultPtCut[1] = 0.5; fTrackMultPtCut[2] = 1.0; fTrackMultPtCut[3] = 2.0 ; fTrackMultPtCut[4] = 4.0; fTrackMultPtCut[5] = 6.0; fTrackMultPtCut[6] = 8.0 ; fTrackMultPtCut[7] = 10.; fTrackMultPtCut[8] = 15.0; fTrackMultPtCut[9] = 20.; } //__________________________________________________________________________ /// Select the cluster depending on a time window, either a simple /// range or a parametrization depending on the energy. //__________________________________________________________________________ Bool_t AliCaloTrackReader::IsInTimeWindow(Double_t tof, Float_t energy) const { // Parametrized cut depending on E if(fUseParamTimeCut) { Float_t minCut= fEMCALParamTimeCutMin[0]+fEMCALParamTimeCutMin[1]*TMath::Exp(-(energy-fEMCALParamTimeCutMin[2])/fEMCALParamTimeCutMin[3]); Float_t maxCut= fEMCALParamTimeCutMax[0]+fEMCALParamTimeCutMax[1]*TMath::Exp(-(energy-fEMCALParamTimeCutMax[2])/fEMCALParamTimeCutMax[3]); //printf("tof %f, minCut %f, maxCut %f\n",tof,minCut,maxCut); if( tof < minCut || tof > maxCut ) return kFALSE ; } //In any case, the time should to be larger than the fixed window ... if( tof < fEMCALTimeCutMin || tof > fEMCALTimeCutMax ) return kFALSE ; return kTRUE ; } //________________________________________________ /// Check if event is from pile-up determined by SPD. /// Default values: (3, 0.8, 3., 2., 5.). //________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromSPD() const { return fInputEvent->IsPileupFromSPD((Int_t) fPileUpParamSPD[0] , fPileUpParamSPD[1] , fPileUpParamSPD[2] , fPileUpParamSPD[3] , fPileUpParamSPD[4] ); //printf("Param : %d, %2.2f, %2.2f, %2.2f, %2.2f\n",(Int_t) fPileUpParamSPD[0], fPileUpParamSPD[1], fPileUpParamSPD[2], fPileUpParamSPD[3], fPileUpParamSPD[4]); } //__________________________________________________ /// Check if event is from pile-up determined by EMCal //__________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromEMCal() const { if(fNPileUpClusters > fNPileUpClustersCut) return kTRUE ; else return kFALSE; } //________________________________________________________ /// Check if event is from pile-up determined by SPD and EMCal. //________________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromSPDAndEMCal() const { if( IsPileUpFromSPD() && IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //_______________________________________________________ /// Check if event is from pile-up determined by SPD or EMCal. //_______________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromSPDOrEMCal() const { if( IsPileUpFromSPD() || IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //___________________________________________________________ /// Check if event is from pile-up determined by SPD and not by EMCal. //___________________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromSPDAndNotEMCal() const { if( IsPileUpFromSPD() && !IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //___________________________________________________________ /// Check if event is from pile-up determined by EMCal, not by SPD. //___________________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromEMCalAndNotSPD() const { if( !IsPileUpFromSPD() && IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //______________________________________________________________ /// Check if event not from pile-up determined neither by SPD nor by EMCal. //______________________________________________________________ Bool_t AliCaloTrackReader::IsPileUpFromNotSPDAndNotEMCal() const { if( !IsPileUpFromSPD() && !IsPileUpFromEMCal()) return kTRUE ; else return kFALSE; } //___________________________________________________________________________________ /// Event and tracks/clusters filtering method. Main steps: /// * Accept/reject the event looking to the triggers, vertex, pile-up, time stamps, /// PYTHIA pT hard, centrality etc. /// * Filter the tracks and calorimeter clusters, even correct the clusters if requested /// and put them in lists. /// /// Called by the analysis maker. //___________________________________________________________________________________ Bool_t AliCaloTrackReader::FillInputEvent(Int_t iEntry, const char * /*curFileName*/) { fEventNumber = iEntry; fTriggerClusterIndex = -1; fTriggerClusterId = -1; fIsTriggerMatch = kFALSE; fTriggerClusterBC = -10000; fIsExoticEvent = kFALSE; fIsBadCellEvent = kFALSE; fIsBadMaxCellEvent = kFALSE; fIsTriggerMatchOpenCut[0] = kFALSE ; fIsTriggerMatchOpenCut[1] = kFALSE ; fIsTriggerMatchOpenCut[2] = kFALSE ; //fCurrentFileName = TString(currentFileName); if(!fInputEvent) { AliInfo("Input event not available, skip event analysis"); return kFALSE; } fhNEventsAfterCut->Fill(0.5); //----------------------------------------------- // Select the event depending on the trigger type // and other event characteristics // like the goodness of the EMCal trigger //----------------------------------------------- Bool_t accept = CheckEventTriggers(); if(!accept) return kFALSE; AliDebug(1,"Pass Event trigger selection"); //------------------------------------------------------ // Event rejection depending on time stamp //------------------------------------------------------ if(fDataType==kESD && fTimeStampEventSelect) { AliESDEvent* esd = dynamic_cast<AliESDEvent*> (fInputEvent); if(esd) { Int_t timeStamp = esd->GetTimeStamp(); Float_t timeStampFrac = 1.*(timeStamp-fTimeStampRunMin) / (fTimeStampRunMax-fTimeStampRunMin); //printf("stamp0 %d, max0 %d, frac %f\n", timeStamp-fTimeStampRunMin,fTimeStampRunMax-fTimeStampRunMin, timeStampFrac); if(timeStampFrac < fTimeStampEventFracMin || timeStampFrac > fTimeStampEventFracMax) return kFALSE; } AliDebug(1,"Pass Time Stamp rejection"); fhNEventsAfterCut->Fill(8.5); } //------------------------------------------------------ // Event rejection depending on vertex, pileup, v0and //------------------------------------------------------ FillVertexArray(); if(fUseEventsWithPrimaryVertex) { if( !CheckForPrimaryVertex() ) return kFALSE; // algorithm in ESD/AOD Readers fhNEventsAfterCut->Fill(9.5); if( TMath::Abs(fVertex[0][0] ) < 1.e-6 && TMath::Abs(fVertex[0][1] ) < 1.e-6 && TMath::Abs(fVertex[0][2] ) < 1.e-6 ) return kFALSE; AliDebug(1,"Pass primary vertex/null rejection"); fhNEventsAfterCut->Fill(10.5); } //Reject events with Z vertex too large, only for SE analysis, if not, cut on the analysis code if(!GetMixedEvent() && TMath::Abs(fVertex[0][2]) > fZvtxCut) return kFALSE; fhNEventsAfterCut->Fill(11.5); AliDebug(1,"Pass z vertex rejection"); //printf("Reader : IsPileUp %d, Multi %d\n",IsPileUpFromSPD(),fInputEvent->IsPileupFromSPDInMultBins()); if(fDoPileUpEventRejection) { // Do not analyze events with pileup Bool_t bPileup = IsPileUpFromSPD(); //IsPileupFromSPDInMultBins() // method to try //printf("pile-up %d, %d, %2.2f, %2.2f, %2.2f, %2.2f\n",bPileup, (Int_t) fPileUpParamSPD[0], fPileUpParamSPD[1], fPileUpParamSPD[2], fPileUpParamSPD[3], fPileUpParamSPD[4]); if(bPileup) return kFALSE; AliDebug(1,"Pass Pile-Up event rejection"); fhNEventsAfterCut->Fill(12.5); } if(fDoV0ANDEventSelection) { AliVVZERO* v0 = fInputEvent->GetVZEROData(); Bool_t bV0AND = ((v0->GetV0ADecision()==1) && (v0->GetV0CDecision()==1)); //bV0AND = fTriggerAnalysis->IsOfflineTriggerFired((AliESDEvent*)fInputEvent, AliTriggerAnalysis::kV0AND); //printf("V0AND event? %d\n",bV0AND); if(!bV0AND) { AliDebug(1,"Reject event by V0AND"); return kFALSE; } AliDebug(1,"Pass V0AND event rejection"); fhNEventsAfterCut->Fill(13.5); } //------------------------------------------------------ // Check if there is a centrality value, PbPb analysis, // and if a centrality bin selection is requested //------------------------------------------------------ //If we need a centrality bin, we select only those events in the corresponding bin. Int_t cen = -1; if ( fCentralityBin[0] >= 0 && fCentralityBin[1] >= 0 ) { cen = GetEventCentrality(); if(cen > fCentralityBin[1] || cen <= fCentralityBin[0]) return kFALSE; //reject events out of bin. AliDebug(1,"Pass centrality rejection"); fhNEventsAfterCut->Fill(14.5); } //---------------------------------------------------------------- // Reject the event if the event header name is not // the one requested among the possible generators. // Needed in case of cocktail MC generation with multiple options. //---------------------------------------------------------------- if(fMCGenerEventHeaderToAccept!="") { if(!GetGenEventHeader()) return kFALSE; AliDebug(1,"Pass Event header selection"); fhNEventsAfterCut->Fill(15.5); } //--------------------------------------------------------------------------- // In case of analysis of events with jets, skip those with jet pt > 5 pt hard // To be used on for MC data in pT hard bins //--------------------------------------------------------------------------- if(fComparePtHardAndJetPt) { if(!ComparePtHardAndJetPt()) return kFALSE ; AliDebug(1,"Pass Pt Hard - Jet rejection"); fhNEventsAfterCut->Fill(16.5); } if(fComparePtHardAndClusterPt) { if(!ComparePtHardAndClusterPt()) return kFALSE ; AliDebug(1,"Pass Pt Hard - Cluster rejection"); fhNEventsAfterCut->Fill(17.5); } //------------------------------------------------------------------ // Recover the weight assigned to the event, if provided // right now only for pT-hard bins and centrality depedent weights //------------------------------------------------------------------ if ( fWeightUtils->IsWeightSettingOn() ) { fWeightUtils->SetCentrality(cen); fWeightUtils->SetPythiaEventHeader(((AliGenPythiaEventHeader*)GetGenEventHeader())); fEventWeight = fWeightUtils->GetWeight(); } //------------------------------------------------------- // Get the main vertex BC, in case not available // it is calculated in FillCTS checking the BC of tracks //------------------------------------------------------ fVertexBC = fInputEvent->GetPrimaryVertex()->GetBC(); //----------------------------------------------- // Fill the arrays with cluster/tracks/cells data //----------------------------------------------- if(fFillCTS) { FillInputCTS(); //Accept events with at least one track if(fTrackMult[0] == 0 && fDoRejectNoTrackEvents) return kFALSE ; AliDebug(1,"Pass rejection of null track events"); fhNEventsAfterCut->Fill(18.5); } if(fDoVertexBCEventSelection) { if(fVertexBC != 0 && fVertexBC != AliVTrack::kTOFBCNA) return kFALSE ; AliDebug(1,"Pass rejection of events with vertex at BC!=0"); fhNEventsAfterCut->Fill(19.5); } if(fFillEMCALCells) FillInputEMCALCells(); if(fFillPHOSCells) FillInputPHOSCells(); if(fFillEMCAL || fFillDCAL) FillInputEMCAL(); if(fFillPHOS) FillInputPHOS(); FillInputVZERO(); //one specified jet branch if(fFillInputNonStandardJetBranch) FillInputNonStandardJets(); if(fFillInputBackgroundJetBranch) FillInputBackgroundJets(); AliDebug(1,"Event accepted for analysis"); return kTRUE ; } //__________________________________________________ /// \return Current event centrality bin. /// Different percentile options and centrality class can be requested. //__________________________________________________ Int_t AliCaloTrackReader::GetEventCentrality() const { if(fUseAliCentrality) { if ( !GetCentrality() ) return -1; AliDebug(1,Form("Cent. Percentile: V0M %2.2f, CL0 %2.2f, CL1 %2.2f; selected class %s", GetCentrality()->GetCentralityPercentile("V0M"), GetCentrality()->GetCentralityPercentile("CL0"), GetCentrality()->GetCentralityPercentile("CL1"), fCentralityClass.Data())); if (fCentralityOpt == 100) return (Int_t) GetCentrality()->GetCentralityPercentile(fCentralityClass); // 100 bins max else if(fCentralityOpt == 10) return GetCentrality()->GetCentralityClass10(fCentralityClass);// 10 bins max else if(fCentralityOpt == 20) return GetCentrality()->GetCentralityClass5(fCentralityClass); // 20 bins max else { AliInfo(Form("Unknown centrality option %d, use 10, 20 or 100\n",fCentralityOpt)); return -1; } } else { if ( !GetMultSelCen() ) return -1; AliDebug(1,Form("Mult. Percentile: V0M %2.2f, CL0 %2.2f, CL1 %2.2f; selected class %s", GetMultSelCen()->GetMultiplicityPercentile("V0M",1), GetMultSelCen()->GetMultiplicityPercentile("CL0",1), GetMultSelCen()->GetMultiplicityPercentile("CL1",1), fCentralityClass.Data())); return GetMultSelCen()->GetMultiplicityPercentile(fCentralityClass, kTRUE); // returns centrality only for events used in calibration // equivalent to //GetMultSelCen()->GetMultiplicityPercentile("V0M", kFALSE); // returns centrality for any event //Int_t qual = GetMultSelCen()->GetEvSelCode(); if (qual ! = 0) cent = qual; } } //_____________________________________________________ /// \return Current event plane angle. /// Different methods options can be requested. //_____________________________________________________ Double_t AliCaloTrackReader::GetEventPlaneAngle() const { if( !GetEventPlane() ) return -1000; Float_t ep = GetEventPlane()->GetEventplane(GetEventPlaneMethod(), GetInputEvent()); if(GetEventPlaneMethod()=="Q" && (ep < 0 || ep > TMath::Pi())) { AliDebug(1,Form("Bad EP for <Q> method : %f\n",ep)); return -1000; } else if(GetEventPlaneMethod().Contains("V0") ) { if((ep > TMath::Pi()/2 || ep < -TMath::Pi()/2)) { AliDebug(1,Form("Bad EP for <%s> method : %f\n",GetEventPlaneMethod().Data(), ep)); return -1000; } ep+=TMath::Pi()/2; // put same range as for <Q> method } AliDebug(3,Form("Event plane angle %f",ep)); // if(fDebug > 0 ) // { // if (ep > TMath::Pi()) printf("AliCaloTrackReader::GetEventPlaneAngle() - Too large angle = %f\n",ep); // else if(ep < 0 ) printf("AliCaloTrackReader::GetEventPlaneAngle() - Negative angle = %f\n" ,ep); // } return ep; } //__________________________________________________________ /// \return Vertex position to be used for single event analysis. //__________________________________________________________ void AliCaloTrackReader::GetVertex(Double_t vertex[3]) const { vertex[0] = fVertex[0][0]; vertex[1] = fVertex[0][1]; vertex[2] = fVertex[0][2]; } //__________________________________________________________________________ /// \return Vertex position for mixed event, recover the vertex in a particular event. //__________________________________________________________________________ void AliCaloTrackReader::GetVertex(Double_t vertex[3], Int_t evtIndex) const { vertex[0] = fVertex[evtIndex][0]; vertex[1] = fVertex[evtIndex][1]; vertex[2] = fVertex[evtIndex][2]; } //________________________________________ /// Fill data member fVertex. /// In case of Mixed event, multiple vertices. //________________________________________ void AliCaloTrackReader::FillVertexArray() { // Delete previous vertex if(fVertex) { for (Int_t i = 0; i < fNMixedEvent; i++) { delete [] fVertex[i] ; } delete [] fVertex ; } fVertex = new Double_t*[fNMixedEvent] ; for (Int_t i = 0; i < fNMixedEvent; i++) { fVertex[i] = new Double_t[3] ; fVertex[i][0] = 0.0 ; fVertex[i][1] = 0.0 ; fVertex[i][2] = 0.0 ; } if (!fMixedEvent) { // Single event analysis if(fDataType!=kMC) { if(fInputEvent->GetPrimaryVertex()) { fInputEvent->GetPrimaryVertex()->GetXYZ(fVertex[0]); } else { AliWarning("NULL primary vertex"); fVertex[0][0]=0.; fVertex[0][1]=0.; fVertex[0][2]=0.; }//Primary vertex pointer do not exist } else {// MC read event fVertex[0][0]=0.; fVertex[0][1]=0.; fVertex[0][2]=0.; } AliDebug(1,Form("Single Event Vertex : %f,%f,%f\n",fVertex[0][0],fVertex[0][1],fVertex[0][2])); } else { // MultiEvent analysis for (Int_t iev = 0; iev < fNMixedEvent; iev++) { if (fMixedEvent->GetVertexOfEvent(iev)) fMixedEvent->GetVertexOfEvent(iev)->GetXYZ(fVertex[iev]); else AliWarning("No vertex found"); AliDebug(1,Form("Multi Event %d Vertex : %f,%f,%f",iev,fVertex[iev][0],fVertex[iev][1],fVertex[iev][2])); } } } //_____________________________________ /// Fill the array with Central Tracking System (CTS) /// filtered tracks. To select the tracks, kinematic cuts, DCA, /// re-fit status and timing cuts are applied. /// Other more ESD/AOD dependent cuts are applied in *SelectTrack()* method, /// see AliCaloTrackAODReader and AliCaloTrackESDReader. //_____________________________________ void AliCaloTrackReader::FillInputCTS() { AliDebug(1,"Begin"); Double_t pTrack[3] = {0,0,0}; Int_t nTracks = fInputEvent->GetNumberOfTracks() ; Int_t nstatus = 0; Double_t bz = GetInputEvent()->GetMagneticField(); for(Int_t i = 0; i < 19; i++) { fTrackBCEvent [i] = 0; fTrackBCEventCut[i] = 0; } for(Int_t iptCut = 0; iptCut < fTrackMultNPtCut; iptCut++ ) { fTrackMult [iptCut] = 0; fTrackSumPt[iptCut] = 0; } Bool_t bc0 = kFALSE; if(fRecalculateVertexBC) fVertexBC = AliVTrack::kTOFBCNA; for (Int_t itrack = 0; itrack < nTracks; itrack++) {////////////// track loop AliVTrack * track = (AliVTrack*)fInputEvent->GetTrack(itrack) ; // retrieve track from esd if ( !AcceptParticleMCLabel( TMath::Abs(track->GetLabel()) ) ) continue ; fhCTSTrackCutsPt[0]->Fill(track->Pt()); //Select tracks under certain conditions, TPCrefit, ITSrefit ... check the set bits ULong_t status = track->GetStatus(); if (fTrackStatus && !((status & fTrackStatus) == fTrackStatus)) continue ; fhCTSTrackCutsPt[1]->Fill(track->Pt()); nstatus++; //------------------------- // Select the tracks depending on cuts of AOD or ESD if(!SelectTrack(track, pTrack)) continue ; fhCTSTrackCutsPt[2]->Fill(track->Pt()); //------------------------- // TOF cuts Bool_t okTOF = ( (status & AliVTrack::kTOFout) == AliVTrack::kTOFout ) ; Double_t tof = -1000; Int_t trackBC = -1000 ; if(fAccessTrackTOF) { if(okTOF) { trackBC = track->GetTOFBunchCrossing(bz); SetTrackEventBC(trackBC+9); tof = track->GetTOFsignal()*1e-3; //After selecting tracks with small DCA, pointing to vertex, set vertex BC depeding on tracks BC if(fRecalculateVertexBC) { if (trackBC != 0 && trackBC != AliVTrack::kTOFBCNA) fVertexBC = trackBC; else if(trackBC == 0) bc0 = kTRUE; } //In any case, the time should to be larger than the fixed window ... if( fUseTrackTimeCut && (trackBC !=0 || tof < fTrackTimeCutMin || tof > fTrackTimeCutMax) ) { //printf("Remove track time %f and bc = %d\n",tof,trackBC); continue ; } //else printf("Accept track time %f and bc = %d\n",tof,trackBC); } } fhCTSTrackCutsPt[3]->Fill(track->Pt()); //--------------------- // DCA cuts // fMomentum.SetPxPyPzE(pTrack[0],pTrack[1],pTrack[2],0); if(fUseTrackDCACut) { Float_t dcaTPC =-999; //In case of AODs, TPC tracks cannot be propagated back to primary vertex, if( fDataType == kAOD ) dcaTPC = ((AliAODTrack*) track)->DCA(); //normal way to get the dca, cut on dca_xy if(dcaTPC==-999) { Double_t dca[2] = {1e6,1e6}; Double_t covar[3] = {1e6,1e6,1e6}; Bool_t okDCA = track->PropagateToDCA(fInputEvent->GetPrimaryVertex(),bz,100.,dca,covar); if( okDCA) okDCA = AcceptDCA(fMomentum.Pt(),dca[0]); if(!okDCA) { //printf("AliCaloTrackReader::FillInputCTS() - Reject track pt %2.2f, dca_xy %2.4f\n",fMomentum.Pt(),dca[0]); continue ; } } }// DCA cuts fhCTSTrackCutsPt[4]->Fill(track->Pt()); //------------------------- // Kinematic/acceptance cuts // // Count the tracks in eta < 0.9 and different pT cuts Float_t ptTrack = fMomentum.Pt(); if(TMath::Abs(track->Eta())< fTrackMultEtaCut) { for(Int_t iptCut = 0; iptCut < fTrackMultNPtCut; iptCut++ ) { if(ptTrack > fTrackMultPtCut[iptCut]) { fTrackMult [iptCut]++; fTrackSumPt[iptCut]+=ptTrack; } } } if(fCTSPtMin > ptTrack || fCTSPtMax < ptTrack) continue ; // Check effect of cuts on track BC if(fAccessTrackTOF && okTOF) SetTrackEventBCcut(trackBC+9); if(fCheckFidCut && !fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kCTS)) continue; fhCTSTrackCutsPt[5]->Fill(track->Pt()); // ------------------------------ // Add selected tracks to array AliDebug(2,Form("Selected tracks pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); fCTSTracks->Add(track); // TODO, check if remove if (fMixedEvent) track->SetID(itrack); }// track loop if( fRecalculateVertexBC && (fVertexBC == 0 || fVertexBC == AliVTrack::kTOFBCNA)) { if( bc0 ) fVertexBC = 0 ; else fVertexBC = AliVTrack::kTOFBCNA ; } AliDebug(1,Form("CTS entries %d, input tracks %d, pass status %d, multipliticy %d", fCTSTracks->GetEntriesFast(), nTracks, nstatus, fTrackMult[0]));//fCTSTracksNormalInputEntries); } //_______________________________________________________________________________ /// Correct, if requested, and select here the EMCal cluster. /// If selected add it to the EMCal clusters array. /// The actions taken are: /// /// * If requested, recalibrate and recalculate most of the cluster parameters (careful not to be done if tender applied or other tasks executed after) /// * Select clusters without bad channels, exotic channels or close to borders /// * If requested, correct cluster non linearity (careful not to be done if tender applied or other tasks executed after) /// * Select clusters within an energy window and passing fiducial cuts /// * Select clusters within a time window /// * Select clusters with a minimum number of cells and not too close to a bad channel /// * Smear the shower shape, to be done only for MC /// * Besides, some counters on the number of clusters with time in different BC are stored /// /// \param clus: AliVCaloCluster pointer /// \param iclus: cluster index, only needed in case of mixing frame (not used recently) /// /// Method called by *FillInputEMCAL()* //_______________________________________________________________________________ void AliCaloTrackReader::FillInputEMCALAlgorithm(AliVCluster * clus, Int_t iclus) { // Accept clusters with the proper label, only applicable for MC if ( clus->GetLabel() >= 0 ) // -1 corresponds to noisy MC { if ( !AcceptParticleMCLabel(clus->GetLabel()) ) return ; } // TODO, not sure if needed anymore Int_t vindex = 0 ; if (fMixedEvent) vindex = fMixedEvent->EventIndexForCaloCluster(iclus); clus->GetMomentum(fMomentum, fVertex[vindex]); // No correction/cut applied yet fhEMCALClusterCutsE[0]->Fill(clus->E()); //if( (fDebug > 2 && fMomentum.E() > 0.1) || fDebug > 10 ) AliDebug(2,Form("Input cluster E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); //--------------------------- // Embedding case // TO BE REVISED if(fSelectEmbeddedClusters) { if(clus->GetNLabels()==0 || clus->GetLabel() < 0) return; //else printf("Embedded cluster, %d, n label %d label %d \n",iclus,clus->GetNLabels(),clus->GetLabel()); } //-------------------------------------- // Apply some corrections in the cluster // if(fRecalculateClusters) { //Recalibrate the cluster energy if(GetCaloUtils()->IsRecalibrationOn()) { Float_t energy = GetCaloUtils()->RecalibrateClusterEnergy(clus, GetEMCALCells()); clus->SetE(energy); //printf("Recalibrated Energy %f\n",clus->E()); GetCaloUtils()->RecalculateClusterShowerShapeParameters(GetEMCALCells(),clus); GetCaloUtils()->RecalculateClusterPID(clus); } // recalculate E //Recalculate distance to bad channels, if new list of bad channels provided GetCaloUtils()->RecalculateClusterDistanceToBadChannel(GetEMCALCells(),clus); //Recalculate cluster position if(GetCaloUtils()->IsRecalculationOfClusterPositionOn()) { GetCaloUtils()->RecalculateClusterPosition(GetEMCALCells(),clus); //clus->GetPosition(pos); //printf("After Corrections: e %f, x %f, y %f, z %f\n",clus->E(),pos[0],pos[1],pos[2]); } // Recalculate TOF if(GetCaloUtils()->GetEMCALRecoUtils()->IsTimeRecalibrationOn()) { Double_t tof = clus->GetTOF(); Float_t frac =-1; Int_t absIdMax = GetCaloUtils()->GetMaxEnergyCell(fEMCALCells, clus,frac); GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTime(absIdMax,fInputEvent->GetBunchCrossNumber(),tof); //additional L1 phase shift if(GetCaloUtils()->GetEMCALRecoUtils()->IsL1PhaseInTimeRecalibrationOn()) { GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTimeL1Phase(GetCaloUtils()->GetEMCALGeometry()->GetSuperModuleNumber(absIdMax), fInputEvent->GetBunchCrossNumber(), tof); } clus->SetTOF(tof); }// Time recalibration } // Check effect of corrections fhEMCALClusterCutsE[1]->Fill(clus->E()); //----------------------------------------------------------------- // Reject clusters with bad channels, close to borders and exotic // Bool_t goodCluster = GetCaloUtils()->GetEMCALRecoUtils()->IsGoodCluster(clus, GetCaloUtils()->GetEMCALGeometry(), GetEMCALCells(),fInputEvent->GetBunchCrossNumber()); if(!goodCluster) { //if( (fDebug > 2 && fMomentum.E() > 0.1) || fDebug > 10 ) AliDebug(1,Form("Bad cluster E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); return; } // Check effect of bad cluster removal fhEMCALClusterCutsE[2]->Fill(clus->E()); //Float_t pos[3]; //clus->GetPosition(pos); //printf("Before Corrections: e %f, x %f, y %f, z %f\n",clus->E(),pos[0],pos[1],pos[2]); //-------------------------------------- // Correct non linearity or smear energy // if(fCorrectELinearity && GetCaloUtils()->IsCorrectionOfClusterEnergyOn()) { GetCaloUtils()->CorrectClusterEnergy(clus) ; //if( (fDebug > 5 && fMomentum.E() > 0.1) || fDebug > 10 ) AliDebug(5,Form("Correct Non Lin: Old E %3.2f, New E %3.2f", fMomentum.E(),clus->E())); // In case of MC analysis, to match resolution/calibration in real data // Not needed anymore, just leave for MC studies on systematics if( GetCaloUtils()->GetEMCALRecoUtils()->IsClusterEnergySmeared() ) { Float_t rdmEnergy = GetCaloUtils()->GetEMCALRecoUtils()->SmearClusterEnergy(clus); //if( (fDebug > 5 && fMomentum.E() > 0.1) || fDebug > 10 ) AliDebug(5,Form("Smear energy: Old E %3.2f, New E %3.2f",clus->E(),rdmEnergy)); clus->SetE(rdmEnergy); } } clus->GetMomentum(fMomentum, fVertex[vindex]); // Check effect linearity correction, energy smearing fhEMCALClusterCutsE[3]->Fill(clus->E()); // Check the event BC depending on EMCal clustr before final cuts Double_t tof = clus->GetTOF()*1e9; Int_t bc = TMath::Nint(tof/50) + 9; //printf("tof %2.2f, bc+5=%d\n",tof,bc); SetEMCalEventBC(bc); //-------------------------------------- // Apply some kinematical/acceptance cuts // if(fEMCALPtMin > clus->E() || fEMCALPtMax < clus->E()) return ; // Select cluster fiducial region // Bool_t bEMCAL = kFALSE; Bool_t bDCAL = kFALSE; if(fCheckFidCut) { if(fFillEMCAL && fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kEMCAL)) bEMCAL = kTRUE ; if(fFillDCAL && fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kDCAL )) bDCAL = kTRUE ; } else { bEMCAL = kTRUE; } //--------------------------------------------------------------------- // Mask all cells in collumns facing ALICE thick material if requested // if(GetCaloUtils()->GetNMaskCellColumns()) { Int_t absId = -1; Int_t iSupMod = -1; Int_t iphi = -1; Int_t ieta = -1; Bool_t shared = kFALSE; GetCaloUtils()->GetEMCALRecoUtils()->GetMaxEnergyCell(GetCaloUtils()->GetEMCALGeometry(), GetEMCALCells(),clus,absId,iSupMod,ieta,iphi,shared); AliDebug(2,Form("Masked collumn: cluster E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); if(GetCaloUtils()->MaskFrameCluster(iSupMod, ieta)) return; } // Check effect of energy and fiducial cuts fhEMCALClusterCutsE[4]->Fill(clus->E()); //---------------------------------------------------- // Apply N cells cut // if(clus->GetNCells() <= fEMCALNCellsCut && fDataType != AliCaloTrackReader::kMC) return ; // Check effect of n cells cut fhEMCALClusterCutsE[5]->Fill(clus->E()); //---------------------------------------------------- // Apply distance to bad channel cut // Double_t distBad = clus->GetDistanceToBadChannel() ; //Distance to bad channel if(distBad < 0.) distBad=9999. ; //workout strange convension dist = -1. ; if(distBad < fEMCALBadChMinDist) return ; // Check effect distance to bad channel cut fhEMCALClusterCutsE[6]->Fill(clus->E()); //------------------------------------------ // Apply time cut, count EMCal BC before cut // SetEMCalEventBCcut(bc); // Shift time in case of no calibration with rough factor Double_t tofShift = tof; if(tof > 400) tofShift-=615; fhEMCALClusterTimeE->Fill(clus->E(),tofShift); if(!IsInTimeWindow(tof,clus->E())) { fNPileUpClusters++ ; if(fUseEMCALTimeCut) { AliDebug(2,Form("Out of time window E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f, time %e", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta(),tof)); return ; } } else fNNonPileUpClusters++; // Check effect of time cut fhEMCALClusterCutsE[7]->Fill(clus->E()); //---------------------------------------------------- // Smear the SS to try to match data and simulations, // do it only for simulations. // Int_t nMaxima = GetCaloUtils()->GetNumberOfLocalMaxima(clus, GetEMCALCells()); // Int_t nMaxima = clus->GetNExMax(); // For Run2 if( fSmearShowerShape && clus->GetNCells() > 2 && nMaxima >= fSmearNLMMin && nMaxima <= fSmearNLMMax ) { AliDebug(2,Form("Smear shower shape - Original: %2.4f\n", clus->GetM02())); if(fSmearingFunction == kSmearingLandau) { clus->SetM02( clus->GetM02() + fRandom.Landau(0, fSmearShowerShapeWidth) ); } else if(fSmearingFunction == kSmearingLandauShift) { if(iclus%3 == 0 && clus->GetM02() > 0.1) clus->SetM02( clus->GetM02() + fRandom.Landau(0.05, fSmearShowerShapeWidth) ); //fSmearShowerShapeWidth = 0.035 } else if (fSmearingFunction == kNoSmearing) { clus->SetM02( clus->GetM02() ); } //clus->SetM02( fRandom.Landau(clus->GetM02(), fSmearShowerShapeWidth) ); AliDebug(2,Form("Width %2.4f Smeared : %2.4f\n", fSmearShowerShapeWidth,clus->GetM02())); } //-------------------------------------------------------- // Fill the corresponding array with the selected clusters // Usually just filling EMCal array with upper or lower clusters is enough, // but maybe we want to do EMCal-DCal correlations. //if((fDebug > 2 && fMomentum.E() > 0.1) || fDebug > 10) AliDebug(2,Form("Selected clusters (EMCAL%d, DCAL%d), E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", bEMCAL,bDCAL,fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); if (bEMCAL) fEMCALClusters->Add(clus); else if(bDCAL ) fDCALClusters ->Add(clus); // TODO, not sure if needed anymore if (fMixedEvent) clus->SetID(iclus) ; } //_______________________________________ /// Fill the array with EMCAL clusters. /// Source of clusters can be different, /// external branch, output of some other /// analysis task or the standard. /// External branch is requested when providing /// its name in *fEMCALClustersListName*. //_______________________________________ void AliCaloTrackReader::FillInputEMCAL() { AliDebug(1,"Begin"); // First recalibrate cells, time or energy // if(GetCaloUtils()->IsRecalibrationOn()) // GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCells(GetCaloUtils()->GetEMCALGeometry(), // GetEMCALCells(), // fInputEvent->GetBunchCrossNumber()); fNPileUpClusters = 0; // Init counter fNNonPileUpClusters = 0; // Init counter for(Int_t i = 0; i < 19; i++) { fEMCalBCEvent [i] = 0; fEMCalBCEventCut[i] = 0; } //Loop to select clusters in fiducial cut and fill container with aodClusters if(fEMCALClustersListName=="") { Int_t nclusters = fInputEvent->GetNumberOfCaloClusters(); for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = 0; if ( (clus = fInputEvent->GetCaloCluster(iclus)) ) { if (clus->IsEMCAL()) { FillInputEMCALAlgorithm(clus, iclus); }//EMCAL cluster }// cluster exists }// cluster loop //Recalculate track matching GetCaloUtils()->RecalculateClusterTrackMatching(fInputEvent,0x0,fMC); }//Get the clusters from the input event else { TClonesArray * clusterList = 0x0; if (fInputEvent->FindListObject(fEMCALClustersListName)) { clusterList = dynamic_cast<TClonesArray*> (fInputEvent->FindListObject(fEMCALClustersListName)); } else if(fOutputEvent) { clusterList = dynamic_cast<TClonesArray*> (fOutputEvent->FindListObject(fEMCALClustersListName)); } if(!clusterList) { AliWarning(Form("Wrong name of list with clusters? <%s>",fEMCALClustersListName.Data())); return; } Int_t nclusters = clusterList->GetEntriesFast(); for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = dynamic_cast<AliVCluster*> (clusterList->At(iclus)); //printf("E %f\n",clus->E()); if (clus) FillInputEMCALAlgorithm(clus, iclus); else AliWarning("Null cluster in list!"); }// cluster loop // Recalculate the pile-up time, in case long time clusters removed during clusterization //printf("Input event INIT : Pile-up clusters %d, NO pile-up %d\n",fNPileUpClusters,fNNonPileUpClusters); fNPileUpClusters = 0; // Init counter fNNonPileUpClusters = 0; // Init counter for(Int_t i = 0; i < 19; i++) { fEMCalBCEvent [i] = 0; fEMCalBCEventCut[i] = 0; } for (Int_t iclus = 0; iclus < fInputEvent->GetNumberOfCaloClusters(); iclus++) { AliVCluster * clus = 0; if ( (clus = fInputEvent->GetCaloCluster(iclus)) ) { if (clus->IsEMCAL()) { Float_t frac =-1; Int_t absIdMax = GetCaloUtils()->GetMaxEnergyCell(fEMCALCells, clus,frac); Double_t tof = clus->GetTOF(); GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTime(absIdMax,fInputEvent->GetBunchCrossNumber(),tof); //additional L1 phase shift if(GetCaloUtils()->GetEMCALRecoUtils()->IsL1PhaseInTimeRecalibrationOn()) { GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTimeL1Phase(GetCaloUtils()->GetEMCALGeometry()->GetSuperModuleNumber(absIdMax), fInputEvent->GetBunchCrossNumber(), tof); } tof*=1e9; //printf("Input event cluster : AbsIdMax %d, E %2.2f, time %2.2f \n", absIdMax,clus->E(),tof); //Reject clusters with bad channels, close to borders and exotic; if(!GetCaloUtils()->GetEMCALRecoUtils()->IsGoodCluster(clus,GetCaloUtils()->GetEMCALGeometry(),GetEMCALCells(),fInputEvent->GetBunchCrossNumber())) continue; Int_t bc = TMath::Nint(tof/50) + 9; SetEMCalEventBC(bc); if(fEMCALPtMin > clus->E() || fEMCALPtMax < clus->E()) continue ; clus->GetMomentum(fMomentum, fVertex[0]); if(fCheckFidCut && !fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kEMCAL)) return ; SetEMCalEventBCcut(bc); if(!IsInTimeWindow(tof,clus->E())) fNPileUpClusters++ ; else fNNonPileUpClusters++; } } } //printf("Input event : Pile-up clusters %d, NO pile-up %d\n",fNPileUpClusters,fNNonPileUpClusters); // Recalculate track matching, not necessary if already done in the reclusterization task. // in case it was not done ... GetCaloUtils()->RecalculateClusterTrackMatching(fInputEvent,clusterList,fMC); } AliDebug(1,Form("EMCal selected clusters %d", fEMCALClusters->GetEntriesFast())); AliDebug(2,Form("\t n pile-up clusters %d, n non pile-up %d", fNPileUpClusters,fNNonPileUpClusters)); } //_______________________________________ /// Fill the array with PHOS filtered clusters. //_______________________________________ void AliCaloTrackReader::FillInputPHOS() { AliDebug(1,"Begin"); // Loop to select clusters in fiducial cut and fill container with aodClusters Int_t nclusters = fInputEvent->GetNumberOfCaloClusters(); TString genName; for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = fInputEvent->GetCaloCluster(iclus) ; if ( !clus ) continue ; if ( !clus->IsPHOS() ) continue ; if(clus->GetLabel() >=0 ) // -1 corresponds to noisy MC { if ( !AcceptParticleMCLabel(clus->GetLabel()) ) continue ; } fhPHOSClusterCutsE[0]->Fill(clus->E()); // Skip CPV input if( clus->GetType() == AliVCluster::kPHOSCharged ) continue ; fhPHOSClusterCutsE[1]->Fill(clus->E()); //--------------------------------------------- // Old feature, try to rely on PHOS tender // if(fRecalculateClusters) { // Recalibrate the cluster energy if(GetCaloUtils()->IsRecalibrationOn()) { Float_t energy = GetCaloUtils()->RecalibrateClusterEnergy(clus, (AliAODCaloCells*)GetPHOSCells()); clus->SetE(energy); } } //---------------------------------------------------------------------------------- // Check if the cluster contains any bad channel and if close to calorimeter borders // // Old feature, try to rely on PHOS tender if( GetCaloUtils()->ClusterContainsBadChannel(kPHOS,clus->GetCellsAbsId(), clus->GetNCells())) continue; if(!GetCaloUtils()->CheckCellFiducialRegion(clus, fInputEvent->GetPHOSCells())) continue; // TODO, add exotic cut??? fhPHOSClusterCutsE[2]->Fill(clus->E()); // TODO Dead code? remove? Int_t vindex = 0 ; if (fMixedEvent) vindex = fMixedEvent->EventIndexForCaloCluster(iclus); clus->GetMomentum(fMomentum, fVertex[vindex]); //---------------------------------------------------------------------------------- // Remove clusters close to borders // if (fCheckFidCut && !fFiducialCut->IsInFiducialCut(fMomentum.Eta(),fMomentum.Phi(),kPHOS) ) continue ; fhPHOSClusterCutsE[3]->Fill(clus->E()); //---------------------------------------------------------------------------------- // Remove clusters with too low energy // if (fPHOSPtMin > fMomentum.E() || fPHOSPtMax < fMomentum.E() ) continue ; fhPHOSClusterCutsE[4]->Fill(clus->E()); //---------------------------------------------------- // Apply N cells cut // if(clus->GetNCells() <= fPHOSNCellsCut && fDataType != AliCaloTrackReader::kMC) return ; // Check effect of n cells cut fhPHOSClusterCutsE[5]->Fill(clus->E()); //---------------------------------------------------- // Apply distance to bad channel cut // Double_t distBad = clus->GetDistanceToBadChannel() ; //Distance to bad channel if(distBad < 0.) distBad=9999. ; //workout strange convension dist = -1. ; if(distBad < fPHOSBadChMinDist) return ; // Check effect distance to bad channel cut fhPHOSClusterCutsE[6]->Fill(clus->E()); // TODO, add time cut //---------------------------------------------------------------------------------- // Add selected clusters to array // //if(fDebug > 2 && fMomentum.E() > 0.1) AliDebug(2,Form("Selected clusters E %3.2f, pt %3.2f, phi %3.2f deg, eta %3.2f", fMomentum.E(),fMomentum.Pt(),RadToDeg(GetPhi(fMomentum.Phi())),fMomentum.Eta())); fPHOSClusters->Add(clus); // TODO Dead code? remove? if (fMixedEvent) clus->SetID(iclus) ; } // esd/aod cluster loop AliDebug(1,Form("PHOS selected clusters %d",fPHOSClusters->GetEntriesFast())) ; } //____________________________________________ /// Connects the array with EMCAL cells and the pointer. //____________________________________________ void AliCaloTrackReader::FillInputEMCALCells() { fEMCALCells = fInputEvent->GetEMCALCells(); } //___________________________________________ /// Connects the array with PHOS cells and the pointer. //___________________________________________ void AliCaloTrackReader::FillInputPHOSCells() { fPHOSCells = fInputEvent->GetPHOSCells(); } //_______________________________________ /// Fill VZERO information in data member, /// add all the channels information. //_______________________________________ void AliCaloTrackReader::FillInputVZERO() { AliVVZERO* v0 = fInputEvent->GetVZEROData(); //printf("Init V0: ADC (%d,%d), Multiplicity (%d,%d) \n",fV0ADC[0],fV0ADC[1],fV0Mul[0],fV0Mul[1]); if (v0) { AliESDVZERO* esdV0 = dynamic_cast<AliESDVZERO*> (v0); for (Int_t i = 0; i < 32; i++) { if(esdV0) {//Only available in ESDs fV0ADC[0] += (Int_t)esdV0->GetAdcV0C(i); fV0ADC[1] += (Int_t)esdV0->GetAdcV0A(i); } fV0Mul[0] += (Int_t)v0->GetMultiplicityV0C(i); fV0Mul[1] += (Int_t)v0->GetMultiplicityV0A(i); } AliDebug(1,Form("ADC (%d,%d), Multiplicity (%d,%d)",fV0ADC[0],fV0ADC[1],fV0Mul[0],fV0Mul[1])); } else { AliDebug(1,"Cannot retrieve V0 ESD! Run w/ null V0 charges"); } } //_________________________________________________ /// Fill array with non standard jets /// /// Author: Adam T. Matyja //_________________________________________________ void AliCaloTrackReader::FillInputNonStandardJets() { AliDebug(2,"Begin"); // //check if branch name is given if(!fInputNonStandardJetBranchName.Length()) { fInputEvent->Print(); AliFatal("No non-standard jet branch name specified. Specify among existing ones."); } fNonStandardJets = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(fInputNonStandardJetBranchName.Data())); if(!fNonStandardJets) { //check if jet branch exist; exit if not fInputEvent->Print(); AliFatal(Form("%s:%d no reconstructed jet array with name %s in AOD", (char*)__FILE__,__LINE__,fInputNonStandardJetBranchName.Data())); } else { AliDebug(1,Form("AOD input jets %d", fNonStandardJets->GetEntriesFast())); } } //_________________________________________________ /// Fill array with Background jets /// /// Author: Adam T. Matyja //_________________________________________________ void AliCaloTrackReader::FillInputBackgroundJets() { AliDebug(1,"Begin"); // //check if branch name is given if(!fInputBackgroundJetBranchName.Length()) { fInputEvent->Print(); AliFatal("No background jet branch name specified. Specify among existing ones."); } fBackgroundJets = (AliAODJetEventBackground*)(fInputEvent->FindListObject(fInputBackgroundJetBranchName.Data())); if(!fBackgroundJets) { //check if jet branch exist; exit if not fInputEvent->Print(); AliFatal(Form("%s:%d no reconstructed jet array with name %s in AOD", (char*)__FILE__,__LINE__,fInputBackgroundJetBranchName.Data())); } else { AliDebug(1,"FillInputBackgroundJets"); fBackgroundJets->Print(""); } } //____________________________________________________________________ /// Recover the patches that triggered, either L0 or L1. /// /// \param tmin: minimum L0 time bin cut /// \param tmax: maximum L0 time bin cut /// \return TArrayI, array with patches index //____________________________________________________________________ TArrayI AliCaloTrackReader::GetTriggerPatches(Int_t tmin, Int_t tmax ) { // init some variables Int_t trigtimes[30], globCol, globRow,ntimes, i; Int_t absId = -1; //[100]; Int_t nPatch = 0; TArrayI patches(0); // get object pointer AliVCaloTrigger *caloTrigger = GetInputEvent()->GetCaloTrigger( "EMCAL" ); if(!caloTrigger) { AliError("Trigger patches input (AliVCaloTrigger) not available in data!"); return patches; } //printf("CaloTrigger Entries %d\n",caloTrigger->GetEntries() ); // class is not empty if( caloTrigger->GetEntries() > 0 ) { // must reset before usage, or the class will fail caloTrigger->Reset(); // go throuth the trigger channels while( caloTrigger->Next() ) { // get position in global 2x2 tower coordinates caloTrigger->GetPosition( globCol, globRow ); //L0 if(IsEventEMCALL0()) { // get dimension of time arrays caloTrigger->GetNL0Times( ntimes ); // no L0s in this channel // presence of the channel in the iterator still does not guarantee that L0 was produced!! if( ntimes < 1 ) continue; // get timing array caloTrigger->GetL0Times( trigtimes ); //printf("Get L0 patch : n times %d - trigger time window %d - %d\n",ntimes, tmin,tmax); // go through the array for( i = 0; i < ntimes; i++ ) { // check if in cut - 8,9 shall be accepted in 2011 if( trigtimes[i] >= tmin && trigtimes[i] <= tmax ) { //printf("Accepted trigger time %d \n",trigtimes[i]); //if(nTrig > 99) continue; GetCaloUtils()->GetEMCALGeometry()->GetAbsFastORIndexFromPositionInEMCAL(globCol,globRow, absId); //printf("pass the time cut globCol %d, globRow %d absId %d\n",globCol,globRow, absId); patches.Set(nPatch+1); patches.AddAt(absId,nPatch++); } } // trigger time array }//L0 else if(IsEventEMCALL1()) // L1 { Int_t bit = 0; caloTrigger->GetTriggerBits(bit); Int_t sum = 0; caloTrigger->GetL1TimeSum(sum); //fBitEGA-=2; Bool_t isEGA1 = ((bit >> fBitEGA ) & 0x1) && IsEventEMCALL1Gamma1() ; Bool_t isEGA2 = ((bit >> (fBitEGA+1)) & 0x1) && IsEventEMCALL1Gamma2() ; Bool_t isEJE1 = ((bit >> fBitEJE ) & 0x1) && IsEventEMCALL1Jet1 () ; Bool_t isEJE2 = ((bit >> (fBitEJE+1)) & 0x1) && IsEventEMCALL1Jet2 () ; //if((bit>> fBitEGA )&0x1) printf("Trig Bit %d - bit %d - EG1 %d - EG2 %d\n",fBitEGA ,bit,IsEventEMCALL1Gamma1(),IsEventEMCALL1Gamma2()); //if((bit>>(fBitEGA+1))&0x1) printf("Trig Bit %d - bit %d - EG1 %d - EG2 %d\n",fBitEGA+1,bit,IsEventEMCALL1Gamma1(),IsEventEMCALL1Gamma2()); if(!isEGA1 && !isEJE1 && !isEGA2 && !isEJE2) continue; Int_t patchsize = -1; if (isEGA1 || isEGA2) patchsize = 2; else if (isEJE1 || isEJE2) patchsize = 16; //printf("**** Get L1 Patch: Bit %x, sum %d, patchsize %d, EGA1 %d, EGA2 %d, EJE1 %d, EJE2 %d, EGA bit %d, EJE bit %d, Trigger Gamma %d, Trigger Jet %d\n", // bit,sum,patchsize,isEGA1,isEGA2,isEJE1,isEJE2,fBitEGA,fBitEJE,IsEventEMCALL1Gamma(),IsEventEMCALL1Jet()); // add 2x2 (EGA) or 16x16 (EJE) patches for(Int_t irow=0; irow < patchsize; irow++) { for(Int_t icol=0; icol < patchsize; icol++) { GetCaloUtils()->GetEMCALGeometry()->GetAbsFastORIndexFromPositionInEMCAL(globCol+icol,globRow+irow, absId); //printf("pass the time cut globCol %d, globRow %d absId %d\n",globCol,globRow, absId); patches.Set(nPatch+1); patches.AddAt(absId,nPatch++); } } } // L1 } // trigger iterator } // go through triggers if(patches.GetSize()<=0) AliInfo(Form("No patch found! for triggers: %s and selected <%s>", GetFiredTriggerClasses().Data(),fFiredTriggerClassName.Data())); //else printf(">>>>> N patches %d, test %d,first %d, last %d\n",patches.GetSize(), nPatch, patches.At(0), patches.At(patches.GetSize()-1)); return patches; } //____________________________________________________________ /// Finds the cluster that triggered. /// It compares the cells of the trigger patches and /// high energy clusters. //____________________________________________________________ void AliCaloTrackReader::MatchTriggerCluster(TArrayI patches) { // Init info from previous event fTriggerClusterIndex = -1; fTriggerClusterId = -1; fTriggerClusterBC = -10000; fIsExoticEvent = kFALSE; fIsBadCellEvent = kFALSE; fIsBadMaxCellEvent = kFALSE; fIsTriggerMatch = kFALSE; fIsTriggerMatchOpenCut[0] = kFALSE; fIsTriggerMatchOpenCut[1] = kFALSE; fIsTriggerMatchOpenCut[2] = kFALSE; // Do only analysis for triggered events if(!IsEventEMCALL1() && !IsEventEMCALL0()) { fTriggerClusterBC = 0; return; } //printf("***** Try to match trigger to cluster %d **** L0 %d, L1 %d\n",fTriggerPatchClusterMatch,IsEventEMCALL0(),IsEventEMCALL1()); //Recover the list of clusters TClonesArray * clusterList = 0; if (fInputEvent->FindListObject(fEMCALClustersListName)) { clusterList = dynamic_cast<TClonesArray*> (fInputEvent->FindListObject(fEMCALClustersListName)); } else if(fOutputEvent) { clusterList = dynamic_cast<TClonesArray*> (fOutputEvent->FindListObject(fEMCALClustersListName)); } // Get number of clusters and of trigger patches Int_t nclusters = fInputEvent->GetNumberOfCaloClusters(); if(clusterList) nclusters = clusterList->GetEntriesFast(); Int_t nPatch = patches.GetSize(); Float_t exoDiffTime = GetCaloUtils()->GetEMCALRecoUtils()->GetExoticCellDiffTimeCut(); //Init some variables used in the cluster loop Float_t tofPatchMax = 100000; Float_t ePatchMax =-1; Float_t tofMax = 100000; Float_t eMax =-1; Int_t clusMax =-1; Int_t idclusMax =-1; Bool_t badClMax = kFALSE; Bool_t badCeMax = kFALSE; Bool_t exoMax = kFALSE; // Int_t absIdMaxTrig= -1; Int_t absIdMaxMax = -1; Int_t nOfHighECl = 0 ; // // Check what is the trigger threshold // set minimu energym of candidate for trigger cluster // SetEMCALTriggerThresholds(); Float_t triggerThreshold = fTriggerL1EventThreshold; if(IsEventEMCALL0()) triggerThreshold = fTriggerL0EventThreshold; Float_t minE = triggerThreshold / 2.; // This method is not really suitable for JET trigger // but in case, reduce the energy cut since we do not trigger on high energy particle if(IsEventEMCALL1Jet() || minE < 1) minE = 1; AliDebug(1,Form("IsL1Trigger %d, IsL1JetTrigger? %d, IsL0Trigger %d, L1 threshold %2.1f, L0 threshold %2.1f, Min cluster E %2.2f",IsEventEMCALL1Jet(), IsEventEMCALL1(), IsEventEMCALL0(), fTriggerL1EventThreshold,fTriggerL0EventThreshold,minE)); // // Loop on the clusters, check if there is any that falls into one of the patches // for (Int_t iclus = 0; iclus < nclusters; iclus++) { AliVCluster * clus = 0; if(clusterList) clus = (AliVCluster*) clusterList->At(iclus); else clus = fInputEvent->GetCaloCluster(iclus); if ( !clus ) continue ; if ( !clus->IsEMCAL() ) continue ; //Skip clusters with too low energy to be triggering if ( clus->E() < minE ) continue ; Float_t frac = -1; Int_t absIdMax = GetCaloUtils()->GetMaxEnergyCell(fInputEvent->GetEMCALCells(), clus,frac); Bool_t badCluster = GetCaloUtils()->GetEMCALRecoUtils()->ClusterContainsBadChannel(GetCaloUtils()->GetEMCALGeometry(), clus->GetCellsAbsId(),clus->GetNCells()); UShort_t cellMax[] = {(UShort_t) absIdMax}; Bool_t badCell = GetCaloUtils()->GetEMCALRecoUtils()->ClusterContainsBadChannel(GetCaloUtils()->GetEMCALGeometry(),cellMax,1); // if cell is bad, it can happen that time calibration is not available, // when calculating if it is exotic, this can make it to be exotic by default // open it temporarily for this cluster if(badCell) GetCaloUtils()->GetEMCALRecoUtils()->SetExoticCellDiffTimeCut(10000000); Bool_t exotic = GetCaloUtils()->GetEMCALRecoUtils()->IsExoticCluster(clus, fInputEvent->GetEMCALCells()); // Set back the time cut on exotics if(badCell) GetCaloUtils()->GetEMCALRecoUtils()->SetExoticCellDiffTimeCut(exoDiffTime); // Energy threshold for exotic Ecross typically at 4 GeV, // for lower energy, check that there are more than 1 cell in the cluster if(!exotic && clus->GetNCells() < 2) exotic = kTRUE; Float_t energy = clus->E(); Int_t idclus = clus->GetID(); Double_t tof = clus->GetTOF(); if(GetCaloUtils()->GetEMCALRecoUtils()->IsTimeRecalibrationOn() && fTriggerClusterTimeRecal){ GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTime(absIdMax,fInputEvent->GetBunchCrossNumber(),tof); //additional L1 phase shift if(GetCaloUtils()->GetEMCALRecoUtils()->IsL1PhaseInTimeRecalibrationOn()){ GetCaloUtils()->GetEMCALRecoUtils()->RecalibrateCellTimeL1Phase(GetCaloUtils()->GetEMCALGeometry()->GetSuperModuleNumber(absIdMax), fInputEvent->GetBunchCrossNumber(), tof); } } tof *=1.e9; //printf("cluster %d, ID %d, E %2.2f, tof %2.2f, AbsId max %d, exotic %d, bad Cluster %d, bad Cell %d\n", // iclus,idclus, energy,tof,absIdMax, exotic, badCluster,badCell); // Find the highest energy cluster, avobe trigger threshold // in the event in case no match to trigger is found if( energy > eMax ) { tofMax = tof; eMax = energy; badClMax = badCluster; badCeMax = badCell; exoMax = exotic; clusMax = iclus; idclusMax = idclus; absIdMaxMax = absIdMax; } // count the good clusters in the event avobe the trigger threshold // to check the exotic events if(!badCluster && !exotic) nOfHighECl++; // Find match to trigger if(fTriggerPatchClusterMatch && nPatch>0) { for(Int_t iabsId =0; iabsId < nPatch; iabsId++) { Int_t absIDCell[4]; GetCaloUtils()->GetEMCALGeometry()->GetCellIndexFromFastORIndex(patches.At(iabsId), absIDCell); //if(tof > 75 ) printf("E %2.2f TOF %2.2f Trigger patch %d, cells : %d, %d, %d, %d\n", // clus->E(),tof,patches.At(iabsId), absIDCell[0],absIDCell[1],absIDCell[2],absIDCell[3]); for(Int_t ipatch = 0; ipatch < 4; ipatch++) { if(absIdMax == absIDCell[ipatch]) { //printf("*** Patches : absId %d, E %2.1f, tof %f \n",absIdMax,clus->E(), tof); if(energy > ePatchMax) { tofPatchMax = tof; ePatchMax = energy; fIsBadCellEvent = badCluster; fIsBadMaxCellEvent = badCell; fIsExoticEvent = exotic; fTriggerClusterIndex = iclus; fTriggerClusterId = idclus; fIsTriggerMatch = kTRUE; // absIdMaxTrig = absIdMax; } } }// cell patch loop }// trigger patch loop } // Do trigger patch matching }// Cluster loop // If there was no match, assign as trigger // the highest energy cluster in the event if(!fIsTriggerMatch) { tofPatchMax = tofMax; ePatchMax = eMax; fIsBadCellEvent = badClMax; fIsBadMaxCellEvent = badCeMax; fIsExoticEvent = exoMax; fTriggerClusterIndex = clusMax; fTriggerClusterId = idclusMax; } Double_t tofPatchMaxUS = TMath::Abs(tofPatchMax); if (tofPatchMaxUS < 28 ) fTriggerClusterBC = 0 ; else if(tofPatchMaxUS < 75 ) fTriggerClusterBC = 1 ; else if(tofPatchMaxUS < 125) fTriggerClusterBC = 2 ; else if(tofPatchMaxUS < 175) fTriggerClusterBC = 3 ; else if(tofPatchMaxUS < 225) fTriggerClusterBC = 4 ; else if(tofPatchMaxUS < 275) fTriggerClusterBC = 5 ; else { //printf("AliCaloTrackReader::MatchTriggerCluster() - Large BC - tof %2.3f - Index %d\n",tofPatchMaxUS,fTriggerClusterIndex); if(fTriggerClusterIndex >= 0) fTriggerClusterBC = 6 ; else { fTriggerClusterIndex = -2; fTriggerClusterId = -2; } } if(tofPatchMax < 0) fTriggerClusterBC*=-1; // printf("AliCaloTrackReader::MatchTriggerCluster(TArrayI patches) - Trigger cluster: index %d, ID %d, E = %2.2f, tof = %2.2f (BC = %d), bad cluster? %d, bad cell? %d, exotic? %d, patch match? %d, n High E cluster %d, absId Max %d\n", // fTriggerClusterIndex, fTriggerClusterId,ePatchMax, tofPatchMax, // fTriggerClusterBC, fIsBadCellEvent,fIsBadMaxCellEvent,fIsExoticEvent, fIsTriggerMatch, nOfHighECl,absIdMaxMax); // // if(!fIsTriggerMatch) printf("\t highest energy cluster: index %d, ID %d, E = %2.2f, tof = %2.2f, bad cluster? %d, bad cell? %d, exotic? %d\n", // clusMax, idclusMax, eMax,tofMax, badClMax, badCeMax,exoMax); //Redo matching but open cuts if(!fIsTriggerMatch && fTriggerClusterId >= 0) { // Open time patch time TArrayI patchOpen = GetTriggerPatches(7,10); Int_t patchAbsIdOpenTime = -1; for(Int_t iabsId =0; iabsId < patchOpen.GetSize(); iabsId++) { Int_t absIDCell[4]; patchAbsIdOpenTime = patchOpen.At(iabsId); GetCaloUtils()->GetEMCALGeometry()->GetCellIndexFromFastORIndex(patchAbsIdOpenTime, absIDCell); //if(tof > 75 ) printf("E %2.2f TOF %2.2f Trigger patch %d, cells : %d, %d, %d, %d\n", // clus->E(),tof,patches.At(iabsId), absIDCell[0],absIDCell[1],absIDCell[2],absIDCell[3]); for(Int_t ipatch = 0; ipatch < 4; ipatch++) { if(absIdMaxMax == absIDCell[ipatch]) { fIsTriggerMatchOpenCut[0] = kTRUE; break; } }// cell patch loop }// trigger patch loop // Check neighbour patches Int_t patchAbsId = -1; Int_t globalCol = -1; Int_t globalRow = -1; GetCaloUtils()->GetEMCALGeometry()->GetFastORIndexFromCellIndex(absIdMaxMax, patchAbsId); GetCaloUtils()->GetEMCALGeometry()->GetPositionInEMCALFromAbsFastORIndex(patchAbsId,globalCol,globalRow); // Check patches with strict time cut Int_t patchAbsIdNeigh = -1; for(Int_t icol = globalCol-1; icol <= globalCol+1; icol++) { if(icol < 0 || icol > 47) continue; for(Int_t irow = globalRow; irow <= globalRow+1; irow++) { if(irow < 0 || irow > 63) continue; GetCaloUtils()->GetEMCALGeometry()->GetAbsFastORIndexFromPositionInEMCAL(icol, irow, patchAbsIdNeigh); if ( patchAbsIdNeigh < 0 ) continue; for(Int_t iabsId =0; iabsId < patches.GetSize(); iabsId++) { if(patchAbsIdNeigh == patches.At(iabsId)) { fIsTriggerMatchOpenCut[1] = kTRUE; break; } }// trigger patch loop }// row }// col // Check patches with open time cut Int_t patchAbsIdNeighOpenTime = -1; for(Int_t icol = globalCol-1; icol <= globalCol+1; icol++) { if(icol < 0 || icol > 47) continue; for(Int_t irow = globalRow; irow <= globalRow+1; irow++) { if(irow < 0 || irow > 63) continue; GetCaloUtils()->GetEMCALGeometry()->GetAbsFastORIndexFromPositionInEMCAL(icol, irow, patchAbsIdNeighOpenTime); if ( patchAbsIdNeighOpenTime < 0 ) continue; for(Int_t iabsId =0; iabsId < patchOpen.GetSize(); iabsId++) { if(patchAbsIdNeighOpenTime == patchOpen.At(iabsId)) { fIsTriggerMatchOpenCut[2] = kTRUE; break; } }// trigger patch loop }// row }// col // printf("No match, new match: Open time %d-%d, open Neigh %d-%d, both open %d-%d\n",fIsTriggerMatchOpenCut[0],patchAbsIdOpenTime, // fIsTriggerMatchOpenCut[1],patchAbsIdNeigh, // fIsTriggerMatchOpenCut[2],patchAbsIdNeighOpenTime); patchOpen.Reset(); }// No trigger match found //printf("Trigger BC %d, Id %d, Index %d\n",fTriggerClusterBC,fTriggerClusterId,fTriggerClusterIndex); } //_________________________________________________________ /// Recover the EMCal L1 trigger threshold from data. /// Set the EMCal L0 threshold depending on the run number. /// Set the threshold only if requested. //_________________________________________________________ void AliCaloTrackReader::SetEMCALTriggerThresholds() { if(!fTriggerL1EventThresholdFix) { // get object pointer AliVCaloTrigger *caloTrigger = GetInputEvent()->GetCaloTrigger( "EMCAL" ); if ( fBitEGA == 6 ) { if (IsEventEMCALL1Gamma1()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(1); else if(IsEventEMCALL1Gamma2()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(3); else if(IsEventEMCALL1Jet1 ()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(0); else if(IsEventEMCALL1Jet2 ()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(2); // printf("L1 trigger Threshold Jet1 %f, Gamma1 %f, Jet2 %f, Gamma2 %f\n", // 0.07874*caloTrigger->GetL1Threshold(0), // 0.07874*caloTrigger->GetL1Threshold(1), // 0.07874*caloTrigger->GetL1Threshold(2), // 0.07874*caloTrigger->GetL1Threshold(3)); } else { // Old AOD data format, in such case, order of thresholds different!!! if (IsEventEMCALL1Gamma1()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(0); else if(IsEventEMCALL1Gamma2()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(2); else if(IsEventEMCALL1Jet1 ()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(1); else if(IsEventEMCALL1Jet2 ()) fTriggerL1EventThreshold = 0.07874*caloTrigger->GetL1Threshold(3); // printf("L1 trigger Threshold Jet1 %f, Gamma1 %f, Jet2 %f, Gamma2 %f\n", // 0.07874*caloTrigger->GetL1Threshold(1), // 0.07874*caloTrigger->GetL1Threshold(0), // 0.07874*caloTrigger->GetL1Threshold(3), // 0.07874*caloTrigger->GetL1Threshold(2)); } } // Set L0 threshold, if not set by user if( IsEventEMCALL0() && fTriggerL0EventThreshold < 0) { // Revise for periods > LHC11d Int_t runNumber = fInputEvent->GetRunNumber(); if (runNumber < 146861) fTriggerL0EventThreshold = 3. ; // LHC11a else if(runNumber < 154000) fTriggerL0EventThreshold = 4. ; // LHC11b,c else if(runNumber < 165000) fTriggerL0EventThreshold = 5.5; // LHC11c,d,e else if(runNumber < 194000) fTriggerL0EventThreshold = 2 ; // LHC12 else if(runNumber < 197400) fTriggerL0EventThreshold = 3 ; // LHC13def else if(runNumber < 197400) fTriggerL0EventThreshold = 2 ; // LHC13g else if(runNumber < 244300) fTriggerL0EventThreshold = 5 ; // LHC15 in, phys 1, 5 in phys2 else if(runNumber < 266400) fTriggerL0EventThreshold = 2.5; // LHC16ir else fTriggerL0EventThreshold = 3.5; // LHC16s } } //________________________________________________________ /// Print some relevant parameters set for the analysis //________________________________________________________ void AliCaloTrackReader::Print(const Option_t * opt) const { if(! opt) return; printf("***** Print: %s %s ******\n", GetName(), GetTitle() ) ; printf("Task name : %s\n", fTaskName.Data()) ; printf("Data type : %d\n", fDataType) ; printf("CTS Min pT : %2.1f GeV/c\n", fCTSPtMin) ; printf("EMCAL Min pT : %2.1f GeV/c\n", fEMCALPtMin) ; printf("PHOS Min pT : %2.1f GeV/c\n", fPHOSPtMin) ; printf("CTS Max pT : %2.1f GeV/c\n", fCTSPtMax) ; printf("EMCAL Max pT : %2.1f GeV/c\n", fEMCALPtMax) ; printf("PHOS Max pT : %2.1f GeV/c\n", fPHOSPtMax) ; printf("EMCAL Bad Dist > %2.1f \n" , fEMCALBadChMinDist) ; printf("PHOS Bad Dist > %2.1f \n" , fPHOSBadChMinDist) ; printf("EMCAL N cells > %d \n" , fEMCALNCellsCut) ; printf("PHOS N cells > %d \n" , fPHOSNCellsCut) ; printf("EMCAL Time Cut: %3.1f < TOF < %3.1f\n", fEMCALTimeCutMin, fEMCALTimeCutMax); printf("Use CTS = %d\n", fFillCTS) ; printf("Use EMCAL = %d\n", fFillEMCAL) ; printf("Use DCAL = %d\n", fFillDCAL) ; printf("Use PHOS = %d\n", fFillPHOS) ; printf("Use EMCAL Cells = %d\n", fFillEMCALCells) ; printf("Use PHOS Cells = %d\n", fFillPHOSCells) ; printf("Track status = %d\n", (Int_t) fTrackStatus) ; printf("Track Mult Eta Cut = %2.2f\n", fTrackMultEtaCut) ; printf("Track Mult Pt Cuts:") ; for(Int_t icut = 0; icut < fTrackMultNPtCut; icut++) printf(" %2.2f GeV;",fTrackMultPtCut[icut]); printf(" \n") ; printf("Write delta AOD = %d\n", fWriteOutputDeltaAOD) ; printf("Recalculate Clusters = %d, E linearity = %d\n", fRecalculateClusters, fCorrectELinearity) ; printf("Use Triggers selected in SE base class %d; If not what Trigger Mask? %d; MB Trigger Mask for mixed %d \n", fEventTriggerAtSE, fEventTriggerMask,fMixEventTriggerMask); if(fComparePtHardAndJetPt) printf("Compare jet pt and pt hard to accept event, factor = %2.2f",fPtHardAndJetPtFactor); if(fComparePtHardAndClusterPt) printf("Compare cluster pt and pt hard to accept event, factor = %2.2f",fPtHardAndClusterPtFactor); printf("Delta AOD File Name = %s\n", fDeltaAODFileName.Data()) ; printf("Centrality: Class %s, Option %d, Bin [%d,%d] \n", fCentralityClass.Data(),fCentralityOpt,fCentralityBin[0], fCentralityBin[1]) ; printf(" \n") ; } //__________________________________________ /// LED Events in period LHC11a contaminated /// EMCAL clusters sample, simple method /// to reject such events. //__________________________________________ Bool_t AliCaloTrackReader::RejectLEDEvents() { // Count number of cells with energy larger than 0.1 in SM3, cut on this number Int_t ncellsSM3 = 0; for(Int_t icell = 0; icell < fInputEvent->GetEMCALCells()->GetNumberOfCells(); icell++) { Int_t absID = fInputEvent->GetEMCALCells()->GetCellNumber(icell); Int_t sm = GetCaloUtils()->GetEMCALGeometry()->GetSuperModuleNumber(absID); if(fInputEvent->GetEMCALCells()->GetAmplitude(icell) > 0.1 && sm==3) ncellsSM3++; } Int_t ncellcut = 21; if(GetFiredTriggerClasses().Contains("EMC")) ncellcut = 35; if(ncellsSM3 >= ncellcut) { AliDebug(1,Form("Reject event with ncells in SM3 %d, cut %d, trig %s", ncellsSM3,ncellcut,GetFiredTriggerClasses().Data())); return kTRUE; } return kFALSE; } //_________________________________________________________ /// MC label for Cells not remapped after ESD filtering, do it here. /// Needed for old MC/data productions done with AliRoot older /// than v5-02-Rev09 (more or less, not sure) //_________________________________________________________ void AliCaloTrackReader::RemapMCLabelForAODs(Int_t & label) { if(label < 0) return ; AliAODEvent * evt = dynamic_cast<AliAODEvent*> (fInputEvent) ; if(!evt) return ; TClonesArray * arr = dynamic_cast<TClonesArray*>(evt->FindListObject("mcparticles")) ; if(!arr) return ; if(label < arr->GetEntriesFast()) { AliAODMCParticle * particle = dynamic_cast<AliAODMCParticle *>(arr->At(label)); if(!particle) return ; if(label == particle->Label()) return ; // label already OK //else printf("AliCaloTrackReader::RemapMCLabelForAODs() - Label %d - AOD stack %d \n",label, particle->Label()); } //else printf("AliCaloTrackReader::RemapMCLabelForAODs() - Label %d > AOD labels %d \n",label, arr->GetEntriesFast()); // loop on the particles list and check if there is one with the same label for(Int_t ind = 0; ind < arr->GetEntriesFast(); ind++ ) { AliAODMCParticle * particle = dynamic_cast<AliAODMCParticle *>(arr->At(ind)); if(!particle) continue ; if(label == particle->Label()) { label = ind; //printf("AliAnalysisTaskEMCALClusterize::RemapMCLabelForAODs() - New Label Index %d \n",label); return; } } label = -1; //printf("AliCaloTrackReader::RemapMCLabelForAODs() - Label not found set to -1 \n"); } //___________________________________ /// Reset lists, called in AliAnaCaloTrackCorrMaker. //___________________________________ void AliCaloTrackReader::ResetLists() { if(fCTSTracks) fCTSTracks -> Clear(); if(fEMCALClusters) fEMCALClusters -> Clear("C"); if(fPHOSClusters) fPHOSClusters -> Clear("C"); fV0ADC[0] = 0; fV0ADC[1] = 0; fV0Mul[0] = 0; fV0Mul[1] = 0; if(fNonStandardJets) fNonStandardJets -> Clear("C"); fBackgroundJets->Reset(); } //___________________________________________ /// Tag event depending on trigger name. /// Set also the L1 bit defining the EGA or EJE triggers. /// depending on the trigger class version, if not set by user. //___________________________________________ void AliCaloTrackReader::SetEventTriggerBit() { fEventTrigMinBias = kFALSE; fEventTrigCentral = kFALSE; fEventTrigSemiCentral = kFALSE; fEventTrigEMCALL0 = kFALSE; fEventTrigEMCALL1Gamma1 = kFALSE; fEventTrigEMCALL1Gamma2 = kFALSE; fEventTrigEMCALL1Jet1 = kFALSE; fEventTrigEMCALL1Jet2 = kFALSE; AliDebug(1,Form("Select trigger mask bit %d - Trigger Event %s - Select <%s>", fEventTriggerMask,GetFiredTriggerClasses().Data(),fFiredTriggerClassName.Data())); if(fEventTriggerMask <=0 )// in case no mask set { // EMC triggered event? Which type? if( GetFiredTriggerClasses().Contains("-B-") || GetFiredTriggerClasses().Contains("-S-") || GetFiredTriggerClasses().Contains("-I-") ) { if ( GetFiredTriggerClasses().Contains("EGA" ) || GetFiredTriggerClasses().Contains("EG1" ) ) { fEventTrigEMCALL1Gamma1 = kTRUE; if( GetFiredTriggerClasses().Contains("EG1" ) && !fFiredTriggerClassName.Contains("EG1") ) fEventTrigEMCALL1Gamma1 = kFALSE; } else if( GetFiredTriggerClasses().Contains("EG2" ) ) { fEventTrigEMCALL1Gamma2 = kTRUE; if( !fFiredTriggerClassName.Contains("EG2") ) fEventTrigEMCALL1Gamma2 = kFALSE; } else if( GetFiredTriggerClasses().Contains("EJE" ) || GetFiredTriggerClasses().Contains("EJ1" ) ) { fEventTrigEMCALL1Jet1 = kTRUE; if( GetFiredTriggerClasses().Contains("EJ1" ) && !fFiredTriggerClassName.Contains("EJ1") ) fEventTrigEMCALL1Jet1 = kFALSE; } else if( GetFiredTriggerClasses().Contains("EJ2" ) ) { fEventTrigEMCALL1Jet2 = kTRUE; if( !fFiredTriggerClassName.Contains("EJ2") ) fEventTrigEMCALL1Jet2 = kFALSE; } else if( GetFiredTriggerClasses().Contains("CEMC") && !GetFiredTriggerClasses().Contains("EGA" ) && !GetFiredTriggerClasses().Contains("EJE" ) && !GetFiredTriggerClasses().Contains("EG1" ) && !GetFiredTriggerClasses().Contains("EJ1" ) && !GetFiredTriggerClasses().Contains("EG2" ) && !GetFiredTriggerClasses().Contains("EJ2" ) ) { fEventTrigEMCALL0 = kTRUE; } //Min bias event trigger? if (GetFiredTriggerClasses().Contains("CCENT_R2-B-NOPF-ALLNOTRD")) { fEventTrigCentral = kTRUE; } else if(GetFiredTriggerClasses().Contains("CSEMI_R1-B-NOPF-ALLNOTRD")) { fEventTrigSemiCentral = kTRUE; } else if((GetFiredTriggerClasses().Contains("CINT") || GetFiredTriggerClasses().Contains("CPBI2_B1") ) && GetFiredTriggerClasses().Contains("-NOPF-ALLNOTRD") ) { fEventTrigMinBias = kTRUE; } } } else { // EMC L1 Gamma if ( fEventTriggerMask & AliVEvent::kEMCEGA ) { //printf("EGA trigger bit\n"); if (GetFiredTriggerClasses().Contains("EG")) { if (GetFiredTriggerClasses().Contains("EGA")) fEventTrigEMCALL1Gamma1 = kTRUE; else { if(GetFiredTriggerClasses().Contains("EG1")) fEventTrigEMCALL1Gamma1 = kTRUE; if(GetFiredTriggerClasses().Contains("EG2")) fEventTrigEMCALL1Gamma2 = kTRUE; } } } // EMC L1 Jet else if( fEventTriggerMask & AliVEvent::kEMCEJE ) { //printf("EGA trigger bit\n"); if (GetFiredTriggerClasses().Contains("EJ")) { if (GetFiredTriggerClasses().Contains("EJE")) fEventTrigEMCALL1Jet1 = kTRUE; else { if(GetFiredTriggerClasses().Contains("EJ1")) fEventTrigEMCALL1Jet1 = kTRUE; if(GetFiredTriggerClasses().Contains("EJ2")) fEventTrigEMCALL1Jet2 = kTRUE; } } } // EMC L0 else if((fEventTriggerMask & AliVEvent::kEMC7) || (fEventTriggerMask & AliVEvent::kEMC1) ) { //printf("L0 trigger bit\n"); fEventTrigEMCALL0 = kTRUE; } // Min Bias Pb-Pb else if( fEventTriggerMask & AliVEvent::kCentral ) { //printf("MB semi central trigger bit\n"); fEventTrigSemiCentral = kTRUE; } // Min Bias Pb-Pb else if( fEventTriggerMask & AliVEvent::kSemiCentral ) { //printf("MB central trigger bit\n"); fEventTrigCentral = kTRUE; } // Min Bias pp, PbPb, pPb else if((fEventTriggerMask & AliVEvent::kMB ) || (fEventTriggerMask & AliVEvent::kINT7) || (fEventTriggerMask & AliVEvent::kINT8) || (fEventTriggerMask & AliVEvent::kAnyINT) ) { //printf("MB trigger bit\n"); fEventTrigMinBias = kTRUE; } } AliDebug(1,Form("Event bits: \n \t MB %d, Cen %d, Sem %d, L0 %d, L1G1 %d, L1G2 %d, L1J1 %d, L1J2 %d", fEventTrigMinBias, fEventTrigCentral, fEventTrigSemiCentral, fEventTrigEMCALL0 , fEventTrigEMCALL1Gamma1, fEventTrigEMCALL1Gamma2, fEventTrigEMCALL1Jet1 , fEventTrigEMCALL1Jet2)); // L1 trigger bit if( fBitEGA == 0 && fBitEJE == 0 ) { // Init the trigger bit once, correct depending on AliESD(AOD)CaloTrigger header version // Simpler way to do it ... // if( fInputEvent->GetRunNumber() < 172000 ) // reader->SetEventTriggerL1Bit(4,5); // current LHC11 data // else // reader->SetEventTriggerL1Bit(6,8); // LHC12-13 data // Old values fBitEGA = 4; fBitEJE = 5; TFile* file = AliAnalysisManager::GetAnalysisManager()->GetTree()->GetCurrentFile(); const TList *clist = file->GetStreamerInfoCache(); if(clist) { TStreamerInfo *cinfo = (TStreamerInfo*)clist->FindObject("AliESDCaloTrigger"); Int_t verid = 5; // newer ESD header version if(!cinfo) { cinfo = (TStreamerInfo*)clist->FindObject("AliAODCaloTrigger"); verid = 3; // newer AOD header version } if(cinfo) { Int_t classversionid = cinfo->GetClassVersion(); //printf("********* Header class version %d *********** \n",classversionid); if (classversionid >= verid) { fBitEGA = 6; fBitEJE = 8; } } else AliInfo("AliCaloTrackReader()::SetEventTriggerBit() - Streamer info for trigger class not available, bit not changed"); } else AliInfo("AliCaloTrackReader::SetEventTriggerBit() - Streamer list not available!, bit not changed"); } // set once the EJE, EGA trigger bit } //____________________________________________________________ /// Define here the input event and mixed event. /// Called in AliAnaCaloTrackCorrMaker. //____________________________________________________________ void AliCaloTrackReader::SetInputEvent(AliVEvent* const input) { fInputEvent = input; fMixedEvent = dynamic_cast<AliMixedEvent*>(GetInputEvent()) ; if (fMixedEvent) fNMixedEvent = fMixedEvent->GetNumberOfEvents() ; //Delete previous vertex if(fVertex) { for (Int_t i = 0; i < fNMixedEvent; i++) { delete [] fVertex[i] ; } delete [] fVertex ; } fVertex = new Double_t*[fNMixedEvent] ; for (Int_t i = 0; i < fNMixedEvent; i++) { fVertex[i] = new Double_t[3] ; fVertex[i][0] = 0.0 ; fVertex[i][1] = 0.0 ; fVertex[i][2] = 0.0 ; } }
/************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////// // // AliAnalysisTask to extract from ESD tracks the information // on ITS tracking efficiency and resolutions. // // Author: A.Dainese, andrea.dainese@pd.infn.it ///////////////////////////////////////////////////////////// #include <TStyle.h> #include <TChain.h> #include <TTree.h> #include <TNtuple.h> #include <TBranch.h> #include <TClonesArray.h> #include <TObjArray.h> #include <TH1F.h> #include <TH2F.h> #include <TCanvas.h> #include <TParticle.h> #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliMultiplicity.h" #include "AliVertexerTracks.h" #include "AliESDtrack.h" #include "AliExternalTrackParam.h" #include "AliESDVertex.h" #include "AliESDEvent.h" #include "AliESDfriend.h" #include "AliESDInputHandler.h" #include "AliESDInputHandlerRP.h" #include "AliTrackPointArray.h" #include "../ITS/AliITSRecPoint.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliStack.h" #include "AliLog.h" #include "AliGenEventHeader.h" #include "AliAnalysisTaskITSTrackingCheck.h" ClassImp(AliAnalysisTaskITSTrackingCheck) //________________________________________________________________________ AliAnalysisTaskITSTrackingCheck::AliAnalysisTaskITSTrackingCheck(const char *name) : AliAnalysisTask(name, "ITSTrackingCheckTask"), fReadMC(kFALSE), fReadRPLabels(kFALSE), fFillNtuples(kFALSE), fUseITSSAforNtuples(kFALSE), fESD(0), fESDfriend(0), fOutput(0), fHistNtracks(0), fHistNclsITSMI(0), fHistNclsITSSA(0), fHistNclsITSSAInAcc(0), fHistClusterMapITSMI(0), fHistClusterMapITSMIok(0), fHistClusterMapITSMIbad(0), fHistClusterMapITSMIskipped(0), fHistClusterMapITSMIoutinz(0), fHistClusterMapITSMInorefit(0), fHistClusterMapITSMInocls(0), fHistClusterMapITSMIokoutinzbad(0), fHistClusterMapITSSA(0), fHistClusterMapITSSAok(0), fHistClusterMapITSSAbad(0), fHistClusterMapITSSAskipped(0), fHistClusterMapITSSAoutinz(0), fHistClusterMapITSSAnorefit(0), fHistClusterMapITSSAnocls(0), fHistClusterMapITSSAokoutinzbad(0), fHistClusterMapITSSAInAcc(0), fHistClusterMapITSSAokInAcc(0), fHistClusterMapITSSAbadInAcc(0), fHistClusterMapITSSAskippedInAcc(0), fHistClusterMapITSSAoutinzInAcc(0), fHistClusterMapITSSAnorefitInAcc(0), fHistClusterMapITSSAnoclsInAcc(0), fHistClusterMapITSSAokoutinzbadInAcc(0), fHistClusterMapModuleITSSAokInAcc(0), fHistClusterMapModuleITSSAbadInAcc(0), fHistClusterMapModuleITSSAnoclsInAcc(0), fHistPhiTPCInAcc(0), fHistPtTPC(0), fHistPtTPCInAcc(0), fHistPtITSMI2(0), fHistPtITSMI3(0), fHistPtITSMI4(0), fHistPtITSMI5(0), fHistPtITSMI6(0), fHistPtITSMISPD(0), fHistPtITSMIoneSPD(0), fHistPtITSMI2InAcc(0), fHistPtITSMI3InAcc(0), fHistPtITSMI4InAcc(0), fHistPtITSMI5InAcc(0), fHistPtITSMI6InAcc(0), fHistPtITSMISPDInAcc(0), fHistPtITSMIoneSPDInAcc(0), fHistPtITSMIokbadoutinz6(0), fHistPtITSMIokbadoutinz4InAcc(0), fHistPtITSMIokbadoutinz5InAcc(0), fHistPtITSMIokbadoutinz6InAcc(0), fHistPhiITSMIokbadoutinz6InAcc(0), fNtupleESDTracks(0), fNtupleITSAlignExtra(0), fNtupleITSAlignSPDTracklets(0) { // Constructor for(Int_t i=0; i<10; i++) fCountsPerPtBin[i]=0; // Define input and output slots here // Input slot #0 works with a TChain DefineInput(0, TChain::Class()); // Output slot #0 writes into a TList container DefineOutput(0, TList::Class()); //My private output } //________________________________________________________________________ AliAnalysisTaskITSTrackingCheck::~AliAnalysisTaskITSTrackingCheck() { // Destructor // histograms are in the output list and deleted when the output // list is deleted by the TSelector dtor if (fOutput) { delete fOutput; fOutput = 0; } } //________________________________________________________________________ void AliAnalysisTaskITSTrackingCheck::ConnectInputData(Option_t *) { // Connect ESD or AOD here // Called once TTree* tree = dynamic_cast<TTree*> (GetInputData(0)); if (!tree) { Printf("ERROR: Could not read chain from input slot 0"); } else { // Disable all branches and enable only the needed ones // The next two lines are different when data produced as AliESDEvent is read tree->SetBranchStatus("ESDfriend*", 1); tree->SetBranchAddress("ESDfriend.",&fESDfriend); AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!esdH) { Printf("ERROR: Could not get ESDInputHandler"); } else { fESD = esdH->GetEvent(); } } return; } //________________________________________________________________________ void AliAnalysisTaskITSTrackingCheck::CreateOutputObjects() { // Create histograms // Called once gStyle->SetHistLineWidth(2); Int_t nPtBins=21; Float_t xPtBins[22]={0,0.1,0.2,0.3,0.4,0.5,0.6,0.8,1.0,1.5,2.,2.5,3,4,5,6,8,10,15,20,25,30}; for(Int_t i=0; i<10; i++) fCountsPerPtBin[i]=0; // Several histograms are more conveniently managed in a TList fOutput = new TList; fOutput->SetOwner(); fHistNtracks = new TH1F("fHistNtracks", "N ESD tracks; N tracks; Events",5000, -0.5, 4999.5); fHistNtracks->Sumw2(); fHistNtracks->SetMinimum(0); fOutput->Add(fHistNtracks); fHistNclsITSMI = new TH1F("fHistNclsITSMI", "N ITS clusters per track (MI); N clusters; Counts",7, -0.5, 6.5); fHistNclsITSMI->Sumw2(); fHistNclsITSMI->SetMinimum(0); fOutput->Add(fHistNclsITSMI); fHistNclsITSSAInAcc = new TH1F("fHistNclsITSSAInAcc", "N ITS clusters per track (SA); N clusters; Counts",7, -0.5, 6.5); fHistNclsITSSAInAcc->Sumw2(); fHistNclsITSSAInAcc->SetMinimum(0); fOutput->Add(fHistNclsITSSAInAcc); fHistNclsITSSA = new TH1F("fHistNclsITSSA", "N ITS clusters per track (SA); N clusters; Counts",7, -0.5, 6.5); fHistNclsITSSA->Sumw2(); fHistNclsITSSA->SetMinimum(0); fOutput->Add(fHistNclsITSSA); fHistClusterMapITSMI = new TH1F("fHistClusterMapITSMI", "N tracks with point on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMI->Sumw2(); fHistClusterMapITSMI->SetMinimum(0); fOutput->Add(fHistClusterMapITSMI); fHistClusterMapITSSA = new TH1F("fHistClusterMapITSSA", "N tracks with point on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSA->Sumw2(); fHistClusterMapITSSA->SetMinimum(0); fOutput->Add(fHistClusterMapITSSA); fHistClusterMapITSSAInAcc = new TH1F("fHistClusterMapITSSAInAcc", "N tracks with point on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAInAcc->Sumw2(); fHistClusterMapITSSAInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAInAcc); fHistClusterMapITSMIok = new TH1F("fHistClusterMapITSMIok", "N tracks with ok on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIok->Sumw2(); fHistClusterMapITSMIok->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIok); fHistClusterMapITSSAokInAcc = new TH1F("fHistClusterMapITSSAokInAcc", "N tracks with ok on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAokInAcc->Sumw2(); fHistClusterMapITSSAokInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAokInAcc); fHistClusterMapModuleITSSAokInAcc = new TH1F("fHistClusterMapModuleITSSAokInAcc", "N tracks with ok on Module (SA); Module; N tracks",2198, -0.5, 2197.5); fHistClusterMapModuleITSSAokInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapModuleITSSAokInAcc); fHistClusterMapITSSAok = new TH1F("fHistClusterMapITSSAok", "N tracks with ok on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAok->Sumw2(); fHistClusterMapITSSAok->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAok); fHistClusterMapITSMIbad = new TH1F("fHistClusterMapITSMIbad", "N tracks with bad on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIbad->Sumw2(); fHistClusterMapITSMIbad->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIbad); fHistClusterMapITSSAbadInAcc = new TH1F("fHistClusterMapITSSAbadInAcc", "N tracks with bad on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAbadInAcc->Sumw2(); fHistClusterMapITSSAbadInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAbadInAcc); fHistClusterMapModuleITSSAbadInAcc = new TH1F("fHistClusterMapModuleITSSAbadInAcc", "N tracks with bad on Module (SA); Module; N tracks",2198, -0.5, 2197.5); fHistClusterMapModuleITSSAbadInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapModuleITSSAbadInAcc); fHistClusterMapITSSAbad = new TH1F("fHistClusterMapITSSAbad", "N tracks with bad on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAbad->Sumw2(); fHistClusterMapITSSAbad->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAbad); fHistClusterMapITSMIskipped = new TH1F("fHistClusterMapITSMIskipped", "N tracks with skip on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIskipped->Sumw2(); fHistClusterMapITSMIskipped->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIskipped); fHistClusterMapITSSAskippedInAcc = new TH1F("fHistClusterMapITSSAskippedInAcc", "N tracks with skip on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAskippedInAcc->Sumw2(); fHistClusterMapITSSAskippedInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAskippedInAcc); fHistClusterMapITSSAskipped = new TH1F("fHistClusterMapITSSAskipped", "N tracks with skip on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAskipped->Sumw2(); fHistClusterMapITSSAskipped->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAskipped); fHistClusterMapITSMIoutinz = new TH1F("fHistClusterMapITSMIoutinz", "N tracks out in z on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIoutinz->Sumw2(); fHistClusterMapITSMIoutinz->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIoutinz); fHistClusterMapITSSAoutinzInAcc = new TH1F("fHistClusterMapITSSAoutinzInAcc", "N tracks with out in z on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAoutinzInAcc->Sumw2(); fHistClusterMapITSSAoutinzInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAoutinzInAcc); fHistClusterMapITSSAoutinz = new TH1F("fHistClusterMapITSSAoutinz", "N tracks with out in z on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAoutinz->Sumw2(); fHistClusterMapITSSAoutinz->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAoutinz); fHistClusterMapITSSAokoutinzbad = new TH1F("fHistClusterMapITSSAokoutinzbad", "N tracks with cluster or bad zone or out in z (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAokoutinzbad->Sumw2(); fHistClusterMapITSSAokoutinzbad->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAokoutinzbad); fHistClusterMapITSMIokoutinzbad = new TH1F("fHistClusterMapITSMIokoutinzbad", "N tracks with cluster or bad zone or out in z (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIokoutinzbad->Sumw2(); fHistClusterMapITSMIokoutinzbad->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIokoutinzbad); fHistClusterMapITSSAokoutinzbadInAcc = new TH1F("fHistClusterMapITSSAokoutinzbadInAcc", "N tracks with cluster or bad zone or out in z (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAokoutinzbadInAcc->Sumw2(); fHistClusterMapITSSAokoutinzbadInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAokoutinzbadInAcc); fHistClusterMapITSMInorefit = new TH1F("fHistClusterMapITSMInorefit", "N tracks with norefit on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMInorefit->Sumw2(); fHistClusterMapITSMInorefit->SetMinimum(0); fOutput->Add(fHistClusterMapITSMInorefit); fHistClusterMapITSSAnorefitInAcc = new TH1F("fHistClusterMapITSSAnorefitInAcc", "N tracks with norefit on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAnorefitInAcc->Sumw2(); fHistClusterMapITSSAnorefitInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAnorefitInAcc); fHistClusterMapITSSAnorefit = new TH1F("fHistClusterMapITSSAnorefit", "N tracks with norefit on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAnorefit->Sumw2(); fHistClusterMapITSSAnorefit->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAnorefit); fHistClusterMapITSMInocls = new TH1F("fHistClusterMapITSMInocls", "N tracks with nocls on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMInocls->Sumw2(); fHistClusterMapITSMInocls->SetMinimum(0); fOutput->Add(fHistClusterMapITSMInocls); fHistClusterMapITSSAnoclsInAcc = new TH1F("fHistClusterMapITSSAnoclsInAcc", "N tracks with nocls on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAnoclsInAcc->Sumw2(); fHistClusterMapITSSAnoclsInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAnoclsInAcc); fHistClusterMapModuleITSSAnoclsInAcc = new TH1F("fHistClusterMapModuleITSSAnoclsInAcc", "N tracks with nocls on Module (SA); Module; N tracks",2198, -0.5, 2197.5); fHistClusterMapModuleITSSAnoclsInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapModuleITSSAnoclsInAcc); fHistClusterMapITSSAnocls = new TH1F("fHistClusterMapITSSAnocls", "N tracks with nocls on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAnocls->Sumw2(); fHistClusterMapITSSAnocls->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAnocls); fHistPhiTPCInAcc = new TH1F("fHistPhiTPCInAcc","Azimuthal distribution of TPC tracks; #phi; N tracks",100, 0, 2.*3.1415); fHistPhiTPCInAcc->Sumw2(); fHistPhiTPCInAcc->SetMinimum(0); fOutput->Add(fHistPhiTPCInAcc); fHistPhiITSMIokbadoutinz6InAcc = new TH1F("fHistPhiITSMIokbadoutinz6InAcc","Azimuthal distribution of ITSMI tracks with 6 layers OK; #phi; N tracks",100,0,2.*3.1415); fHistPhiITSMIokbadoutinz6InAcc->Sumw2(); fHistPhiITSMIokbadoutinz6InAcc->SetMinimum(0); fOutput->Add(fHistPhiITSMIokbadoutinz6InAcc); fHistPtTPC = new TH1F("fHistPtTPC","pt distribution of TPC tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtTPC->Sumw2(); fHistPtTPC->SetMinimum(0); fOutput->Add(fHistPtTPC); fHistPtITSMI6 = new TH1F("fHistPtITSMI6","pt distribution of ITSMI6 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI6->Sumw2(); fHistPtITSMI6->SetMinimum(0); fOutput->Add(fHistPtITSMI6); fHistPtITSMI5 = new TH1F("fHistPtITSMI5","pt distribution of ITSMI5 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI5->Sumw2(); fHistPtITSMI5->SetMinimum(0); fOutput->Add(fHistPtITSMI5); fHistPtITSMI4 = new TH1F("fHistPtITSMI4","pt distribution of ITSMI4 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI4->Sumw2(); fHistPtITSMI4->SetMinimum(0); fOutput->Add(fHistPtITSMI4); fHistPtITSMI3 = new TH1F("fHistPtITSMI3","pt distribution of ITSMI3 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI3->Sumw2(); fHistPtITSMI3->SetMinimum(0); fOutput->Add(fHistPtITSMI3); fHistPtITSMI2 = new TH1F("fHistPtITSMI2","pt distribution of ITSMI2 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI2->Sumw2(); fHistPtITSMI2->SetMinimum(0); fOutput->Add(fHistPtITSMI2); fHistPtITSMISPD = new TH1F("fHistPtITSMISPD","pt distribution of ITSMISPD tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMISPD->Sumw2(); fHistPtITSMISPD->SetMinimum(0); fOutput->Add(fHistPtITSMISPD); fHistPtITSMIoneSPD = new TH1F("fHistPtITSMIoneSPD","pt distribution of ITSMIoneSPD tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIoneSPD->Sumw2(); fHistPtITSMIoneSPD->SetMinimum(0); fOutput->Add(fHistPtITSMIoneSPD); fHistPtTPCInAcc = new TH1F("fHistPtTPCInAcc","pt distribution of TPC tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtTPCInAcc->Sumw2(); fHistPtTPCInAcc->SetMinimum(0); fOutput->Add(fHistPtTPCInAcc); fHistPtITSMI6InAcc = new TH1F("fHistPtITSMI6InAcc","pt distribution of ITSMI6 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI6InAcc->Sumw2(); fHistPtITSMI6InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI6InAcc); fHistPtITSMI5InAcc = new TH1F("fHistPtITSMI5InAcc","pt distribution of ITSMI5 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI5InAcc->Sumw2(); fHistPtITSMI5InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI5InAcc); fHistPtITSMI4InAcc = new TH1F("fHistPtITSMI4InAcc","pt distribution of ITSMI4 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI4InAcc->Sumw2(); fHistPtITSMI4InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI4InAcc); fHistPtITSMI3InAcc = new TH1F("fHistPtITSMI3InAcc","pt distribution of ITSMI3 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI3InAcc->Sumw2(); fHistPtITSMI3InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI3InAcc); fHistPtITSMI2InAcc = new TH1F("fHistPtITSMI2InAcc","pt distribution of ITSMI2 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI2InAcc->Sumw2(); fHistPtITSMI2InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI2InAcc); fHistPtITSMISPDInAcc = new TH1F("fHistPtITSMISPDInAcc","pt distribution of ITSMISPD tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMISPDInAcc->Sumw2(); fHistPtITSMISPDInAcc->SetMinimum(0); fOutput->Add(fHistPtITSMISPDInAcc); fHistPtITSMIoneSPDInAcc = new TH1F("fHistPtITSMIoneSPDInAcc","pt distribution of ITSMISPD tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIoneSPDInAcc->Sumw2(); fHistPtITSMIoneSPDInAcc->SetMinimum(0); fOutput->Add(fHistPtITSMIoneSPDInAcc); fHistPtITSMIokbadoutinz6 = new TH1F("fHistPtITSMIokbadoutinz6","pt distribution of ITSMI tracks with 6 layers OK; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIokbadoutinz6->Sumw2(); fHistPtITSMIokbadoutinz6->SetMinimum(0); fOutput->Add(fHistPtITSMIokbadoutinz6); fHistPtITSMIokbadoutinz4InAcc = new TH1F("fHistPtITSMIokbadoutinz4InAcc","pt distribution of ITSMI tracks with 4 layers OK; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIokbadoutinz4InAcc->Sumw2(); fHistPtITSMIokbadoutinz4InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMIokbadoutinz4InAcc); fHistPtITSMIokbadoutinz5InAcc = new TH1F("fHistPtITSMIokbadoutinz5InAcc","pt distribution of ITSMI tracks with 5 layers OK; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIokbadoutinz5InAcc->Sumw2(); fHistPtITSMIokbadoutinz5InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMIokbadoutinz5InAcc); fHistPtITSMIokbadoutinz6InAcc = new TH1F("fHistPtITSMIokbadoutinz6InAcc","pt distribution of ITSMI tracks with 6 layers OK; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIokbadoutinz6InAcc->Sumw2(); fHistPtITSMIokbadoutinz6InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMIokbadoutinz6InAcc); // ntuples // fNtupleESDTracks = new TNtuple("fNtupleESDTracks","tracks","pt:eta:phi:d0:z0:sigmad0:sigmaz0:ptMC:pdgMC:d0MC:d0MCv:z0MCv:sigmad0MCv:sigmaz0MCv:ITSflag"); fOutput->Add(fNtupleESDTracks); fNtupleITSAlignExtra = new TNtuple("fNtupleITSAlignExtra","ITS alignment checks: extra clusters","layer:x:y:z:dxy:dz:xloc:zloc:npoints:pt"); fOutput->Add(fNtupleITSAlignExtra); fNtupleITSAlignSPDTracklets = new TNtuple("fNtupleITSAlignSPDTracklets","ITS alignment checks: SPD tracklets wrt SPD vertex","phi:theta:z:dxy:dz:pt"); fOutput->Add(fNtupleITSAlignSPDTracklets); return; } //________________________________________________________________________ void AliAnalysisTaskITSTrackingCheck::Exec(Option_t *) { // Main loop // Called for each event if (!fESD) { Printf("ERROR: fESD not available"); return; } //if(fESD->GetEventType()!=7) return; const AliESDVertex *vertexESD = fESD->GetPrimaryVertexTracks(); // *********** MC info *************** TArrayF mcVertex(3); mcVertex[0]=9999.; mcVertex[1]=9999.; mcVertex[2]=9999.; Float_t dNchdy=-999.; TParticle *part=0; AliESDVertex *vertexMC=0; AliStack *stack=0; if (fReadMC) { AliMCEventHandler *eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); if (!eventHandler) { Printf("ERROR: Could not retrieve MC event handler"); return; } AliMCEvent* mcEvent = eventHandler->MCEvent(); if (!mcEvent) { Printf("ERROR: Could not retrieve MC event"); return; } stack = mcEvent->Stack(); if (!stack) { AliDebug(AliLog::kError, "Stack not available"); return; } AliHeader* header = mcEvent->Header(); if (!header) { AliDebug(AliLog::kError, "Header not available"); return; } AliGenEventHeader* genHeader = header->GenEventHeader(); genHeader->PrimaryVertex(mcVertex); Int_t ngenpart = (Int_t)stack->GetNtrack(); //printf("# generated particles = %d\n",ngenpart); dNchdy=0; for(Int_t ip=0; ip<ngenpart; ip++) { part = (TParticle*)stack->Particle(ip); // keep only electrons, muons, pions, kaons and protons Int_t apdg = TMath::Abs(part->GetPdgCode()); if(apdg!=11 && apdg!=13 && apdg!=211 && apdg!=321 && apdg!=2212) continue; // reject secondaries if(TMath::Sqrt((part->Vx()-mcVertex[0])*(part->Vx()-mcVertex[0])+(part->Vy()-mcVertex[1])*(part->Vy()-mcVertex[1]))>0.0010) continue; // reject incoming protons Double_t energy = part->Energy(); if(energy>900.) continue; Double_t pz = part->Pz(); Double_t y = 0.5*TMath::Log((energy+pz+1.e-13)/(energy-pz+1.e-13)); if(TMath::Abs(y)<1.0) dNchdy += 0.5; // count 1/2 of particles in |y|<1 } //printf("# primary particles = %7.1f\n",dNchdy); } // *********** MC info *************** Double_t mcVtxPos[3]={mcVertex[0],mcVertex[1],mcVertex[2]},mcVtxSigma[3]={0,0,0}; vertexMC = new AliESDVertex(mcVtxPos,mcVtxSigma); // *********** ESD friends *********** fESD->SetESDfriend(fESDfriend); //Attach the friend to the ESD // *********** ESD friends *********** if(!fESDfriend) printf("no ESD friend\n"); // /* // ********** Trigger ***************** ULong64_t triggerMask; ULong64_t spdFO = (1 << 14); ULong64_t v0left = (1 << 11); ULong64_t v0right = (1 << 12); triggerMask=fESD->GetTriggerMask(); // MB1: SPDFO || V0L || V0R Bool_t eventTriggered = (triggerMask & spdFO || ((triggerMask & v0left) || (triggerMask & v0right))); //MB2: GFO && V0R //triggerMask & spdFO && ((triggerMask&v0left) || (triggerMask&v0right)) // ************ Trigger ****************** if(!eventTriggered) return; */ // SPD vertex const AliESDVertex *spdv=fESD->GetPrimaryVertexSPD(); Int_t ntracks = fESD->GetNumberOfTracks(); printf("Tracks # = %d\n",fESD->GetNumberOfTracks()); fHistNtracks->Fill(ntracks); // Post the data already here PostData(0, fOutput); Int_t idet,status; Float_t xloc,zloc; Double_t rSPDouter=7.6,rSDDouter=23.9,rSSDouter=43.1; Double_t zSPDouter=14.1,zSDDouter=29.7,zSSDouter=48.9; // loop on tracks for(Int_t itr=0; itr<ntracks; itr++) { AliESDtrack *track = fESD->GetTrack(itr); // remove kink daughters if(track->GetKinkIndex(0)>0) continue; // remove tracks not reco in ITS or TPC if (!(track->GetStatus() & AliESDtrack::kITSin) && !(track->GetStatus() & AliESDtrack::kTPCin)) continue; Bool_t itsrefit=kFALSE,tpcin=kFALSE,itsfindable=kFALSE,itsfindableAcc=kFALSE; if ((track->GetStatus() & AliESDtrack::kITSrefit)) itsrefit=kTRUE; if ((track->GetStatus() & AliESDtrack::kTPCin)) tpcin=kTRUE; Int_t trkLabel = TMath::Abs(track->GetLabel()); Int_t nclsITS = track->GetNcls(0); Int_t nclsokbadoutinzITS = 0; Bool_t outInZ=kFALSE; for(Int_t layer=0; layer<6; layer++) { track->GetITSModuleIndexInfo(layer,idet,status,xloc,zloc); if(layer>=2) idet+=240; // add n SPD modules if(layer>=4) idet+=260; // add n SPD modules if(status==4) outInZ=kTRUE; if(tpcin) { if(status==1) fHistClusterMapITSMIok->Fill(layer); if(status==2) fHistClusterMapITSMIbad->Fill(layer); if(status==3) fHistClusterMapITSMIskipped->Fill(layer); if(status==4) fHistClusterMapITSMIoutinz->Fill(layer); if(status==5) fHistClusterMapITSMInocls->Fill(layer); if(status==6) fHistClusterMapITSMInorefit->Fill(layer); if(status==1 || status==2 || status==4) { fHistClusterMapITSMIokoutinzbad->Fill(layer); nclsokbadoutinzITS++; } } else { if(status==1) fHistClusterMapITSSAok->Fill(layer); if(status==2) fHistClusterMapITSSAbad->Fill(layer); if(status==3) fHistClusterMapITSSAskipped->Fill(layer); if(status==4) fHistClusterMapITSSAoutinz->Fill(layer); if(status==5) fHistClusterMapITSSAnocls->Fill(layer); if(status==6) fHistClusterMapITSSAnorefit->Fill(layer); if(status==1 || status==2 || status==4) fHistClusterMapITSSAokoutinzbad->Fill(layer); if(status==1 && !outInZ) {fHistClusterMapITSSAokInAcc->Fill(layer);fHistClusterMapModuleITSSAokInAcc->Fill(idet);} if(status==2 && !outInZ) {fHistClusterMapITSSAbadInAcc->Fill(layer);fHistClusterMapModuleITSSAbadInAcc->Fill(idet);} if(status==3 && !outInZ) fHistClusterMapITSSAskippedInAcc->Fill(layer); if(status==4 && !outInZ) fHistClusterMapITSSAoutinzInAcc->Fill(layer); if(status==5 && !outInZ) {fHistClusterMapITSSAnoclsInAcc->Fill(layer);fHistClusterMapModuleITSSAnoclsInAcc->Fill(idet);} if(status==6 && !outInZ) fHistClusterMapITSSAnorefitInAcc->Fill(layer); if((status==1 || status==2 || status==4) && !outInZ) fHistClusterMapITSSAokoutinzbadInAcc->Fill(layer); } if(TESTBIT(track->GetITSClusterMap(),layer)) { if(tpcin) { fHistClusterMapITSMI->Fill(layer); } else { fHistClusterMapITSSA->Fill(layer); if(!outInZ) fHistClusterMapITSSAInAcc->Fill(layer); } } } // TPC track findable in ITS if(tpcin && track->GetNcls(1)>=50 && TMath::Abs(track->GetTPCInnerParam()->GetD(0,0,fESD->GetMagneticField()))<3.) { itsfindable=kTRUE; Double_t zAtSSDouter=100,zAtSDDouter=100,zAtSPDouter=100; track->GetZAt(rSSDouter,fESD->GetMagneticField(),zAtSSDouter); track->GetZAt(rSDDouter,fESD->GetMagneticField(),zAtSDDouter); track->GetZAt(rSPDouter,fESD->GetMagneticField(),zAtSPDouter); fHistPtTPC->Fill(track->Pt()); if(TMath::Abs(track->Eta())<0.9 && TMath::Abs(zAtSSDouter)<zSSDouter && TMath::Abs(zAtSDDouter)<zSDDouter && TMath::Abs(zAtSPDouter)<zSPDouter) { itsfindableAcc=kTRUE; fHistPtTPCInAcc->Fill(track->Pt()); fHistPhiTPCInAcc->Fill(track->Phi()); } } if(itsfindable&&itsrefit) { if(nclsITS==6) fHistPtITSMI6->Fill(track->Pt()); if(nclsITS==5) fHistPtITSMI5->Fill(track->Pt()); if(nclsITS==4) fHistPtITSMI4->Fill(track->Pt()); if(nclsITS==3) fHistPtITSMI3->Fill(track->Pt()); if(nclsITS==2) fHistPtITSMI2->Fill(track->Pt()); if(track->HasPointOnITSLayer(0) && track->HasPointOnITSLayer(1)) fHistPtITSMISPD->Fill(track->Pt()); if(track->HasPointOnITSLayer(0) || track->HasPointOnITSLayer(1)) fHistPtITSMIoneSPD->Fill(track->Pt()); if(nclsokbadoutinzITS==6) fHistPtITSMIokbadoutinz6->Fill(track->Pt()); } if(itsfindableAcc&&itsrefit) { if(nclsITS==6) fHistPtITSMI6InAcc->Fill(track->Pt()); if(nclsITS==5) fHistPtITSMI5InAcc->Fill(track->Pt()); if(nclsITS==4) fHistPtITSMI4InAcc->Fill(track->Pt()); if(nclsITS==3) fHistPtITSMI3InAcc->Fill(track->Pt()); if(nclsITS==2) fHistPtITSMI2InAcc->Fill(track->Pt()); if(track->HasPointOnITSLayer(0) && track->HasPointOnITSLayer(1)) fHistPtITSMISPDInAcc->Fill(track->Pt()); if(track->HasPointOnITSLayer(0) || track->HasPointOnITSLayer(1)) fHistPtITSMIoneSPDInAcc->Fill(track->Pt()); if(nclsokbadoutinzITS==6) fHistPtITSMIokbadoutinz6InAcc->Fill(track->Pt()); if(nclsokbadoutinzITS==5) fHistPtITSMIokbadoutinz5InAcc->Fill(track->Pt()); if(nclsokbadoutinzITS==4) fHistPtITSMIokbadoutinz4InAcc->Fill(track->Pt()); if(nclsokbadoutinzITS==6) fHistPhiITSMIokbadoutinz6InAcc->Fill(track->Phi()); } if(tpcin) { fHistNclsITSMI->Fill(nclsITS); } else { fHistNclsITSSA->Fill(nclsITS); if(!outInZ) fHistNclsITSSAInAcc->Fill(nclsITS); } if(tpcin && fUseITSSAforNtuples) continue; Int_t iITSflag=0; //ITSflag takes the value 0 if the track has no cluster assigned in the SPDs, 1 (2) if one cluster is assigned in SPD1(2), 3 if two clusters are present. Then the same adding 10,20 or 30 for SDD and 100,200 or 300 for SSD if(track->HasPointOnITSLayer(0)) iITSflag+=1; if(track->HasPointOnITSLayer(1)) iITSflag+=2; if(track->HasPointOnITSLayer(2)) iITSflag+=10; if(track->HasPointOnITSLayer(3)) iITSflag+=20; if(track->HasPointOnITSLayer(4)) iITSflag+=100; if(track->HasPointOnITSLayer(5)) iITSflag+=200; if(iITSflag==333 && track->GetNcls(0)<6) printf(" ERROR %d %d\n",track->GetNcls(0),track->GetLabel()); // number of associated ITS clusters iITSflag += 1000*track->GetNcls(0); // number of associated TPC clusters iITSflag += 100000*track->GetNcls(1); // if MC info and is available // write the number of ITS clusters produced by this track Int_t nITSclsMC=0; if(fReadMC && fReadRPLabels) { nITSclsMC = NumberOfITSClustersMC(trkLabel); if(nITSclsMC>=0) iITSflag += 10000*nITSclsMC; } if(!vertexESD) continue; if(!(vertexESD->GetStatus())) continue; // impact parameter to VertexTracks Double_t d0z0[2],covd0z0[3]; track->PropagateToDCA(vertexESD,fESD->GetMagneticField(),100.,d0z0,covd0z0); if(covd0z0[0]<0. || covd0z0[2]<0.) continue; // if MC info is available: get particle properties Float_t ptMC=-999.,pdgMC=-999.,d0MC=-999.; Double_t d0z0MCv[2]={-999.,-999.},covd0z0MCv[3]={1.,1.,1.}; if(fReadMC) { part = (TParticle*)stack->Particle(trkLabel); ptMC=part->Pt(); pdgMC=part->GetPdgCode(); d0MC=ParticleImpParMC(part,vertexMC,0.1*fESD->GetMagneticField()); track->PropagateToDCA(vertexMC,fESD->GetMagneticField(),100.,d0z0MCv,covd0z0MCv); if(covd0z0MCv[0]<0. || covd0z0MCv[2]<0.) continue; // flag fake tracks if(track->GetLabel()<0) iITSflag *= -1; } Double_t sigmad0MCv=TMath::Sqrt(covd0z0MCv[0]); if(!itsrefit) sigmad0MCv *= -1.; // fill ntuple with track properties if(fFillNtuples && SelectPt(track->Pt())) { Float_t fillArray[19]={track->Pt(),track->Eta(),track->Phi(),d0z0[0],d0z0[1],TMath::Sqrt(covd0z0[0]),TMath::Sqrt(covd0z0[2]),ptMC,pdgMC,d0MC,d0z0MCv[0],d0z0MCv[1],sigmad0MCv,TMath::Sqrt(covd0z0MCv[2]),(Float_t)iITSflag}; fNtupleESDTracks->Fill(fillArray); } //--------------------------------------------- // AliTrackPoints: alignment checks // if(!fFillNtuples) continue; if(!fESDfriend) continue; const AliTrackPointArray *array = track->GetTrackPointArray(); if(!array) continue; AliTrackPoint point; Int_t pointOnLayer[6]={0,0,0,0,0,0}; Int_t indexAssociated[6]={-1,-1,-1,-1,-1,-1},indexExtra=-1; Bool_t extra=kFALSE; Int_t layerId,layerExtra=-1; for(Int_t ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); Float_t r = TMath::Sqrt(point.GetX()*point.GetX()+point.GetY()*point.GetY()); if(r>3 && r<6) { layerId = 0; } else if(r>6 && r<8) { layerId = 1; } else if(r>8 && r<18) { layerId = 2; } else if(r>18 && r<30) { layerId = 3; } else if(r>30 && r<40) { layerId = 4; } else if(r>40 && r<50) { layerId = 5; } else { layerId=100; } // only ITS points if(layerId>5) continue; if(!point.IsExtra()) { pointOnLayer[layerId]++; indexAssociated[layerId]=ipt; } else { // this is an extra cluster extra=kTRUE; layerExtra=layerId; indexExtra=ipt; } } // end loop on AliTrackPoints TString vtitle = spdv->GetTitle(); if(!vtitle.Contains("3D")) continue; // SPD tracklet if(indexAssociated[0]>=0 && indexAssociated[1]>=0) { AliTrackPoint pointSPD1,pointSPD2; array->GetPoint(pointSPD1,indexAssociated[0]); array->GetPoint(pointSPD2,indexAssociated[1]); Float_t phi=TMath::ATan2(pointSPD2.GetY()-pointSPD1.GetY(),pointSPD2.GetX()-pointSPD1.GetX()); Float_t lambda=TMath::ATan((pointSPD2.GetZ()-pointSPD1.GetZ())/TMath::Sqrt((pointSPD2.GetX()-pointSPD1.GetX())*(pointSPD2.GetX()-pointSPD1.GetX())+(pointSPD2.GetY()-pointSPD1.GetY())*(pointSPD2.GetY()-pointSPD1.GetY()))); Float_t theta=0.5*TMath::Pi()-lambda; TParticle particle(211,0,0,0,0,0,TMath::Cos(phi),TMath::Sin(phi),TMath::Tan(lambda),10.,pointSPD1.GetX(),pointSPD1.GetY(),pointSPD1.GetZ(),0); AliESDtrack tracklet(&particle); Float_t dz[2]; // distance to primary SPD (only if 3D and high multiplicity) if(spdv->GetNContributors()>10) { tracklet.GetDZ(spdv->GetXv(),spdv->GetYv(),spdv->GetZv(),0,dz); //tracklet.GetDZ(-0.07,0.25,spdv->GetZv(),0,dz); fNtupleITSAlignSPDTracklets->Fill(phi,theta,0.5*(pointSPD1.GetZ()+pointSPD2.GetZ()),dz[0],dz[1],track->Pt()); } } // distance to extra if(extra && spdv->GetNContributors()>4 && indexAssociated[layerExtra]>-1) { AliTrackPoint pointExtra,pointAssociated; array->GetPoint(pointAssociated,indexAssociated[layerExtra]); array->GetPoint(pointExtra,indexExtra); Float_t phiExtra = TMath::ATan2(pointExtra.GetY()-spdv->GetYv(),pointExtra.GetX()-spdv->GetXv()); Float_t phiAssociated = TMath::ATan2(pointAssociated.GetY()-spdv->GetYv(),pointAssociated.GetX()-spdv->GetXv()); Float_t rExtra = TMath::Sqrt((pointExtra.GetX()-spdv->GetXv())*(pointExtra.GetX()-spdv->GetXv())+(pointExtra.GetY()-spdv->GetYv())*(pointExtra.GetY()-spdv->GetYv())); Float_t rAssociated = TMath::Sqrt((pointAssociated.GetX()-spdv->GetXv())*(pointAssociated.GetX()-spdv->GetXv())+(pointAssociated.GetY()-spdv->GetYv())*(pointAssociated.GetY()-spdv->GetYv())); Float_t dzExtra[2]; dzExtra[0] = (phiExtra-phiAssociated)*0.5*(rExtra+rAssociated); dzExtra[1] = pointExtra.GetZ()-pointAssociated.GetZ()-(rExtra-rAssociated)*(pointAssociated.GetZ()-spdv->GetZv())/rAssociated; Float_t xlocExtra=-100.,zlocExtra=-100.; fNtupleITSAlignExtra->Fill(layerExtra,pointExtra.GetX(),pointExtra.GetY(),pointExtra.GetZ(),dzExtra[0],dzExtra[1],xlocExtra,zlocExtra,nclsITS,track->Pt()); } } // end loop on tracks if(vertexMC) { delete vertexMC; vertexMC=0; } return; } //________________________________________________________________________ void AliAnalysisTaskITSTrackingCheck::Terminate(Option_t *) { // Draw result to the screen // Called once at the end of the query fOutput = dynamic_cast<TList*> (GetOutputData(0)); if (!fOutput) { Printf("ERROR: fOutput not available"); return; } fHistNtracks = dynamic_cast<TH1F*>(fOutput->FindObject("fHistNtracks")); fHistNclsITSMI = dynamic_cast<TH1F*>(fOutput->FindObject("fHistNclsITSMI")); fHistNclsITSSA = dynamic_cast<TH1F*>(fOutput->FindObject("fHistNclsITSSA")); fHistClusterMapITSMI = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMI")); fHistClusterMapITSMIbad = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMIbad")); fHistClusterMapITSMIskipped = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMIskipped")); fHistClusterMapITSMIoutinz = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMIoutinz")); fHistClusterMapITSMInorefit = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMInorefit")); fHistClusterMapITSMInocls = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMInocls")); fHistClusterMapITSSA = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSA")); fHistClusterMapITSSAbad = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAbad")); fHistClusterMapITSSAskipped = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAskipped")); fHistClusterMapITSSAoutinz = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAoutinz")); fHistClusterMapITSSAnorefit = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAnorefit")); fHistClusterMapITSSAnocls = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAnocls")); fNtupleESDTracks = dynamic_cast<TNtuple*>(fOutput->FindObject("fNtupleESDTracks")); fNtupleITSAlignExtra = dynamic_cast<TNtuple*>(fOutput->FindObject("fNtupleITSAlignExtra")); fNtupleITSAlignSPDTracklets = dynamic_cast<TNtuple*>(fOutput->FindObject("fNtupleITSAlignSPDTracklets")); return; } //--------------------------------------------------------------------------- Int_t AliAnalysisTaskITSTrackingCheck::NumberOfITSClustersMC(Int_t label) const { // // Return number of ITS clusters produced by MC particle with given label // AliESDInputHandlerRP *esdHRP = dynamic_cast<AliESDInputHandlerRP*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if(!esdHRP) return -1; TTree *cTree = (TTree*)esdHRP->GetTreeR("ITS"); if(!cTree) return -1; TClonesArray *clusters=0; // new TClonesArray("AliITSRecPoint",10000); cTree->SetBranchAddress("ITSRecPoints",&clusters); if(!clusters) return -1; AliITSRecPoint *c=0; Int_t i,n,icl,lay,ilab; Int_t ncls[6]={0,0,0,0,0,0}; Int_t nclstot=0; for(i=0; i<2198; i++) { cTree->GetEvent(i); n=clusters->GetEntriesFast(); for (icl=0; icl<n; icl++) { c=(AliITSRecPoint*)clusters->UncheckedAt(icl); lay=c->GetLayer(); for(ilab=0;ilab<3;ilab++) { if(c->GetLabel(ilab)==label) ncls[lay]++; } } } for(i=0;i<6;i++) { if(ncls[i]) nclstot++; } return nclstot; //return label*0; } //--------------------------------------------------------------------------- Double_t AliAnalysisTaskITSTrackingCheck::ParticleImpParMC(TParticle *part, AliESDVertex *vert, Double_t bzT) const { // // Return the MC value of the impact parameter // Double_t vx=part->Vx()-vert->GetX(); Double_t vy=part->Vy()-vert->GetY(); Double_t pt=part->Pt(); Double_t px=part->Px(); Double_t py=part->Py(); Double_t charge = (part->GetPdgCode()>0. ? 1. : -1.); if(TMath::Abs(part->GetPdgCode())<100) charge*=-1.; if(px<0.000001) px=0.000001; Double_t rAnd=((10./2.99792458)*pt/bzT)*100.; Double_t center[3],d0; center[0]=vx-(1./charge)*rAnd*(py/pt); center[1]=vy+(1./charge)*rAnd*(px/pt); center[2]=TMath::Sqrt(center[0]*center[0]+center[1]*center[1]); d0 = -center[2]+rAnd; return d0; } //--------------------------------------------------------------------------- Bool_t AliAnalysisTaskITSTrackingCheck::SelectPt(Double_t pt) { // // Keep only tracks in given pt bins // Double_t ptlower[10]={0.29,0.49,0.75,0.9,1.9,3.5,6.5, 9.,19.,27.}; Double_t ptupper[10]={0.31,0.51,0.85,1.1,2.1,4.5,7.5,11.,21.,33.}; for(Int_t i=0; i<10; i++) { if(pt>ptlower[i] && pt<ptupper[i]) { fCountsPerPtBin[i]++; return kTRUE; } } return kFALSE; //return kTRUE; } Possibility to use only ITS+TPC tracks for ntuples /************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////// // // AliAnalysisTask to extract from ESD tracks the information // on ITS tracking efficiency and resolutions. // // Author: A.Dainese, andrea.dainese@pd.infn.it ///////////////////////////////////////////////////////////// #include <TStyle.h> #include <TChain.h> #include <TTree.h> #include <TNtuple.h> #include <TBranch.h> #include <TClonesArray.h> #include <TObjArray.h> #include <TH1F.h> #include <TH2F.h> #include <TCanvas.h> #include <TParticle.h> #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliMultiplicity.h" #include "AliVertexerTracks.h" #include "AliESDtrack.h" #include "AliExternalTrackParam.h" #include "AliESDVertex.h" #include "AliESDEvent.h" #include "AliESDfriend.h" #include "AliESDInputHandler.h" #include "AliESDInputHandlerRP.h" #include "AliTrackPointArray.h" #include "../ITS/AliITSRecPoint.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliStack.h" #include "AliLog.h" #include "AliGenEventHeader.h" #include "AliAnalysisTaskITSTrackingCheck.h" ClassImp(AliAnalysisTaskITSTrackingCheck) //________________________________________________________________________ AliAnalysisTaskITSTrackingCheck::AliAnalysisTaskITSTrackingCheck(const char *name) : AliAnalysisTask(name, "ITSTrackingCheckTask"), fReadMC(kFALSE), fReadRPLabels(kFALSE), fFillNtuples(kFALSE), fUseITSSAforNtuples(kFALSE), fESD(0), fESDfriend(0), fOutput(0), fHistNtracks(0), fHistNclsITSMI(0), fHistNclsITSSA(0), fHistNclsITSSAInAcc(0), fHistClusterMapITSMI(0), fHistClusterMapITSMIok(0), fHistClusterMapITSMIbad(0), fHistClusterMapITSMIskipped(0), fHistClusterMapITSMIoutinz(0), fHistClusterMapITSMInorefit(0), fHistClusterMapITSMInocls(0), fHistClusterMapITSMIokoutinzbad(0), fHistClusterMapITSSA(0), fHistClusterMapITSSAok(0), fHistClusterMapITSSAbad(0), fHistClusterMapITSSAskipped(0), fHistClusterMapITSSAoutinz(0), fHistClusterMapITSSAnorefit(0), fHistClusterMapITSSAnocls(0), fHistClusterMapITSSAokoutinzbad(0), fHistClusterMapITSSAInAcc(0), fHistClusterMapITSSAokInAcc(0), fHistClusterMapITSSAbadInAcc(0), fHistClusterMapITSSAskippedInAcc(0), fHistClusterMapITSSAoutinzInAcc(0), fHistClusterMapITSSAnorefitInAcc(0), fHistClusterMapITSSAnoclsInAcc(0), fHistClusterMapITSSAokoutinzbadInAcc(0), fHistClusterMapModuleITSSAokInAcc(0), fHistClusterMapModuleITSSAbadInAcc(0), fHistClusterMapModuleITSSAnoclsInAcc(0), fHistPhiTPCInAcc(0), fHistPtTPC(0), fHistPtTPCInAcc(0), fHistPtITSMI2(0), fHistPtITSMI3(0), fHistPtITSMI4(0), fHistPtITSMI5(0), fHistPtITSMI6(0), fHistPtITSMISPD(0), fHistPtITSMIoneSPD(0), fHistPtITSMI2InAcc(0), fHistPtITSMI3InAcc(0), fHistPtITSMI4InAcc(0), fHistPtITSMI5InAcc(0), fHistPtITSMI6InAcc(0), fHistPtITSMISPDInAcc(0), fHistPtITSMIoneSPDInAcc(0), fHistPtITSMIokbadoutinz6(0), fHistPtITSMIokbadoutinz4InAcc(0), fHistPtITSMIokbadoutinz5InAcc(0), fHistPtITSMIokbadoutinz6InAcc(0), fHistPhiITSMIokbadoutinz6InAcc(0), fNtupleESDTracks(0), fNtupleITSAlignExtra(0), fNtupleITSAlignSPDTracklets(0) { // Constructor for(Int_t i=0; i<10; i++) fCountsPerPtBin[i]=0; // Define input and output slots here // Input slot #0 works with a TChain DefineInput(0, TChain::Class()); // Output slot #0 writes into a TList container DefineOutput(0, TList::Class()); //My private output } //________________________________________________________________________ AliAnalysisTaskITSTrackingCheck::~AliAnalysisTaskITSTrackingCheck() { // Destructor // histograms are in the output list and deleted when the output // list is deleted by the TSelector dtor if (fOutput) { delete fOutput; fOutput = 0; } } //________________________________________________________________________ void AliAnalysisTaskITSTrackingCheck::ConnectInputData(Option_t *) { // Connect ESD or AOD here // Called once TTree* tree = dynamic_cast<TTree*> (GetInputData(0)); if (!tree) { Printf("ERROR: Could not read chain from input slot 0"); } else { // Disable all branches and enable only the needed ones // The next two lines are different when data produced as AliESDEvent is read tree->SetBranchStatus("ESDfriend*", 1); tree->SetBranchAddress("ESDfriend.",&fESDfriend); AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!esdH) { Printf("ERROR: Could not get ESDInputHandler"); } else { fESD = esdH->GetEvent(); } } return; } //________________________________________________________________________ void AliAnalysisTaskITSTrackingCheck::CreateOutputObjects() { // Create histograms // Called once gStyle->SetHistLineWidth(2); Int_t nPtBins=21; Float_t xPtBins[22]={0,0.1,0.2,0.3,0.4,0.5,0.6,0.8,1.0,1.5,2.,2.5,3,4,5,6,8,10,15,20,25,30}; for(Int_t i=0; i<10; i++) fCountsPerPtBin[i]=0; // Several histograms are more conveniently managed in a TList fOutput = new TList; fOutput->SetOwner(); fHistNtracks = new TH1F("fHistNtracks", "N ESD tracks; N tracks; Events",5000, -0.5, 4999.5); fHistNtracks->Sumw2(); fHistNtracks->SetMinimum(0); fOutput->Add(fHistNtracks); fHistNclsITSMI = new TH1F("fHistNclsITSMI", "N ITS clusters per track (MI); N clusters; Counts",7, -0.5, 6.5); fHistNclsITSMI->Sumw2(); fHistNclsITSMI->SetMinimum(0); fOutput->Add(fHistNclsITSMI); fHistNclsITSSAInAcc = new TH1F("fHistNclsITSSAInAcc", "N ITS clusters per track (SA); N clusters; Counts",7, -0.5, 6.5); fHistNclsITSSAInAcc->Sumw2(); fHistNclsITSSAInAcc->SetMinimum(0); fOutput->Add(fHistNclsITSSAInAcc); fHistNclsITSSA = new TH1F("fHistNclsITSSA", "N ITS clusters per track (SA); N clusters; Counts",7, -0.5, 6.5); fHistNclsITSSA->Sumw2(); fHistNclsITSSA->SetMinimum(0); fOutput->Add(fHistNclsITSSA); fHistClusterMapITSMI = new TH1F("fHistClusterMapITSMI", "N tracks with point on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMI->Sumw2(); fHistClusterMapITSMI->SetMinimum(0); fOutput->Add(fHistClusterMapITSMI); fHistClusterMapITSSA = new TH1F("fHistClusterMapITSSA", "N tracks with point on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSA->Sumw2(); fHistClusterMapITSSA->SetMinimum(0); fOutput->Add(fHistClusterMapITSSA); fHistClusterMapITSSAInAcc = new TH1F("fHistClusterMapITSSAInAcc", "N tracks with point on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAInAcc->Sumw2(); fHistClusterMapITSSAInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAInAcc); fHistClusterMapITSMIok = new TH1F("fHistClusterMapITSMIok", "N tracks with ok on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIok->Sumw2(); fHistClusterMapITSMIok->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIok); fHistClusterMapITSSAokInAcc = new TH1F("fHistClusterMapITSSAokInAcc", "N tracks with ok on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAokInAcc->Sumw2(); fHistClusterMapITSSAokInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAokInAcc); fHistClusterMapModuleITSSAokInAcc = new TH1F("fHistClusterMapModuleITSSAokInAcc", "N tracks with ok on Module (SA); Module; N tracks",2198, -0.5, 2197.5); fHistClusterMapModuleITSSAokInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapModuleITSSAokInAcc); fHistClusterMapITSSAok = new TH1F("fHistClusterMapITSSAok", "N tracks with ok on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAok->Sumw2(); fHistClusterMapITSSAok->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAok); fHistClusterMapITSMIbad = new TH1F("fHistClusterMapITSMIbad", "N tracks with bad on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIbad->Sumw2(); fHistClusterMapITSMIbad->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIbad); fHistClusterMapITSSAbadInAcc = new TH1F("fHistClusterMapITSSAbadInAcc", "N tracks with bad on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAbadInAcc->Sumw2(); fHistClusterMapITSSAbadInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAbadInAcc); fHistClusterMapModuleITSSAbadInAcc = new TH1F("fHistClusterMapModuleITSSAbadInAcc", "N tracks with bad on Module (SA); Module; N tracks",2198, -0.5, 2197.5); fHistClusterMapModuleITSSAbadInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapModuleITSSAbadInAcc); fHistClusterMapITSSAbad = new TH1F("fHistClusterMapITSSAbad", "N tracks with bad on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAbad->Sumw2(); fHistClusterMapITSSAbad->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAbad); fHistClusterMapITSMIskipped = new TH1F("fHistClusterMapITSMIskipped", "N tracks with skip on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIskipped->Sumw2(); fHistClusterMapITSMIskipped->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIskipped); fHistClusterMapITSSAskippedInAcc = new TH1F("fHistClusterMapITSSAskippedInAcc", "N tracks with skip on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAskippedInAcc->Sumw2(); fHistClusterMapITSSAskippedInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAskippedInAcc); fHistClusterMapITSSAskipped = new TH1F("fHistClusterMapITSSAskipped", "N tracks with skip on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAskipped->Sumw2(); fHistClusterMapITSSAskipped->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAskipped); fHistClusterMapITSMIoutinz = new TH1F("fHistClusterMapITSMIoutinz", "N tracks out in z on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIoutinz->Sumw2(); fHistClusterMapITSMIoutinz->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIoutinz); fHistClusterMapITSSAoutinzInAcc = new TH1F("fHistClusterMapITSSAoutinzInAcc", "N tracks with out in z on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAoutinzInAcc->Sumw2(); fHistClusterMapITSSAoutinzInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAoutinzInAcc); fHistClusterMapITSSAoutinz = new TH1F("fHistClusterMapITSSAoutinz", "N tracks with out in z on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAoutinz->Sumw2(); fHistClusterMapITSSAoutinz->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAoutinz); fHistClusterMapITSSAokoutinzbad = new TH1F("fHistClusterMapITSSAokoutinzbad", "N tracks with cluster or bad zone or out in z (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAokoutinzbad->Sumw2(); fHistClusterMapITSSAokoutinzbad->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAokoutinzbad); fHistClusterMapITSMIokoutinzbad = new TH1F("fHistClusterMapITSMIokoutinzbad", "N tracks with cluster or bad zone or out in z (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMIokoutinzbad->Sumw2(); fHistClusterMapITSMIokoutinzbad->SetMinimum(0); fOutput->Add(fHistClusterMapITSMIokoutinzbad); fHistClusterMapITSSAokoutinzbadInAcc = new TH1F("fHistClusterMapITSSAokoutinzbadInAcc", "N tracks with cluster or bad zone or out in z (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAokoutinzbadInAcc->Sumw2(); fHistClusterMapITSSAokoutinzbadInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAokoutinzbadInAcc); fHistClusterMapITSMInorefit = new TH1F("fHistClusterMapITSMInorefit", "N tracks with norefit on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMInorefit->Sumw2(); fHistClusterMapITSMInorefit->SetMinimum(0); fOutput->Add(fHistClusterMapITSMInorefit); fHistClusterMapITSSAnorefitInAcc = new TH1F("fHistClusterMapITSSAnorefitInAcc", "N tracks with norefit on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAnorefitInAcc->Sumw2(); fHistClusterMapITSSAnorefitInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAnorefitInAcc); fHistClusterMapITSSAnorefit = new TH1F("fHistClusterMapITSSAnorefit", "N tracks with norefit on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAnorefit->Sumw2(); fHistClusterMapITSSAnorefit->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAnorefit); fHistClusterMapITSMInocls = new TH1F("fHistClusterMapITSMInocls", "N tracks with nocls on Layer (MI); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSMInocls->Sumw2(); fHistClusterMapITSMInocls->SetMinimum(0); fOutput->Add(fHistClusterMapITSMInocls); fHistClusterMapITSSAnoclsInAcc = new TH1F("fHistClusterMapITSSAnoclsInAcc", "N tracks with nocls on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAnoclsInAcc->Sumw2(); fHistClusterMapITSSAnoclsInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAnoclsInAcc); fHistClusterMapModuleITSSAnoclsInAcc = new TH1F("fHistClusterMapModuleITSSAnoclsInAcc", "N tracks with nocls on Module (SA); Module; N tracks",2198, -0.5, 2197.5); fHistClusterMapModuleITSSAnoclsInAcc->SetMinimum(0); fOutput->Add(fHistClusterMapModuleITSSAnoclsInAcc); fHistClusterMapITSSAnocls = new TH1F("fHistClusterMapITSSAnocls", "N tracks with nocls on Layer (SA); Layer; N tracks",6, -0.5, 5.5); fHistClusterMapITSSAnocls->Sumw2(); fHistClusterMapITSSAnocls->SetMinimum(0); fOutput->Add(fHistClusterMapITSSAnocls); fHistPhiTPCInAcc = new TH1F("fHistPhiTPCInAcc","Azimuthal distribution of TPC tracks; #phi; N tracks",100, 0, 2.*3.1415); fHistPhiTPCInAcc->Sumw2(); fHistPhiTPCInAcc->SetMinimum(0); fOutput->Add(fHistPhiTPCInAcc); fHistPhiITSMIokbadoutinz6InAcc = new TH1F("fHistPhiITSMIokbadoutinz6InAcc","Azimuthal distribution of ITSMI tracks with 6 layers OK; #phi; N tracks",100,0,2.*3.1415); fHistPhiITSMIokbadoutinz6InAcc->Sumw2(); fHistPhiITSMIokbadoutinz6InAcc->SetMinimum(0); fOutput->Add(fHistPhiITSMIokbadoutinz6InAcc); fHistPtTPC = new TH1F("fHistPtTPC","pt distribution of TPC tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtTPC->Sumw2(); fHistPtTPC->SetMinimum(0); fOutput->Add(fHistPtTPC); fHistPtITSMI6 = new TH1F("fHistPtITSMI6","pt distribution of ITSMI6 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI6->Sumw2(); fHistPtITSMI6->SetMinimum(0); fOutput->Add(fHistPtITSMI6); fHistPtITSMI5 = new TH1F("fHistPtITSMI5","pt distribution of ITSMI5 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI5->Sumw2(); fHistPtITSMI5->SetMinimum(0); fOutput->Add(fHistPtITSMI5); fHistPtITSMI4 = new TH1F("fHistPtITSMI4","pt distribution of ITSMI4 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI4->Sumw2(); fHistPtITSMI4->SetMinimum(0); fOutput->Add(fHistPtITSMI4); fHistPtITSMI3 = new TH1F("fHistPtITSMI3","pt distribution of ITSMI3 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI3->Sumw2(); fHistPtITSMI3->SetMinimum(0); fOutput->Add(fHistPtITSMI3); fHistPtITSMI2 = new TH1F("fHistPtITSMI2","pt distribution of ITSMI2 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI2->Sumw2(); fHistPtITSMI2->SetMinimum(0); fOutput->Add(fHistPtITSMI2); fHistPtITSMISPD = new TH1F("fHistPtITSMISPD","pt distribution of ITSMISPD tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMISPD->Sumw2(); fHistPtITSMISPD->SetMinimum(0); fOutput->Add(fHistPtITSMISPD); fHistPtITSMIoneSPD = new TH1F("fHistPtITSMIoneSPD","pt distribution of ITSMIoneSPD tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIoneSPD->Sumw2(); fHistPtITSMIoneSPD->SetMinimum(0); fOutput->Add(fHistPtITSMIoneSPD); fHistPtTPCInAcc = new TH1F("fHistPtTPCInAcc","pt distribution of TPC tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtTPCInAcc->Sumw2(); fHistPtTPCInAcc->SetMinimum(0); fOutput->Add(fHistPtTPCInAcc); fHistPtITSMI6InAcc = new TH1F("fHistPtITSMI6InAcc","pt distribution of ITSMI6 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI6InAcc->Sumw2(); fHistPtITSMI6InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI6InAcc); fHistPtITSMI5InAcc = new TH1F("fHistPtITSMI5InAcc","pt distribution of ITSMI5 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI5InAcc->Sumw2(); fHistPtITSMI5InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI5InAcc); fHistPtITSMI4InAcc = new TH1F("fHistPtITSMI4InAcc","pt distribution of ITSMI4 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI4InAcc->Sumw2(); fHistPtITSMI4InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI4InAcc); fHistPtITSMI3InAcc = new TH1F("fHistPtITSMI3InAcc","pt distribution of ITSMI3 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI3InAcc->Sumw2(); fHistPtITSMI3InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI3InAcc); fHistPtITSMI2InAcc = new TH1F("fHistPtITSMI2InAcc","pt distribution of ITSMI2 tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMI2InAcc->Sumw2(); fHistPtITSMI2InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMI2InAcc); fHistPtITSMISPDInAcc = new TH1F("fHistPtITSMISPDInAcc","pt distribution of ITSMISPD tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMISPDInAcc->Sumw2(); fHistPtITSMISPDInAcc->SetMinimum(0); fOutput->Add(fHistPtITSMISPDInAcc); fHistPtITSMIoneSPDInAcc = new TH1F("fHistPtITSMIoneSPDInAcc","pt distribution of ITSMISPD tracks; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIoneSPDInAcc->Sumw2(); fHistPtITSMIoneSPDInAcc->SetMinimum(0); fOutput->Add(fHistPtITSMIoneSPDInAcc); fHistPtITSMIokbadoutinz6 = new TH1F("fHistPtITSMIokbadoutinz6","pt distribution of ITSMI tracks with 6 layers OK; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIokbadoutinz6->Sumw2(); fHistPtITSMIokbadoutinz6->SetMinimum(0); fOutput->Add(fHistPtITSMIokbadoutinz6); fHistPtITSMIokbadoutinz4InAcc = new TH1F("fHistPtITSMIokbadoutinz4InAcc","pt distribution of ITSMI tracks with 4 layers OK; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIokbadoutinz4InAcc->Sumw2(); fHistPtITSMIokbadoutinz4InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMIokbadoutinz4InAcc); fHistPtITSMIokbadoutinz5InAcc = new TH1F("fHistPtITSMIokbadoutinz5InAcc","pt distribution of ITSMI tracks with 5 layers OK; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIokbadoutinz5InAcc->Sumw2(); fHistPtITSMIokbadoutinz5InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMIokbadoutinz5InAcc); fHistPtITSMIokbadoutinz6InAcc = new TH1F("fHistPtITSMIokbadoutinz6InAcc","pt distribution of ITSMI tracks with 6 layers OK; p_{t} [GeV/c]; N tracks",nPtBins,xPtBins); fHistPtITSMIokbadoutinz6InAcc->Sumw2(); fHistPtITSMIokbadoutinz6InAcc->SetMinimum(0); fOutput->Add(fHistPtITSMIokbadoutinz6InAcc); // ntuples // fNtupleESDTracks = new TNtuple("fNtupleESDTracks","tracks","pt:eta:phi:d0:z0:sigmad0:sigmaz0:ptMC:pdgMC:d0MC:d0MCv:z0MCv:sigmad0MCv:sigmaz0MCv:ITSflag"); fOutput->Add(fNtupleESDTracks); fNtupleITSAlignExtra = new TNtuple("fNtupleITSAlignExtra","ITS alignment checks: extra clusters","layer:x:y:z:dxy:dz:xloc:zloc:npoints:pt"); fOutput->Add(fNtupleITSAlignExtra); fNtupleITSAlignSPDTracklets = new TNtuple("fNtupleITSAlignSPDTracklets","ITS alignment checks: SPD tracklets wrt SPD vertex","phi:theta:z:dxy:dz:pt"); fOutput->Add(fNtupleITSAlignSPDTracklets); return; } //________________________________________________________________________ void AliAnalysisTaskITSTrackingCheck::Exec(Option_t *) { // Main loop // Called for each event if (!fESD) { Printf("ERROR: fESD not available"); return; } //if(fESD->GetEventType()!=7) return; const AliESDVertex *vertexESD = fESD->GetPrimaryVertexTracks(); // *********** MC info *************** TArrayF mcVertex(3); mcVertex[0]=9999.; mcVertex[1]=9999.; mcVertex[2]=9999.; Float_t dNchdy=-999.; TParticle *part=0; AliESDVertex *vertexMC=0; AliStack *stack=0; if (fReadMC) { AliMCEventHandler *eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); if (!eventHandler) { Printf("ERROR: Could not retrieve MC event handler"); return; } AliMCEvent* mcEvent = eventHandler->MCEvent(); if (!mcEvent) { Printf("ERROR: Could not retrieve MC event"); return; } stack = mcEvent->Stack(); if (!stack) { AliDebug(AliLog::kError, "Stack not available"); return; } AliHeader* header = mcEvent->Header(); if (!header) { AliDebug(AliLog::kError, "Header not available"); return; } AliGenEventHeader* genHeader = header->GenEventHeader(); genHeader->PrimaryVertex(mcVertex); Int_t ngenpart = (Int_t)stack->GetNtrack(); //printf("# generated particles = %d\n",ngenpart); dNchdy=0; for(Int_t ip=0; ip<ngenpart; ip++) { part = (TParticle*)stack->Particle(ip); // keep only electrons, muons, pions, kaons and protons Int_t apdg = TMath::Abs(part->GetPdgCode()); if(apdg!=11 && apdg!=13 && apdg!=211 && apdg!=321 && apdg!=2212) continue; // reject secondaries if(TMath::Sqrt((part->Vx()-mcVertex[0])*(part->Vx()-mcVertex[0])+(part->Vy()-mcVertex[1])*(part->Vy()-mcVertex[1]))>0.0010) continue; // reject incoming protons Double_t energy = part->Energy(); if(energy>900.) continue; Double_t pz = part->Pz(); Double_t y = 0.5*TMath::Log((energy+pz+1.e-13)/(energy-pz+1.e-13)); if(TMath::Abs(y)<1.0) dNchdy += 0.5; // count 1/2 of particles in |y|<1 } //printf("# primary particles = %7.1f\n",dNchdy); } // *********** MC info *************** Double_t mcVtxPos[3]={mcVertex[0],mcVertex[1],mcVertex[2]},mcVtxSigma[3]={0,0,0}; vertexMC = new AliESDVertex(mcVtxPos,mcVtxSigma); // *********** ESD friends *********** fESD->SetESDfriend(fESDfriend); //Attach the friend to the ESD // *********** ESD friends *********** if(!fESDfriend) printf("no ESD friend\n"); // /* // ********** Trigger ***************** ULong64_t triggerMask; ULong64_t spdFO = (1 << 14); ULong64_t v0left = (1 << 11); ULong64_t v0right = (1 << 12); triggerMask=fESD->GetTriggerMask(); // MB1: SPDFO || V0L || V0R Bool_t eventTriggered = (triggerMask & spdFO || ((triggerMask & v0left) || (triggerMask & v0right))); //MB2: GFO && V0R //triggerMask & spdFO && ((triggerMask&v0left) || (triggerMask&v0right)) // ************ Trigger ****************** if(!eventTriggered) return; */ // SPD vertex const AliESDVertex *spdv=fESD->GetPrimaryVertexSPD(); Int_t ntracks = fESD->GetNumberOfTracks(); printf("Tracks # = %d\n",fESD->GetNumberOfTracks()); fHistNtracks->Fill(ntracks); // Post the data already here PostData(0, fOutput); Int_t idet,status; Float_t xloc,zloc; Double_t rSPDouter=7.6,rSDDouter=23.9,rSSDouter=43.1; Double_t zSPDouter=14.1,zSDDouter=29.7,zSSDouter=48.9; // loop on tracks for(Int_t itr=0; itr<ntracks; itr++) { AliESDtrack *track = fESD->GetTrack(itr); //if( TMath::Abs(TMath::Abs(track->Phi()-TMath::Pi())-0.5*TMath::Pi()) < 0.25*TMath::Pi() ) continue; // remove kink daughters if(track->GetKinkIndex(0)>0) continue; // remove tracks not reco in ITS or TPC if (!(track->GetStatus() & AliESDtrack::kITSin) && !(track->GetStatus() & AliESDtrack::kTPCin)) continue; Bool_t itsrefit=kFALSE,tpcin=kFALSE,itsfindable=kFALSE,itsfindableAcc=kFALSE; if ((track->GetStatus() & AliESDtrack::kITSrefit)) itsrefit=kTRUE; if ((track->GetStatus() & AliESDtrack::kTPCin)) tpcin=kTRUE; Int_t trkLabel = TMath::Abs(track->GetLabel()); Int_t nclsITS = track->GetNcls(0); Int_t nclsokbadoutinzITS = 0; Bool_t outInZ=kFALSE; for(Int_t layer=0; layer<6; layer++) { track->GetITSModuleIndexInfo(layer,idet,status,xloc,zloc); if(layer>=2) idet+=240; // add n SPD modules if(layer>=4) idet+=260; // add n SPD modules if(status==4) outInZ=kTRUE; if(tpcin) { if(status==1) fHistClusterMapITSMIok->Fill(layer); if(status==2) fHistClusterMapITSMIbad->Fill(layer); if(status==3) fHistClusterMapITSMIskipped->Fill(layer); if(status==4) fHistClusterMapITSMIoutinz->Fill(layer); if(status==5) fHistClusterMapITSMInocls->Fill(layer); if(status==6) fHistClusterMapITSMInorefit->Fill(layer); if(status==1 || status==2 || status==4) { fHistClusterMapITSMIokoutinzbad->Fill(layer); nclsokbadoutinzITS++; } } else { if(status==1) fHistClusterMapITSSAok->Fill(layer); if(status==2) fHistClusterMapITSSAbad->Fill(layer); if(status==3) fHistClusterMapITSSAskipped->Fill(layer); if(status==4) fHistClusterMapITSSAoutinz->Fill(layer); if(status==5) fHistClusterMapITSSAnocls->Fill(layer); if(status==6) fHistClusterMapITSSAnorefit->Fill(layer); if(status==1 || status==2 || status==4) fHistClusterMapITSSAokoutinzbad->Fill(layer); if(status==1 && !outInZ) {fHistClusterMapITSSAokInAcc->Fill(layer);fHistClusterMapModuleITSSAokInAcc->Fill(idet);} if(status==2 && !outInZ) {fHistClusterMapITSSAbadInAcc->Fill(layer);fHistClusterMapModuleITSSAbadInAcc->Fill(idet);} if(status==3 && !outInZ) fHistClusterMapITSSAskippedInAcc->Fill(layer); if(status==4 && !outInZ) fHistClusterMapITSSAoutinzInAcc->Fill(layer); if(status==5 && !outInZ) {fHistClusterMapITSSAnoclsInAcc->Fill(layer);fHistClusterMapModuleITSSAnoclsInAcc->Fill(idet);} if(status==6 && !outInZ) fHistClusterMapITSSAnorefitInAcc->Fill(layer); if((status==1 || status==2 || status==4) && !outInZ) fHistClusterMapITSSAokoutinzbadInAcc->Fill(layer); } if(TESTBIT(track->GetITSClusterMap(),layer)) { if(tpcin) { fHistClusterMapITSMI->Fill(layer); } else { fHistClusterMapITSSA->Fill(layer); if(!outInZ) fHistClusterMapITSSAInAcc->Fill(layer); } } } // TPC track findable in ITS if(tpcin && track->GetNcls(1)>=50 && TMath::Abs(track->GetTPCInnerParam()->GetD(0,0,fESD->GetMagneticField()))<3.) { itsfindable=kTRUE; Double_t zAtSSDouter=100,zAtSDDouter=100,zAtSPDouter=100; track->GetZAt(rSSDouter,fESD->GetMagneticField(),zAtSSDouter); track->GetZAt(rSDDouter,fESD->GetMagneticField(),zAtSDDouter); track->GetZAt(rSPDouter,fESD->GetMagneticField(),zAtSPDouter); fHistPtTPC->Fill(track->Pt()); if(TMath::Abs(track->Eta())<0.9 && TMath::Abs(zAtSSDouter)<zSSDouter && TMath::Abs(zAtSDDouter)<zSDDouter && TMath::Abs(zAtSPDouter)<zSPDouter) { itsfindableAcc=kTRUE; fHistPtTPCInAcc->Fill(track->Pt()); fHistPhiTPCInAcc->Fill(track->Phi()); } } if(itsfindable&&itsrefit) { if(nclsITS==6) fHistPtITSMI6->Fill(track->Pt()); if(nclsITS==5) fHistPtITSMI5->Fill(track->Pt()); if(nclsITS==4) fHistPtITSMI4->Fill(track->Pt()); if(nclsITS==3) fHistPtITSMI3->Fill(track->Pt()); if(nclsITS==2) fHistPtITSMI2->Fill(track->Pt()); if(track->HasPointOnITSLayer(0) && track->HasPointOnITSLayer(1)) fHistPtITSMISPD->Fill(track->Pt()); if(track->HasPointOnITSLayer(0) || track->HasPointOnITSLayer(1)) fHistPtITSMIoneSPD->Fill(track->Pt()); if(nclsokbadoutinzITS==6) fHistPtITSMIokbadoutinz6->Fill(track->Pt()); } if(itsfindableAcc&&itsrefit) { if(nclsITS==6) fHistPtITSMI6InAcc->Fill(track->Pt()); if(nclsITS==5) fHistPtITSMI5InAcc->Fill(track->Pt()); if(nclsITS==4) fHistPtITSMI4InAcc->Fill(track->Pt()); if(nclsITS==3) fHistPtITSMI3InAcc->Fill(track->Pt()); if(nclsITS==2) fHistPtITSMI2InAcc->Fill(track->Pt()); if(track->HasPointOnITSLayer(0) && track->HasPointOnITSLayer(1)) fHistPtITSMISPDInAcc->Fill(track->Pt()); if(track->HasPointOnITSLayer(0) || track->HasPointOnITSLayer(1)) fHistPtITSMIoneSPDInAcc->Fill(track->Pt()); if(nclsokbadoutinzITS==6) fHistPtITSMIokbadoutinz6InAcc->Fill(track->Pt()); if(nclsokbadoutinzITS==5) fHistPtITSMIokbadoutinz5InAcc->Fill(track->Pt()); if(nclsokbadoutinzITS==4) fHistPtITSMIokbadoutinz4InAcc->Fill(track->Pt()); if(nclsokbadoutinzITS==6) fHistPhiITSMIokbadoutinz6InAcc->Fill(track->Phi()); } if(tpcin) { fHistNclsITSMI->Fill(nclsITS); } else { fHistNclsITSSA->Fill(nclsITS); if(!outInZ) fHistNclsITSSAInAcc->Fill(nclsITS); } if(tpcin && fUseITSSAforNtuples) continue; // only ITS-SA for ntuples if(!tpcin && !fUseITSSAforNtuples) continue; // only ITS-TPC for ntuples Int_t iITSflag=0; //ITSflag takes the value 0 if the track has no cluster assigned in the SPDs, 1 (2) if one cluster is assigned in SPD1(2), 3 if two clusters are present. Then the same adding 10,20 or 30 for SDD and 100,200 or 300 for SSD if(track->HasPointOnITSLayer(0)) iITSflag+=1; if(track->HasPointOnITSLayer(1)) iITSflag+=2; if(track->HasPointOnITSLayer(2)) iITSflag+=10; if(track->HasPointOnITSLayer(3)) iITSflag+=20; if(track->HasPointOnITSLayer(4)) iITSflag+=100; if(track->HasPointOnITSLayer(5)) iITSflag+=200; if(iITSflag==333 && track->GetNcls(0)<6) printf(" ERROR %d %d\n",track->GetNcls(0),track->GetLabel()); // number of associated ITS clusters iITSflag += 1000*track->GetNcls(0); // number of associated TPC clusters iITSflag += 100000*track->GetNcls(1); // if MC info and is available // write the number of ITS clusters produced by this track Int_t nITSclsMC=0; if(fReadMC && fReadRPLabels) { nITSclsMC = NumberOfITSClustersMC(trkLabel); if(nITSclsMC>=0) iITSflag += 10000*nITSclsMC; } if(!vertexESD) continue; if(!(vertexESD->GetStatus())) continue; // impact parameter to VertexTracks Double_t d0z0[2],covd0z0[3]; track->PropagateToDCA(vertexESD,fESD->GetMagneticField(),100.,d0z0,covd0z0); if(covd0z0[0]<0. || covd0z0[2]<0.) continue; // if MC info is available: get particle properties Float_t ptMC=-999.,pdgMC=-999.,d0MC=-999.; Double_t d0z0MCv[2]={-999.,-999.},covd0z0MCv[3]={1.,1.,1.}; if(fReadMC) { part = (TParticle*)stack->Particle(trkLabel); ptMC=part->Pt(); pdgMC=part->GetPdgCode(); d0MC=ParticleImpParMC(part,vertexMC,0.1*fESD->GetMagneticField()); track->PropagateToDCA(vertexMC,fESD->GetMagneticField(),100.,d0z0MCv,covd0z0MCv); if(covd0z0MCv[0]<0. || covd0z0MCv[2]<0.) continue; // flag fake tracks if(track->GetLabel()<0) iITSflag *= -1; } Double_t sigmad0MCv=TMath::Sqrt(covd0z0MCv[0]); if(!itsrefit) sigmad0MCv *= -1.; // fill ntuple with track properties if(fFillNtuples && SelectPt(track->Pt())) { Float_t fillArray[19]={track->Pt(),track->Eta(),track->Phi(),d0z0[0],d0z0[1],TMath::Sqrt(covd0z0[0]),TMath::Sqrt(covd0z0[2]),ptMC,pdgMC,d0MC,d0z0MCv[0],d0z0MCv[1],sigmad0MCv,TMath::Sqrt(covd0z0MCv[2]),(Float_t)iITSflag}; fNtupleESDTracks->Fill(fillArray); } //--------------------------------------------- // AliTrackPoints: alignment checks // if(!fFillNtuples) continue; if(!fESDfriend) continue; const AliTrackPointArray *array = track->GetTrackPointArray(); if(!array) continue; AliTrackPoint point; Int_t pointOnLayer[6]={0,0,0,0,0,0}; Int_t indexAssociated[6]={-1,-1,-1,-1,-1,-1},indexExtra=-1; Bool_t extra=kFALSE; Int_t layerId,layerExtra=-1; for(Int_t ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); Float_t r = TMath::Sqrt(point.GetX()*point.GetX()+point.GetY()*point.GetY()); if(r>3 && r<6) { layerId = 0; } else if(r>6 && r<8) { layerId = 1; } else if(r>8 && r<18) { layerId = 2; } else if(r>18 && r<30) { layerId = 3; } else if(r>30 && r<40) { layerId = 4; } else if(r>40 && r<50) { layerId = 5; } else { layerId=100; } // only ITS points if(layerId>5) continue; if(!point.IsExtra()) { pointOnLayer[layerId]++; indexAssociated[layerId]=ipt; } else { // this is an extra cluster extra=kTRUE; layerExtra=layerId; indexExtra=ipt; } } // end loop on AliTrackPoints TString vtitle = spdv->GetTitle(); if(!vtitle.Contains("3D")) continue; // SPD tracklet if(indexAssociated[0]>=0 && indexAssociated[1]>=0) { AliTrackPoint pointSPD1,pointSPD2; array->GetPoint(pointSPD1,indexAssociated[0]); array->GetPoint(pointSPD2,indexAssociated[1]); Float_t phi=TMath::ATan2(pointSPD2.GetY()-pointSPD1.GetY(),pointSPD2.GetX()-pointSPD1.GetX()); Float_t lambda=TMath::ATan((pointSPD2.GetZ()-pointSPD1.GetZ())/TMath::Sqrt((pointSPD2.GetX()-pointSPD1.GetX())*(pointSPD2.GetX()-pointSPD1.GetX())+(pointSPD2.GetY()-pointSPD1.GetY())*(pointSPD2.GetY()-pointSPD1.GetY()))); Float_t theta=0.5*TMath::Pi()-lambda; TParticle particle(211,0,0,0,0,0,TMath::Cos(phi),TMath::Sin(phi),TMath::Tan(lambda),10.,pointSPD1.GetX(),pointSPD1.GetY(),pointSPD1.GetZ(),0); AliESDtrack tracklet(&particle); Float_t dz[2]; // distance to primary SPD (only if 3D and high multiplicity) if(spdv->GetNContributors()>10) { tracklet.GetDZ(spdv->GetXv(),spdv->GetYv(),spdv->GetZv(),0,dz); //tracklet.GetDZ(-0.07,0.25,spdv->GetZv(),0,dz); fNtupleITSAlignSPDTracklets->Fill(phi,theta,0.5*(pointSPD1.GetZ()+pointSPD2.GetZ()),dz[0],dz[1],track->Pt()); } } // distance to extra if(extra && spdv->GetNContributors()>4 && indexAssociated[layerExtra]>-1) { AliTrackPoint pointExtra,pointAssociated; array->GetPoint(pointAssociated,indexAssociated[layerExtra]); array->GetPoint(pointExtra,indexExtra); Float_t phiExtra = TMath::ATan2(pointExtra.GetY()-spdv->GetYv(),pointExtra.GetX()-spdv->GetXv()); Float_t phiAssociated = TMath::ATan2(pointAssociated.GetY()-spdv->GetYv(),pointAssociated.GetX()-spdv->GetXv()); Float_t rExtra = TMath::Sqrt((pointExtra.GetX()-spdv->GetXv())*(pointExtra.GetX()-spdv->GetXv())+(pointExtra.GetY()-spdv->GetYv())*(pointExtra.GetY()-spdv->GetYv())); Float_t rAssociated = TMath::Sqrt((pointAssociated.GetX()-spdv->GetXv())*(pointAssociated.GetX()-spdv->GetXv())+(pointAssociated.GetY()-spdv->GetYv())*(pointAssociated.GetY()-spdv->GetYv())); Float_t dzExtra[2]; dzExtra[0] = (phiExtra-phiAssociated)*0.5*(rExtra+rAssociated); dzExtra[1] = pointExtra.GetZ()-pointAssociated.GetZ()-(rExtra-rAssociated)*(pointAssociated.GetZ()-spdv->GetZv())/rAssociated; Float_t xlocExtra=-100.,zlocExtra=-100.; fNtupleITSAlignExtra->Fill(layerExtra,pointExtra.GetX(),pointExtra.GetY(),pointExtra.GetZ(),dzExtra[0],dzExtra[1],xlocExtra,zlocExtra,nclsITS,track->Pt()); } } // end loop on tracks if(vertexMC) { delete vertexMC; vertexMC=0; } return; } //________________________________________________________________________ void AliAnalysisTaskITSTrackingCheck::Terminate(Option_t *) { // Draw result to the screen // Called once at the end of the query fOutput = dynamic_cast<TList*> (GetOutputData(0)); if (!fOutput) { Printf("ERROR: fOutput not available"); return; } fHistNtracks = dynamic_cast<TH1F*>(fOutput->FindObject("fHistNtracks")); fHistNclsITSMI = dynamic_cast<TH1F*>(fOutput->FindObject("fHistNclsITSMI")); fHistNclsITSSA = dynamic_cast<TH1F*>(fOutput->FindObject("fHistNclsITSSA")); fHistClusterMapITSMI = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMI")); fHistClusterMapITSMIbad = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMIbad")); fHistClusterMapITSMIskipped = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMIskipped")); fHistClusterMapITSMIoutinz = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMIoutinz")); fHistClusterMapITSMInorefit = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMInorefit")); fHistClusterMapITSMInocls = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSMInocls")); fHistClusterMapITSSA = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSA")); fHistClusterMapITSSAbad = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAbad")); fHistClusterMapITSSAskipped = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAskipped")); fHistClusterMapITSSAoutinz = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAoutinz")); fHistClusterMapITSSAnorefit = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAnorefit")); fHistClusterMapITSSAnocls = dynamic_cast<TH1F*>(fOutput->FindObject("fHistClusterMapITSSAnocls")); fNtupleESDTracks = dynamic_cast<TNtuple*>(fOutput->FindObject("fNtupleESDTracks")); fNtupleITSAlignExtra = dynamic_cast<TNtuple*>(fOutput->FindObject("fNtupleITSAlignExtra")); fNtupleITSAlignSPDTracklets = dynamic_cast<TNtuple*>(fOutput->FindObject("fNtupleITSAlignSPDTracklets")); return; } //--------------------------------------------------------------------------- Int_t AliAnalysisTaskITSTrackingCheck::NumberOfITSClustersMC(Int_t label) const { // // Return number of ITS clusters produced by MC particle with given label // AliESDInputHandlerRP *esdHRP = dynamic_cast<AliESDInputHandlerRP*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if(!esdHRP) return -1; TTree *cTree = (TTree*)esdHRP->GetTreeR("ITS"); if(!cTree) return -1; TClonesArray *clusters=0; // new TClonesArray("AliITSRecPoint",10000); cTree->SetBranchAddress("ITSRecPoints",&clusters); if(!clusters) return -1; AliITSRecPoint *c=0; Int_t i,n,icl,lay,ilab; Int_t ncls[6]={0,0,0,0,0,0}; Int_t nclstot=0; for(i=0; i<2198; i++) { cTree->GetEvent(i); n=clusters->GetEntriesFast(); for (icl=0; icl<n; icl++) { c=(AliITSRecPoint*)clusters->UncheckedAt(icl); lay=c->GetLayer(); for(ilab=0;ilab<3;ilab++) { if(c->GetLabel(ilab)==label) ncls[lay]++; } } } for(i=0;i<6;i++) { if(ncls[i]) nclstot++; } return nclstot; //return label*0; } //--------------------------------------------------------------------------- Double_t AliAnalysisTaskITSTrackingCheck::ParticleImpParMC(TParticle *part, AliESDVertex *vert, Double_t bzT) const { // // Return the MC value of the impact parameter // Double_t vx=part->Vx()-vert->GetX(); Double_t vy=part->Vy()-vert->GetY(); Double_t pt=part->Pt(); Double_t px=part->Px(); Double_t py=part->Py(); Double_t charge = (part->GetPdgCode()>0. ? 1. : -1.); if(TMath::Abs(part->GetPdgCode())<100) charge*=-1.; if(px<0.000001) px=0.000001; Double_t rAnd=((10./2.99792458)*pt/bzT)*100.; Double_t center[3],d0; center[0]=vx-(1./charge)*rAnd*(py/pt); center[1]=vy+(1./charge)*rAnd*(px/pt); center[2]=TMath::Sqrt(center[0]*center[0]+center[1]*center[1]); d0 = -center[2]+rAnd; return d0; } //--------------------------------------------------------------------------- Bool_t AliAnalysisTaskITSTrackingCheck::SelectPt(Double_t pt) { // // Keep only tracks in given pt bins // Double_t ptlower[10]={0.29,0.49,0.75,0.9,1.9,3.5,6.5, 9.,19.,27.}; Double_t ptupper[10]={0.31,0.51,0.85,1.1,2.1,4.5,7.5,11.,21.,33.}; for(Int_t i=0; i<10; i++) { if(pt>ptlower[i] && pt<ptupper[i]) { fCountsPerPtBin[i]++; return kTRUE; } } return kFALSE; //return kTRUE; }
#include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <string> #include <list> #include <vector> #include <sstream> #include <algorithm> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/if.h> #include <linux/if_tun.h> #include <poll.h> #include <rina/api.h> #include <pthread.h> #include <rina/cdap.hpp> #include "iporina.pb.h" using namespace std; /* * Internal data structures. */ struct IPSubnet { string repr; uint32_t netaddr; unsigned netbits; IPSubnet() : netaddr(0), netbits(0) { } IPSubnet(const string &p); }; struct Local { string app_name; list<string> dif_names; Local() { } Local(const string &a) : app_name(a) { } }; struct Remote { string app_name; string dif_name; IPSubnet tun_subnet; string tun_name; int tun_fd; /* Flow for control connection. */ int rfd; Remote() : tun_fd(-1) { } Remote(const string &a, const string &d, const IPSubnet &i) : app_name(a), dif_name(d), tun_subnet(i), tun_fd(-1), rfd(-1) { } }; struct Route { IPSubnet subnet; Route(const IPSubnet &i) : subnet(i) { } }; struct IPoRINA { /* Enable verbose mode */ int verbose; /* Control device to listen for incoming connections. */ int rfd; Local local; list<Remote> remotes; list<Route> routes; IPoRINA() : verbose(0), rfd(-1) { } }; /* * CDAP objects with their serialization and deserialization routines */ struct Obj { virtual int serialize(char *buf, unsigned int size) const = 0; virtual ~Obj() { } }; static int ser_common(::google::protobuf::MessageLite &gm, char *buf, int size) { if (gm.ByteSize() > size) { fprintf(stderr, "User buffer too small [%u/%u]\n", gm.ByteSize(), size); return -1; } gm.SerializeToArray(buf, size); return gm.ByteSize(); } struct Hello : public Obj { string tun_subnet; /* Subnet to be used for the tunnel */ uint32_t num_routes; /* How many route to exchange */ Hello() : num_routes(0) { } Hello(const char *buf, unsigned int size); int serialize(char *buf, unsigned int size) const; }; static void gpb2Hello(Hello &m, const gpb::hello_msg_t &gm) { m.tun_subnet = gm.tun_subnet(); m.num_routes = gm.num_routes(); } static int Hello2gpb(const Hello &m, gpb::hello_msg_t &gm) { gm.set_tun_subnet(m.tun_subnet); gm.set_num_routes(m.num_routes); return 0; } Hello::Hello(const char *buf, unsigned int size) : num_routes(0) { gpb::hello_msg_t gm; gm.ParseFromArray(buf, size); gpb2Hello(*this, gm); } int Hello::serialize(char *buf, unsigned int size) const { gpb::hello_msg_t gm; Hello2gpb(*this, gm); return ser_common(gm, buf, size); } struct RouteObj : public Obj { string route; /* Route represented as a string. */ RouteObj() { } RouteObj(const string& s) : route(s) { } RouteObj(const char *buf, unsigned int size); int serialize(char *buf, unsigned int size) const; }; static void gpb2RouteObj(RouteObj &m, const gpb::route_msg_t &gm) { m.route = gm.route(); } static int RouteObj2gpb(const RouteObj &m, gpb::route_msg_t &gm) { gm.set_route(m.route); return 0; } RouteObj::RouteObj(const char *buf, unsigned int size) { gpb::route_msg_t gm; gm.ParseFromArray(buf, size); gpb2RouteObj(*this, gm); } int RouteObj::serialize(char *buf, unsigned int size) const { gpb::route_msg_t gm; RouteObj2gpb(*this, gm); return ser_common(gm, buf, size); } /* Send a CDAP message after attaching a serialized object. */ static int cdap_obj_send(CDAPConn *conn, CDAPMessage *m, int invoke_id, const Obj *obj) { char objbuf[4096]; int objlen; if (obj) { objlen = obj->serialize(objbuf, sizeof(objbuf)); if (objlen < 0) { errno = EINVAL; fprintf(stderr, "serialization failed\n"); return objlen; } m->set_obj_value(objbuf, objlen); } return conn->msg_send(m, invoke_id); } /* * Global variables to hold the daemon state. */ static IPoRINA _g; static IPoRINA *g = &_g; #if 0 static string int2string(int x) { stringstream sstr; sstr << x; return sstr.str(); } #endif static int string2int(const string& s, int& ret) { char *dummy; const char *cstr = s.c_str(); ret = strtoul(cstr, &dummy, 10); if (!s.size() || *dummy != '\0') { ret = ~0U; return -1; } return 0; } IPSubnet::IPSubnet(const string &_p) : repr(_p) { stringstream ss; string p = _p; string digit; size_t slash; int m; slash = p.find("/"); if (slash == string::npos) { goto ex; } /* Extract the mask m in "a.b.c.d/m" */ if (string2int(p.substr(slash + 1), m)) { goto ex; } if (m < 1 || m > 30) { goto ex; } netbits = m; p = p.substr(0, slash); /* Extract a, b, c and d. */ std::replace(p.begin(), p.end(), '.', ' '); ss = stringstream(p); netaddr = 0; while (ss >> digit) { int d; if (string2int(digit, d)) { goto ex; } if (d < 0 || d > 255) { goto ex; } netaddr <<= 8; netaddr |= (unsigned)d; } return; ex: throw "Invalid IP prefix"; } /* Arguments taken by the function: * * char *dev: the name of an interface (or '\0'). MUST have enough * space to hold the interface name if '\0' is passed * int flags: interface flags (eg, IFF_TUN, IFF_NO_PI, IFF_TAP etc.) */ static int tun_alloc(char *dev, int flags) { struct ifreq ifr; int fd, err; if ((fd = open("/dev/net/tun", O_RDWR)) < 0) { perror("open(/dev/net/tun)"); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = flags; /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */ if (*dev) { /* If a device name was specified, put it in the structure; otherwise, * the kernel will try to allocate the "next" device of the * specified type */ strncpy(ifr.ifr_name, dev, IFNAMSIZ); } /* Try to create the device */ if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { perror("ioctl(TUNSETIFF)"); close(fd); return err; } /* If the operation was successful, write back the name of the * interface to the variable "dev", so the caller can know * it. Note that the caller MUST reserve space in *dev (see calling * code below) */ strcpy(dev, ifr.ifr_name); /* this is the special file descriptor that the caller will use to talk * with the virtual interface */ return fd; } static int parse_conf(const char *path) { ifstream fin(path); if (fin.fail()) { cerr << "Cannot open configuration file " << path << endl; return -1; } for (unsigned int lines_cnt = 1; !fin.eof(); lines_cnt++) { string line; getline(fin, line); istringstream iss(line); vector<string> tokens; string token; while (iss >> token) { tokens.push_back(token); } if (tokens.size() <= 0 || tokens[0][0] == '#') { /* Ignore comments and white spaces. */ continue; } if (tokens[0] == "local") { if (tokens.size() < 3) { cerr << "Invalid 'local' directive at line " << lines_cnt << endl; return -1; } if (g->local.app_name.size()) { cerr << "Duplicated 'local' directive at line " << lines_cnt << endl; return -1; } g->local = Local(tokens[1]); for (unsigned int i = 2; i < tokens.size(); i ++) { g->local.dif_names.push_back(tokens[i]); } } else if (tokens[0] == "remote") { IPSubnet subnet; if (tokens.size() != 4) { cerr << "Invalid 'remote' directive at line " << lines_cnt << endl; return -1; } try { subnet = IPSubnet(tokens[3]); } catch (...) { cerr << "Invalid IP prefix at line " << lines_cnt << endl; return -1; } g->remotes.push_back(Remote(tokens[1], tokens[2], subnet)); } else if (tokens[0] == "route") { IPSubnet subnet; if (tokens.size() != 2) { cerr << "Invalid 'route' directive at line " << lines_cnt << endl; return -1; } try { subnet = IPSubnet(tokens[1]); } catch (...) { cerr << "Invalid IP prefix at line " << lines_cnt << endl; return -1; } g->routes.push_back(Route(subnet)); } } fin.close(); return 0; } static void dump_conf(void) { cout << "Local: " << g->local.app_name << "in DIFs"; for (list<string>::iterator l = g->local.dif_names.begin(); l != g->local.dif_names.end(); l ++) { cout << " " << *l; } cout << endl; cout << "Remotes:" << endl; for (list<Remote>::iterator l = g->remotes.begin(); l != g->remotes.end(); l ++) { cout << " " << l->app_name << " in DIF " << l->dif_name << ", tunnel prefix " << l->tun_subnet.repr << endl; } cout << "Advertised routes:" << endl; for (list<Route>::iterator l = g->routes.begin(); l != g->routes.end(); l ++) { cout << " " << l->subnet.repr << endl; } } static int remote_tun_alloc(Remote &r) { char tun_name[IFNAMSIZ]; tun_name[0] = '\0'; r.tun_fd = tun_alloc(tun_name, IFF_TUN | IFF_NO_PI); if (r.tun_fd < 0) { cerr << "Failed to create tunnel" << endl; return -1; } r.tun_name = tun_name; if (g->verbose) { cout << "Created tunnel device " << r.tun_name << endl; } return 0; } static int setup(void) { g->rfd = rina_open(); if (g->rfd < 0) { perror("rina_open()"); return -1; } /* Register us to one or more local DIFs. */ for (list<string>::iterator l = g->local.dif_names.begin(); l != g->local.dif_names.end(); l ++) { int ret; ret = rina_register(g->rfd, l->c_str(), g->local.app_name.c_str(), 0); if (ret) { perror("rina_register()"); cerr << "Failed to register " << g->local.app_name << " in DIF " << *l << endl; return -1; } } /* Create a TUN device for each remote. */ for (list<Remote>::iterator l = g->remotes.begin(); l != g->remotes.end(); l ++) { if (remote_tun_alloc(*l)) { return -1; } } return 0; } /* Try to connect to all the user-specified remotes. */ static void * connect_to_remotes(void *opaque) { string myname = g->local.app_name; for (;;) { for (list<Remote>::iterator re = g->remotes.begin(); re != g->remotes.end(); re ++) { struct rina_flow_spec spec; struct pollfd pfd; int ret; int wfd; if (re->rfd >= 0) { /* We are already connected to this remote. */ continue; } /* Tyr to allocate a reliable flow. */ rina_flow_spec_default(&spec); spec.max_sdu_gap = 0; spec.in_order_delivery = 1; spec.msg_boundaries = 1; spec.spare3 = 1; wfd = rina_flow_alloc(re->dif_name.c_str(), myname.c_str(), re->app_name.c_str(), &spec, RINA_F_NOWAIT); if (wfd < 0) { perror("rina_flow_alloc()"); cout << "Failed to connect to remote " << re->app_name << " through DIF " << re->dif_name << endl; continue; } pfd.fd = wfd; pfd.events = POLLIN; ret = poll(&pfd, 1, 3000); if (ret <= 0) { if (ret < 0) { perror("poll(wfd)"); } else if (g->verbose) { cout << "Failed to connect to remote " << re->app_name << " through DIF " << re->dif_name << endl; } close(wfd); continue; } re->rfd = rina_flow_alloc_wait(wfd); if (re->rfd < 0) { perror("rina_flow_alloc_wait()"); cout << "Failed to connect to remote " << re->app_name << " through DIF " << re->dif_name << endl; continue; } if (g->verbose) { cout << "Connected to remote " << re->app_name << " through DIF " << re->dif_name << endl; } CDAPConn conn(re->rfd, 1); CDAPMessage m, *rm = NULL; Hello hello; /* CDAP connection setup. */ m.m_connect(gpb::AUTH_NONE, NULL, /* src */ myname, /* dst */ re->app_name); if (conn.msg_send(&m, 0)) { cerr << "Failed to send M_CONNECT" << endl; goto abor; } rm = conn.msg_recv(); if (rm->op_code != gpb::M_CONNECT_R) { cerr << "M_CONNECT_R expected" << endl; goto abor; } delete rm; rm = NULL; cout << "Connected to remote peer" << endl; /* Exchange routes. */ m.m_start(gpb::F_NO_FLAGS, "hello", "/hello", 0, 0, string()); hello.num_routes = g->routes.size(); hello.tun_subnet = re->tun_subnet.repr; if (cdap_obj_send(&conn, &m, 0, &hello)) { cerr << "Failed to send M_START" << endl; goto abor; } for (list<Route>::iterator ro = g->routes.begin(); ro != g->routes.end(); ro ++) { RouteObj robj(ro->subnet.repr); m.m_write(gpb::F_NO_FLAGS, "route", "/routes", 0, 0, string()); if (cdap_obj_send(&conn, &m, 0, &robj)) { cerr << "Failed to send M_WRITE" << endl; goto abor; } } abor: if (rm) { delete rm; } close(re->rfd); } sleep(5); } pthread_exit(NULL); } static void usage(void) { cout << "iporinad [OPTIONS]" << endl << " -h : show this help" << endl << " -c CONF_FILE: path to configuration file" << endl; } int main(int argc, char **argv) { const char *confpath = "/etc/iporinad.conf"; struct pollfd pfd[1]; pthread_t fa_th; int opt; while ((opt = getopt(argc, argv, "hc:v")) != -1) { switch (opt) { case 'h': usage(); return 0; case 'c': confpath = optarg; break; case 'v': g->verbose ++; break; default: printf(" Unrecognized option %c\n", opt); usage(); return -1; } } if (parse_conf(confpath)) { return -1; } if (g->verbose) { dump_conf(); } if (setup()) { return -1; } if (pthread_create(&fa_th, NULL, connect_to_remotes, NULL)) { perror("pthread_create()"); return -1; } /* Wait for incoming control connections. */ for (;;) { Remote r; int cfd; int ret; pfd[0].fd = g->rfd; pfd[0].events = POLLIN; ret = poll(pfd, 1, -1); if (ret < 0) { perror("poll(lfd)"); return -1; } if (!pfd[0].revents & POLLIN) { continue; } cfd = rina_flow_accept(g->rfd, NULL, NULL, 0); if (cfd < 0) { if (errno == ENOSPC) { continue; } perror("rina_flow_accept(lfd)"); return -1; } cout << "Flow accepted!" << endl; r.rfd = cfd; if (remote_tun_alloc(r)) { close(r.rfd); continue; } g->remotes.push_back(r); CDAPConn conn(r.rfd, 1); CDAPMessage *rm; CDAPMessage m; const char *objbuf; size_t objlen; Hello hello; rm = conn.msg_recv(); if (rm->op_code != gpb::M_CONNECT) { cerr << "M_CONNECT expected" << endl; goto abor; } r.app_name = rm->src_appl; r.dif_name = string(); m.m_connect_r(rm, 0, string()); if (conn.msg_send(&m, rm->invoke_id)) { cerr << "Failed to send M_CONNECT_R" << endl; goto abor; } delete rm; rm = NULL; rm = conn.msg_recv(); if (rm->op_code != gpb::M_START) { cerr << "M_START expected" << endl; goto abor; } rm->get_obj_value(objbuf, objlen); if (!objbuf) { cerr << "M_START does not contain a nested message" << endl; goto abor; } hello = Hello(objbuf, objlen); delete rm; rm = NULL; cout << "Hello received " << hello.num_routes << " " << hello.tun_subnet << endl; for (unsigned int i = 0; i < hello.num_routes; i ++) { RouteObj robj; rm = conn.msg_recv(); if (rm->op_code != gpb::M_WRITE) { cerr << "M_WRITE expected" << endl; goto abor; } rm->get_obj_value(objbuf, objlen); if (!objbuf) { cerr << "M_WRITE does not contain a nested message" << endl; goto abor; } robj = RouteObj(objbuf, objlen); delete rm; rm = NULL; cout << "Received route " << robj.route << endl; } abor: close(r.rfd); } pthread_exit(NULL); return 0; } tools: iporinad: fix compilation issues #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <string> #include <list> #include <vector> #include <sstream> #include <algorithm> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/if.h> #include <linux/if_tun.h> #include <poll.h> #include <pthread.h> #include <errno.h> #include <stdint.h> #include <rina/api.h> #include <rina/cdap.hpp> #include "iporina.pb.h" using namespace std; /* * Internal data structures. */ struct IPSubnet { string repr; uint32_t netaddr; unsigned netbits; IPSubnet() : netaddr(0), netbits(0) { } IPSubnet(const string &p); }; struct Local { string app_name; list<string> dif_names; Local() { } Local(const string &a) : app_name(a) { } }; struct Remote { string app_name; string dif_name; IPSubnet tun_subnet; string tun_name; int tun_fd; /* Flow for control connection. */ int rfd; Remote() : tun_fd(-1) { } Remote(const string &a, const string &d, const IPSubnet &i) : app_name(a), dif_name(d), tun_subnet(i), tun_fd(-1), rfd(-1) { } }; struct Route { IPSubnet subnet; Route(const IPSubnet &i) : subnet(i) { } }; struct IPoRINA { /* Enable verbose mode */ int verbose; /* Control device to listen for incoming connections. */ int rfd; Local local; list<Remote> remotes; list<Route> routes; IPoRINA() : verbose(0), rfd(-1) { } }; /* * CDAP objects with their serialization and deserialization routines */ struct Obj { virtual int serialize(char *buf, unsigned int size) const = 0; virtual ~Obj() { } }; static int ser_common(::google::protobuf::MessageLite &gm, char *buf, int size) { if (gm.ByteSize() > size) { fprintf(stderr, "User buffer too small [%u/%u]\n", gm.ByteSize(), size); return -1; } gm.SerializeToArray(buf, size); return gm.ByteSize(); } struct Hello : public Obj { string tun_subnet; /* Subnet to be used for the tunnel */ uint32_t num_routes; /* How many route to exchange */ Hello() : num_routes(0) { } Hello(const char *buf, unsigned int size); int serialize(char *buf, unsigned int size) const; }; static void gpb2Hello(Hello &m, const gpb::hello_msg_t &gm) { m.tun_subnet = gm.tun_subnet(); m.num_routes = gm.num_routes(); } static int Hello2gpb(const Hello &m, gpb::hello_msg_t &gm) { gm.set_tun_subnet(m.tun_subnet); gm.set_num_routes(m.num_routes); return 0; } Hello::Hello(const char *buf, unsigned int size) : num_routes(0) { gpb::hello_msg_t gm; gm.ParseFromArray(buf, size); gpb2Hello(*this, gm); } int Hello::serialize(char *buf, unsigned int size) const { gpb::hello_msg_t gm; Hello2gpb(*this, gm); return ser_common(gm, buf, size); } struct RouteObj : public Obj { string route; /* Route represented as a string. */ RouteObj() { } RouteObj(const string& s) : route(s) { } RouteObj(const char *buf, unsigned int size); int serialize(char *buf, unsigned int size) const; }; static void gpb2RouteObj(RouteObj &m, const gpb::route_msg_t &gm) { m.route = gm.route(); } static int RouteObj2gpb(const RouteObj &m, gpb::route_msg_t &gm) { gm.set_route(m.route); return 0; } RouteObj::RouteObj(const char *buf, unsigned int size) { gpb::route_msg_t gm; gm.ParseFromArray(buf, size); gpb2RouteObj(*this, gm); } int RouteObj::serialize(char *buf, unsigned int size) const { gpb::route_msg_t gm; RouteObj2gpb(*this, gm); return ser_common(gm, buf, size); } /* Send a CDAP message after attaching a serialized object. */ static int cdap_obj_send(CDAPConn *conn, CDAPMessage *m, int invoke_id, const Obj *obj) { char objbuf[4096]; int objlen; if (obj) { objlen = obj->serialize(objbuf, sizeof(objbuf)); if (objlen < 0) { errno = EINVAL; fprintf(stderr, "serialization failed\n"); return objlen; } m->set_obj_value(objbuf, objlen); } return conn->msg_send(m, invoke_id); } /* * Global variables to hold the daemon state. */ static IPoRINA _g; static IPoRINA *g = &_g; #if 0 static string int2string(int x) { stringstream sstr; sstr << x; return sstr.str(); } #endif static int string2int(const string& s, int& ret) { char *dummy; const char *cstr = s.c_str(); ret = strtoul(cstr, &dummy, 10); if (!s.size() || *dummy != '\0') { ret = ~0U; return -1; } return 0; } IPSubnet::IPSubnet(const string &_p) : repr(_p) { string p = _p; string digit; size_t slash; int m; slash = p.find("/"); if (slash == string::npos) { throw "Invalid IP prefix"; } /* Extract the mask m in "a.b.c.d/m" */ if (string2int(p.substr(slash + 1), m)) { throw "Invalid IP prefix"; } if (m < 1 || m > 30) { throw "Invalid IP prefix"; } netbits = m; p = p.substr(0, slash); /* Extract a, b, c and d. */ std::replace(p.begin(), p.end(), '.', ' '); stringstream ss(p); netaddr = 0; while (ss >> digit) { int d; if (string2int(digit, d)) { throw "Invalid IP prefix"; } if (d < 0 || d > 255) { throw "Invalid IP prefix"; } netaddr <<= 8; netaddr |= (unsigned)d; } return; } /* Arguments taken by the function: * * char *dev: the name of an interface (or '\0'). MUST have enough * space to hold the interface name if '\0' is passed * int flags: interface flags (eg, IFF_TUN, IFF_NO_PI, IFF_TAP etc.) */ static int tun_alloc(char *dev, int flags) { struct ifreq ifr; int fd, err; if ((fd = open("/dev/net/tun", O_RDWR)) < 0) { perror("open(/dev/net/tun)"); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = flags; /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */ if (*dev) { /* If a device name was specified, put it in the structure; otherwise, * the kernel will try to allocate the "next" device of the * specified type */ strncpy(ifr.ifr_name, dev, IFNAMSIZ); } /* Try to create the device */ if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { perror("ioctl(TUNSETIFF)"); close(fd); return err; } /* If the operation was successful, write back the name of the * interface to the variable "dev", so the caller can know * it. Note that the caller MUST reserve space in *dev (see calling * code below) */ strcpy(dev, ifr.ifr_name); /* this is the special file descriptor that the caller will use to talk * with the virtual interface */ return fd; } static int parse_conf(const char *path) { ifstream fin(path); if (fin.fail()) { cerr << "Cannot open configuration file " << path << endl; return -1; } for (unsigned int lines_cnt = 1; !fin.eof(); lines_cnt++) { string line; getline(fin, line); istringstream iss(line); vector<string> tokens; string token; while (iss >> token) { tokens.push_back(token); } if (tokens.size() <= 0 || tokens[0][0] == '#') { /* Ignore comments and white spaces. */ continue; } if (tokens[0] == "local") { if (tokens.size() < 3) { cerr << "Invalid 'local' directive at line " << lines_cnt << endl; return -1; } if (g->local.app_name.size()) { cerr << "Duplicated 'local' directive at line " << lines_cnt << endl; return -1; } g->local = Local(tokens[1]); for (unsigned int i = 2; i < tokens.size(); i ++) { g->local.dif_names.push_back(tokens[i]); } } else if (tokens[0] == "remote") { IPSubnet subnet; if (tokens.size() != 4) { cerr << "Invalid 'remote' directive at line " << lines_cnt << endl; return -1; } try { subnet = IPSubnet(tokens[3]); } catch (...) { cerr << "Invalid IP prefix at line " << lines_cnt << endl; return -1; } g->remotes.push_back(Remote(tokens[1], tokens[2], subnet)); } else if (tokens[0] == "route") { IPSubnet subnet; if (tokens.size() != 2) { cerr << "Invalid 'route' directive at line " << lines_cnt << endl; return -1; } try { subnet = IPSubnet(tokens[1]); } catch (...) { cerr << "Invalid IP prefix at line " << lines_cnt << endl; return -1; } g->routes.push_back(Route(subnet)); } } fin.close(); return 0; } static void dump_conf(void) { cout << "Local: " << g->local.app_name << "in DIFs"; for (list<string>::iterator l = g->local.dif_names.begin(); l != g->local.dif_names.end(); l ++) { cout << " " << *l; } cout << endl; cout << "Remotes:" << endl; for (list<Remote>::iterator l = g->remotes.begin(); l != g->remotes.end(); l ++) { cout << " " << l->app_name << " in DIF " << l->dif_name << ", tunnel prefix " << l->tun_subnet.repr << endl; } cout << "Advertised routes:" << endl; for (list<Route>::iterator l = g->routes.begin(); l != g->routes.end(); l ++) { cout << " " << l->subnet.repr << endl; } } static int remote_tun_alloc(Remote &r) { char tun_name[IFNAMSIZ]; tun_name[0] = '\0'; r.tun_fd = tun_alloc(tun_name, IFF_TUN | IFF_NO_PI); if (r.tun_fd < 0) { cerr << "Failed to create tunnel" << endl; return -1; } r.tun_name = tun_name; if (g->verbose) { cout << "Created tunnel device " << r.tun_name << endl; } return 0; } static int setup(void) { g->rfd = rina_open(); if (g->rfd < 0) { perror("rina_open()"); return -1; } /* Register us to one or more local DIFs. */ for (list<string>::iterator l = g->local.dif_names.begin(); l != g->local.dif_names.end(); l ++) { int ret; ret = rina_register(g->rfd, l->c_str(), g->local.app_name.c_str(), 0); if (ret) { perror("rina_register()"); cerr << "Failed to register " << g->local.app_name << " in DIF " << *l << endl; return -1; } } /* Create a TUN device for each remote. */ for (list<Remote>::iterator l = g->remotes.begin(); l != g->remotes.end(); l ++) { if (remote_tun_alloc(*l)) { return -1; } } return 0; } /* Try to connect to all the user-specified remotes. */ static void * connect_to_remotes(void *opaque) { string myname = g->local.app_name; for (;;) { for (list<Remote>::iterator re = g->remotes.begin(); re != g->remotes.end(); re ++) { struct rina_flow_spec spec; struct pollfd pfd; int ret; int wfd; if (re->rfd >= 0) { /* We are already connected to this remote. */ continue; } /* Tyr to allocate a reliable flow. */ rina_flow_spec_default(&spec); spec.max_sdu_gap = 0; spec.in_order_delivery = 1; spec.msg_boundaries = 1; spec.spare3 = 1; wfd = rina_flow_alloc(re->dif_name.c_str(), myname.c_str(), re->app_name.c_str(), &spec, RINA_F_NOWAIT); if (wfd < 0) { perror("rina_flow_alloc()"); cout << "Failed to connect to remote " << re->app_name << " through DIF " << re->dif_name << endl; continue; } pfd.fd = wfd; pfd.events = POLLIN; ret = poll(&pfd, 1, 3000); if (ret <= 0) { if (ret < 0) { perror("poll(wfd)"); } else if (g->verbose) { cout << "Failed to connect to remote " << re->app_name << " through DIF " << re->dif_name << endl; } close(wfd); continue; } re->rfd = rina_flow_alloc_wait(wfd); if (re->rfd < 0) { perror("rina_flow_alloc_wait()"); cout << "Failed to connect to remote " << re->app_name << " through DIF " << re->dif_name << endl; continue; } if (g->verbose) { cout << "Connected to remote " << re->app_name << " through DIF " << re->dif_name << endl; } CDAPConn conn(re->rfd, 1); CDAPMessage m, *rm = NULL; Hello hello; /* CDAP connection setup. */ m.m_connect(gpb::AUTH_NONE, NULL, /* src */ myname, /* dst */ re->app_name); if (conn.msg_send(&m, 0)) { cerr << "Failed to send M_CONNECT" << endl; goto abor; } rm = conn.msg_recv(); if (rm->op_code != gpb::M_CONNECT_R) { cerr << "M_CONNECT_R expected" << endl; goto abor; } delete rm; rm = NULL; cout << "Connected to remote peer" << endl; /* Exchange routes. */ m.m_start(gpb::F_NO_FLAGS, "hello", "/hello", 0, 0, string()); hello.num_routes = g->routes.size(); hello.tun_subnet = re->tun_subnet.repr; if (cdap_obj_send(&conn, &m, 0, &hello)) { cerr << "Failed to send M_START" << endl; goto abor; } for (list<Route>::iterator ro = g->routes.begin(); ro != g->routes.end(); ro ++) { RouteObj robj(ro->subnet.repr); m.m_write(gpb::F_NO_FLAGS, "route", "/routes", 0, 0, string()); if (cdap_obj_send(&conn, &m, 0, &robj)) { cerr << "Failed to send M_WRITE" << endl; goto abor; } } abor: if (rm) { delete rm; } close(re->rfd); } sleep(5); } pthread_exit(NULL); } static void usage(void) { cout << "iporinad [OPTIONS]" << endl << " -h : show this help" << endl << " -c CONF_FILE: path to configuration file" << endl; } int main(int argc, char **argv) { const char *confpath = "/etc/iporinad.conf"; struct pollfd pfd[1]; pthread_t fa_th; int opt; while ((opt = getopt(argc, argv, "hc:v")) != -1) { switch (opt) { case 'h': usage(); return 0; case 'c': confpath = optarg; break; case 'v': g->verbose ++; break; default: printf(" Unrecognized option %c\n", opt); usage(); return -1; } } if (parse_conf(confpath)) { return -1; } if (g->verbose) { dump_conf(); } if (setup()) { return -1; } if (pthread_create(&fa_th, NULL, connect_to_remotes, NULL)) { perror("pthread_create()"); return -1; } /* Wait for incoming control connections. */ for (;;) { Remote r; int cfd; int ret; pfd[0].fd = g->rfd; pfd[0].events = POLLIN; ret = poll(pfd, 1, -1); if (ret < 0) { perror("poll(lfd)"); return -1; } if (!pfd[0].revents & POLLIN) { continue; } cfd = rina_flow_accept(g->rfd, NULL, NULL, 0); if (cfd < 0) { if (errno == ENOSPC) { continue; } perror("rina_flow_accept(lfd)"); return -1; } cout << "Flow accepted!" << endl; r.rfd = cfd; if (remote_tun_alloc(r)) { close(r.rfd); continue; } g->remotes.push_back(r); CDAPConn conn(r.rfd, 1); CDAPMessage *rm; CDAPMessage m; const char *objbuf; size_t objlen; Hello hello; rm = conn.msg_recv(); if (rm->op_code != gpb::M_CONNECT) { cerr << "M_CONNECT expected" << endl; goto abor; } r.app_name = rm->src_appl; r.dif_name = string(); m.m_connect_r(rm, 0, string()); if (conn.msg_send(&m, rm->invoke_id)) { cerr << "Failed to send M_CONNECT_R" << endl; goto abor; } delete rm; rm = NULL; rm = conn.msg_recv(); if (rm->op_code != gpb::M_START) { cerr << "M_START expected" << endl; goto abor; } rm->get_obj_value(objbuf, objlen); if (!objbuf) { cerr << "M_START does not contain a nested message" << endl; goto abor; } hello = Hello(objbuf, objlen); delete rm; rm = NULL; cout << "Hello received " << hello.num_routes << " " << hello.tun_subnet << endl; for (unsigned int i = 0; i < hello.num_routes; i ++) { RouteObj robj; rm = conn.msg_recv(); if (rm->op_code != gpb::M_WRITE) { cerr << "M_WRITE expected" << endl; goto abor; } rm->get_obj_value(objbuf, objlen); if (!objbuf) { cerr << "M_WRITE does not contain a nested message" << endl; goto abor; } robj = RouteObj(objbuf, objlen); delete rm; rm = NULL; cout << "Received route " << robj.route << endl; } abor: close(r.rfd); } pthread_exit(NULL); return 0; }
#if !defined(__CINT__) || defined(__MAKECINT__) #include <Riostream.h> #include <TFile.h> #include <TString.h> #include <TH2F.h> #include <TH1F.h> #include <TF1.h> #include <TGraph.h> #include <TDirectoryFile.h> #include <TList.h> #include <TCanvas.h> #include <TLegend.h> #include <TPaveText.h> #include <TPaveStats.h> #include <TStyle.h> #include <TClass.h> #include <TDatabasePDG.h> #include <TParameter.h> #include <AliCounterCollection.h> #include <AliRDHFCuts.h> #endif /* $Id$ */ TString *periodsname; //read the file and take list and stat Bool_t ReadFile(TList* &list,TH1F* &hstat, TString listname,TString partname,TString path="./",TString filename=/*"AnalysisResults.root"*/"PWG3histograms.root", TString dirname="PWG3_D2H_QA"); Bool_t ReadFileMore(TList* &list,TH1F* &hstat, AliRDHFCuts* &cutobj, TString listname,TString partname,TString path="./",TString filename=/*"AnalysisResults.root"*/"PWG3histograms.root", TString dirname="PWG3_D2H_QA"); void SuperimposeBBToTPCSignal(Int_t period /*0=LHC10bc, 1=LHC10d, 2=LHC10h*/,TCanvas* cpid, Int_t set); void TPCBetheBloch(Int_t set); Bool_t ReadFile(TList* &list,TH1F* &hstat, TString listname,TString partname,TString path,TString filename, TString dirname){ TString hstatname="nEntriesQA", cutobjname=""; filename.Prepend(path); listname+=partname; hstatname+=partname; TFile* f=new TFile(filename.Data()); if(!f->IsOpen()){ cout<<filename.Data()<<" not found"<<endl; return kFALSE; } TDirectoryFile* dir=(TDirectoryFile*)f->Get(dirname); if(!dir){ cout<<dirname.Data()<<" not found in "<<filename.Data()<<endl; f->ls(); return kFALSE; } list=(TList*)dir->Get(listname); if(!list){ cout<<"List "<<listname.Data()<<" not found"<<endl; dir->ls(); return kFALSE; } hstat=(TH1F*)dir->Get(hstatname); if(!hstat){ cout<<hstatname.Data()<<" not found"<<endl; return kFALSE; } return kTRUE; } Bool_t ReadFileMore(TList* &list,TH1F* &hstat, AliRDHFCuts* &cutobj, TString listname,TString partname,TString path,TString filename,TString dirname){ TString hstatname="nEntriesQA", cutobjname=""; filename.Prepend(path); listname+=partname; hstatname+=partname; if(partname.Contains("Dplus")) cutobjname="AnalysisCuts";//"DplustoKpipiCutsStandard"; else{ if(partname.Contains("D0")) cutobjname="D0toKpiCutsStandard";//"D0toKpiCuts" else{ if(partname.Contains("Dstar")) cutobjname="DStartoKpipiCuts"; else{ if(partname.Contains("Ds")) cutobjname="DstoKKpiCuts"; else{ if(partname.Contains("D04")) cutobjname="D0toKpipipiCuts"; else{ if(partname.Contains("Lc")) cutobjname="LctopKpiAnalysisCuts"; } } } } } TFile* f=new TFile(filename.Data()); if(!f->IsOpen()){ cout<<filename.Data()<<" not found"<<endl; return kFALSE; } TDirectoryFile* dir=(TDirectoryFile*)f->Get(dirname); if(!dir){ cout<<dirname.Data()<<" not found in "<<filename.Data()<<endl; return kFALSE; } list=(TList*)dir->Get(listname); if(!list){ cout<<"List "<<listname.Data()<<" not found"<<endl; dir->ls(); return kFALSE; } hstat=(TH1F*)dir->Get(hstatname); if(!hstat){ cout<<hstatname.Data()<<" not found"<<endl; return kFALSE; } cutobj=(AliRDHFCuts*)dir->Get(cutobjname); if(!cutobj){ cout<<cutobjname.Data()<<" not found"<<endl; return kFALSE; } return kTRUE; } //draw "track related" histograms (list "outputTrack") void DrawOutputTrack(TString partname="D0",TString textleg="",TString path="./", Bool_t superimpose=kFALSE, TString suffixdir="",TString filename=/*"AnalysisResults.root"*/"PWG3histograms.root", Bool_t normint=kTRUE /*normalize at integral, or at nevents*/){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPalette(1); TString listname="outputTrack",name1="",name2="",path2="",filename2="PWG3histograms.root",legtext1="",legtext2="",suffixdir2=""; TString tmp="y"; if(superimpose){ cout<<"Enter the names:\n>"; cin>>name1; cout<<">"; cin>>name2; cout<<"Are they in the same output file? (y/n)"<<endl; cin>>tmp; if(tmp=="n"){ cout<<"Path: \n"; cout<<">"; cin>>path2; cout<<"Filename: "<<endl; cout<<">"; cin>>filename2; cout<<"Suffix in the dir name, if any (otherwhise write no)\n>"; cin>>suffixdir2; if(suffixdir2=="no") suffixdir2=""; cout<<"Text in the legend:\n 1)"; cin>>legtext1; cout<<"2)"; cin>>legtext2; } } Float_t nevents,nevents2; TList* list; TH1F * hstat; TString dirname="PWG3_D2H_QA"; //dirname+=suffixdir; Bool_t isRead=ReadFile(list,hstat,listname,Form("%s%s",partname.Data(),name1.Data()),path,filename,Form("%s%s",dirname.Data(),suffixdir.Data())); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } nevents=hstat->GetBinContent(1); TPaveText *pvtxt=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt->SetBorderSize(0); pvtxt->SetFillStyle(0); pvtxt->AddText(legtext1); TList* llist; TH1F* hhstat; if(superimpose){ isRead=ReadFile(llist,hhstat,listname,Form("%s%s",partname.Data(),name2.Data()),path2,filename2,Form("%s%s",dirname.Data(),suffixdir2.Data())); if(!isRead) return; if(!llist || !hhstat){ cout<<":-( null pointers..."<<endl; return; } nevents2=hhstat->GetBinContent(1); TText *redtext=pvtxt->AddText(legtext2); redtext->SetTextColor(kRed); hhstat->Scale(hstat->Integral()/hhstat->Integral()); } for(Int_t i=0;i<list->GetEntries();i++){ TH1F* h=(TH1F*)list->At(i); TH1F* hh=0x0; TH1F* hr=0x0; if(superimpose){ hh=(TH1F*)llist->At(i); hr=(TH1F*)hh->Clone(Form("%s_ratio",hh->GetName())); if(hh && TMath::Abs(hh->Integral()) > 1e-6)hh->Scale(h->Integral()/hh->Integral()); } if(!h || (superimpose && !hh)){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } if(superimpose){ if(normint) hh->Scale(h->Integral()/hh->Integral()); else hh->Scale(nevents/nevents2); hhstat->SetLineColor(kRed); hh->SetLineColor(kRed); hr->Divide(h); } TCanvas* c=new TCanvas(Form("c%s",h->GetName()),h->GetName()); c->cd(); c->SetGrid(); TString hname=h->GetName(); if(!hname.Contains("nCls")){ c->SetLogy(); if(hname.Contains("Layer")){ for(Int_t ibin=1;ibin<=h->GetNbinsX();ibin++){ h->GetXaxis()->SetBinLabel(ibin+1,Form("%d",ibin)); } h->GetXaxis()->SetLabelSize(0.06); h->GetXaxis()->SetRangeUser(0,6); //comment to see ntracks! } //h->SetMinimum(1); h->Draw(); if(superimpose) { hh->Draw("sames"); TCanvas* c2=new TCanvas(Form("c2%s",h->GetName()),h->GetName()); c2->cd(); c2->SetGrid(); hr->Draw(); c2->SaveAs(Form("%s%s%s%sRatio.png",c->GetName(),name1.Data(),name2.Data(),textleg.Data())); } } else { h->Draw("htext0"); if(superimpose)hh->Draw("htext0sames"); } c->cd(); pvtxt->Draw(); c->SaveAs(Form("%s%s%s%s.png",c->GetName(),name1.Data(),name2.Data(),textleg.Data())); c->SaveAs(Form("%s%s%s%s.eps",c->GetName(),name1.Data(),name2.Data(),textleg.Data())); } TCanvas* cst=new TCanvas("cst","Stat"); cst->SetGridy(); cst->cd(); hstat->Draw("htext0"); if(superimpose) { hhstat->Draw("htext0sames"); pvtxt->Draw(); } cst->SaveAs(Form("%s%s.png",hstat->GetName(),textleg.Data())); cst->SaveAs(Form("%s%s.eps",hstat->GetName(),textleg.Data())); TH1F* hd0fb4=(TH1F*)list->FindObject("hd0TracksFilterBit4"); TH1F* hd0SPD1=(TH1F*)list->FindObject("hd0TracksSPDin"); TH1F* hd0SPDany=(TH1F*)list->FindObject("hd0TracksSPDany"); TH1F* hd0TPCITScuts=(TH1F*)list->FindObject("hd0TracksTPCITSSPDany"); TH1F* hhd0fb4=0x0; TH1F* hhd0SPD1=0x0; TH1F* hhd0SPDany=0x0; TH1F* hhd0TPCITScuts=0x0; if(superimpose){ hhd0fb4=(TH1F*)llist->FindObject("hd0TracksFilterBit4"); hhd0SPD1=(TH1F*)llist->FindObject("hd0TracksSPDin"); hhd0SPDany=(TH1F*)llist->FindObject("hd0TracksSPDany"); hhd0TPCITScuts=(TH1F*)llist->FindObject("hd0TracksTPCITSSPDany"); } if(hd0fb4 && hd0SPD1 && hd0SPDany && hd0TPCITScuts){ TCanvas* ctrsel=new TCanvas("ctrsel","Track Sel"); ctrsel->SetLogy(); hd0SPD1->SetLineColor(kCyan+3); hd0SPD1->Draw(); ctrsel->Update(); TPaveStats *st1=(TPaveStats*)hd0SPD1->GetListOfFunctions()->FindObject("stats"); st1->SetTextColor(kCyan+3); st1->SetY1NDC(0.71); st1->SetY2NDC(0.9); hd0SPDany->SetLineColor(4); hd0SPDany->Draw("sames"); ctrsel->Update(); TPaveStats *st2=(TPaveStats*)hd0SPDany->GetListOfFunctions()->FindObject("stats"); st2->SetY1NDC(0.51); st2->SetY2NDC(0.7); st2->SetTextColor(4); hd0fb4->SetLineColor(2); hd0fb4->Draw("sames"); ctrsel->Update(); TPaveStats *st3=(TPaveStats*)hd0fb4->GetListOfFunctions()->FindObject("stats"); st3->SetY1NDC(0.31); st3->SetY2NDC(0.5); st3->SetTextColor(2); hd0TPCITScuts->SetLineColor(kGreen+1); hd0TPCITScuts->Draw("sames"); ctrsel->Update(); TPaveStats *st4=(TPaveStats*)hd0TPCITScuts->GetListOfFunctions()->FindObject("stats"); st4->SetY1NDC(0.71); st4->SetY2NDC(0.9); st4->SetX1NDC(0.55); st4->SetX2NDC(0.75); st4->SetTextColor(kGreen+1); ctrsel->Modified(); TLegend* leg=new TLegend(0.15,0.5,0.45,0.78); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->AddEntry(hd0SPD1,"kITSrefit+SPD inner","L"); leg->AddEntry(hd0SPDany,"kITSrefit+SPD any","L"); leg->AddEntry(hd0TPCITScuts,"TPC+ITS cuts+SPD any","L"); leg->AddEntry(hd0fb4,"Filter Bit 4","L"); leg->Draw(); if(superimpose && hhd0fb4 && hhd0SPD1 && hhd0SPDany && hhd0TPCITScuts){ hhd0SPD1->SetLineColor(kCyan+3); hhd0SPD1->SetStats(0); hhd0SPD1->SetLineStyle(3); hhd0SPDany->SetLineColor(4); hhd0SPDany->SetStats(0); hhd0SPDany->SetLineStyle(3); hhd0TPCITScuts->SetLineColor(kGreen+1); hhd0TPCITScuts->SetStats(0); hhd0TPCITScuts->SetLineStyle(3); hhd0fb4->SetLineColor(2); hhd0fb4->SetStats(0); hhd0fb4->SetLineStyle(3); ctrsel->cd(); hhd0SPD1->Draw("sames"); hhd0SPDany->Draw("sames"); hhd0TPCITScuts->Draw("sames"); hhd0fb4->Draw("sames"); } ctrsel->SaveAs("ImpactParameterTrackSel.eps"); ctrsel->SaveAs("ImpactParameterTrackSel.png"); } } //draw "pid related" histograms (list "outputPID") //period=-999 to draw the pull instead of the cut void DrawOutputPID(TString partname="D0", Int_t mode=0/*0=with pull, 1=with nsigma*/,TString textleg="",TString path="./",TString suffixdir="", TString filename="AnalysisResults.root"){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetOptStat(0); gStyle->SetPalette(1); Int_t period=2 ,set=0; if(mode==1){ cout<<"Choose period: \n-LHC10h -> 2;\n-LHC10de -> 1;\n-LHC10bc -> 0"<<endl; cin>>period; if(period>0){ cout<<"Choose set: "<<endl; if(period==2) cout<<"-pass1 -> 0;\n-pass2 -> 1"<<endl; cin>>set; } } TString listname="outputPid"; TString dirname="PWG3_D2H_QA"; dirname+=suffixdir; TList* list; TH1F * hstat; //needed only for mode 1 AliRDHFCuts* cutobj; AliAODPidHF* aodpid; Double_t nsigmaTOF=0; Double_t nsigmaTPC[3]={},plimTPC[2]={}; if(mode==1){ Bool_t isRead=ReadFileMore(list,hstat,cutobj,listname,partname,path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } aodpid=(AliAODPidHF*)cutobj->GetPidHF(); if(!aodpid){ cout<<"PidHF object not found! cannot get the nsigma values"<<endl; return; } nsigmaTOF=aodpid->GetSigma(3); nsigmaTPC[0]=aodpid->GetSigma(0); nsigmaTPC[1]=aodpid->GetSigma(1); nsigmaTPC[2]=aodpid->GetSigma(2); aodpid->GetPLimit(plimTPC); }else{ Bool_t isRead=ReadFile(list,hstat,listname,partname,path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } } TPaveText *txtsigmaTOF=new TPaveText(0.1,0.65,0.5,0.9,"NDC"); txtsigmaTOF->SetBorderSize(0); txtsigmaTOF->SetFillStyle(0); txtsigmaTOF->AddText(Form("nsigmacut from cutobj = %.1f",nsigmaTOF)); TLine lTOF; lTOF.SetLineColor(kMagenta+1); lTOF.SetLineStyle(2); lTOF.SetLineWidth(3); TPaveText *txtsigmaTPC=new TPaveText(0.3,0.6,0.6,0.9,"NDC"); txtsigmaTPC->SetBorderSize(0); txtsigmaTPC->SetFillStyle(0); txtsigmaTPC->AddText("nsigmacut from cutobj \n"); txtsigmaTPC->AddText(Form("p < %.1f : %.1f \n",plimTPC[0],nsigmaTPC[0])); txtsigmaTPC->AddText(Form("%.1f < p < %.1f : %.1f \n",plimTPC[0],plimTPC[1],nsigmaTPC[1])); txtsigmaTPC->AddText(Form("p > %.1f : %.1f \n",plimTPC[1],nsigmaTPC[2])); TLine lTPC; lTPC.SetLineColor(kMagenta+1); lTPC.SetLineStyle(2); lTPC.SetLineWidth(3); // TCanvas *ctest=new TCanvas("text","Test text"); // ctest->cd(); // txtsigmaTPC->Draw(); // txtsigmaTOF->Draw(); for(Int_t i=0;i<list->GetEntries();i++){ TClass* objtype=list->At(i)->IsA(); TString tpname=objtype->GetName(); if(tpname=="TH1F"){ TH1F* h=(TH1F*)list->At(i); if(!h){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } //h->Scale(1./h->Integral("width")); TCanvas* c=new TCanvas(Form("c%s",h->GetName()),h->GetName()); c->SetLogz(); c->cd(); h->Draw(); //write c->SaveAs(Form("%s%s.png",h->GetName(),textleg.Data())); c->SaveAs(Form("%s%s.eps",h->GetName(),textleg.Data())); TFile* fout=new TFile(Form("%s.root",h->GetName()),"recreate"); fout->cd(); c->Write(); } if(tpname=="TH2F"){ TH2F* h=(TH2F*)list->At(i); if(!h){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } TString hname=h->GetName(); h->Sumw2(); if(h->Integral("width")==0) {cout<<"Empty histogram, skip\n"; continue;} h->Scale(1./h->Integral("width")); Double_t maxzaxis=h->GetBinContent(h->GetMaximumBin()); Double_t minzaxis=h->GetBinContent(h->GetMinimumBin()); printf("Minimum = %f, maximum = %f\n",minzaxis,maxzaxis); TH2F* hallzrange=(TH2F*)h->Clone(Form("%swholez",hname.Data())); hallzrange->SetAxisRange(1e-07,maxzaxis,"Z"); //hallzrange->SetAxisRange(minzaxis,maxzaxis,"Z"); TCanvas* cwholez=new TCanvas(Form("c%swholez",hname.Data()),Form("%s down to lowest z",hname.Data())); cwholez->SetLogz(); hallzrange->Draw("colz"); cwholez->SaveAs(Form("%swholez.png",h->GetName())); cwholez->SaveAs(Form("%swholez.eps",h->GetName())); if(hname.Contains("hTOFtimeKaonHyptime")){ TCanvas* cz=new TCanvas(Form("c%szoom",hname.Data()),Form("%szoom",hname.Data())); cz->SetLogz(); TH2F* hz=(TH2F*)h->Clone(Form("%sz",hname.Data())); hz->Draw("colz"); hz->SetAxisRange(-1500,1500,"Y"); hz->SetAxisRange(0.,5.,"X"); //write cz->SaveAs(Form("%szoom.png",h->GetName())); cz->SaveAs(Form("%szoom.eps",h->GetName())); } TCanvas* c=new TCanvas(Form("c%s",hname.Data()),hname.Data()); c->SetLogz(); //c->SetLogx(); TCanvas* c2=new TCanvas(Form("c2%s",hname.Data()),hname.Data()); c2->SetLogz(); c->cd(); h->DrawClone("colz"); if (hname.Contains("Sig") || hname.Contains("sigma"))h->SetAxisRange(-5,5,"Y"); c2->cd(); //if (hname.Contains("TOFtime"))h->SetAxisRange(-1500,1500,"Y"); h->SetAxisRange(0.,5.,"X"); h->Draw("colz"); //TCanvas *test=new TCanvas("test","test"); if(mode==0){ //mean and pull, code from Jens Wiechula TF1 fg("fg","gaus",-2.,2.); // fit range +- 2 sigma TLine l; TObjArray arr; //h->Draw("colz"); fg.SetParameters(1,0,1); h->FitSlicesY(&fg,0,-1,0,"NQR",&arr); TH1 *hM=(TH1*)arr.At(1); hM->SetMarkerStyle(20); hM->SetMarkerSize(.5); hM->DrawClone("sames"); TH1 *hS=(TH1*)arr.At(2); hS->SetMarkerStyle(20); hS->SetMarkerSize(.5); hS->SetMarkerColor(kRed); hS->SetLineColor(kRed); hS->DrawClone("same"); l.SetLineColor(kBlack); l.DrawLine(.2,0,20,0); l.SetLineColor(kRed); l.DrawLine(.2,1,20,1); }else{ //mode 1 if(hname.Contains("TOFsigma")) { c->cd(); txtsigmaTOF->Draw(); lTOF.DrawLine(.2,nsigmaTOF,20,nsigmaTOF); lTOF.DrawLine(.2,-1*nsigmaTOF,4.,-1*nsigmaTOF); } if(hname.Contains("TPCsigma")){ c->cd(); txtsigmaTPC->Draw(); lTPC.DrawLine(0.,nsigmaTPC[0],plimTPC[0],nsigmaTPC[0]); lTPC.DrawLine(plimTPC[0],nsigmaTPC[1],plimTPC[1],nsigmaTPC[1]); lTPC.DrawLine(plimTPC[1],nsigmaTPC[2],4,nsigmaTPC[2]); lTPC.DrawLine(0.,-1*nsigmaTPC[0],plimTPC[0],-1*nsigmaTPC[0]); lTPC.DrawLine(plimTPC[0],-1*nsigmaTPC[1],plimTPC[1],-1*nsigmaTPC[1]); lTPC.DrawLine(plimTPC[1],-1*nsigmaTPC[2],4,-1*nsigmaTPC[2]); } if(hname.Contains("TPCsigvsp")){ SuperimposeBBToTPCSignal(period,c,set); } } //write c->SaveAs(Form("%s%d.png",h->GetName(),mode)); c->SaveAs(Form("%s%d.eps",h->GetName(),mode)); c2->SaveAs(Form("%s2%d.png",h->GetName(),mode)); c2->SaveAs(Form("%s2%d.eps",h->GetName(),mode)); TFile* fout=new TFile(Form("%s%d.root",h->GetName(),mode),"recreate"); fout->cd(); c->Write(); c2->Write(); } } } void SuperimposeBBToTPCSignal(Int_t period /*0=LHC10bc, 1=LHC10d, 2=LHC10h*/,TCanvas* cpid,Int_t set /*see below*/){ TFile* fBethe=new TFile("BetheBlochTPC.root"); if(!fBethe->IsOpen()){ TPCBetheBloch(set); fBethe=new TFile("BetheBlochTPC.root"); } const Int_t npart=4; TString partnames[npart]={"Kaon","Pion","Electron","Proton"}; for(Int_t ipart=0;ipart<npart;ipart++){ TString grname=Form("%sP%d",partnames[ipart].Data(),period); TGraph* gr=(TGraph*)fBethe->Get(grname); cpid->cd(); gr->SetLineColor(1); gr->SetLineWidth(2); gr->Draw("L"); } //cpid->SaveAs(Form("%sBB.png",hname.Data())); } //draw and save Bethe Bloch from TPC in different periods void TPCBetheBloch(Int_t set){ gStyle->SetOptTitle(0); gStyle->SetCanvasColor(0); AliTPCPIDResponse *tpcResp=new AliTPCPIDResponse(); const Int_t npart=4; //Double_t masses[npart]={TDatabasePDG::Instance()->GetParticle(321)->Mass()/*Kaon*/,TDatabasePDG::Instance()->GetParticle(211)->Mass()/*Pion*/,TDatabasePDG::Instance()->GetParticle(11)->Mass()/*Electron*/,TDatabasePDG::Instance()->GetParticle(2212)->Mass()/*Proton*/}; TString partnames[npart]={"Kaon","Pion","Electron","Proton"}; //printf("%s = %.4f,%s = %.4f,%s = %.4f\n",partnames[0].Data(),masses[0],partnames[1].Data(),masses[1],partnames[2].Data(),masses[2]); TCanvas *cBethe=new TCanvas("cBethe","Bethe Bloch K pi e p"); Int_t nperiods=4; //LHC10b+c, LHC10d, LHC10h, MC Double_t alephParameters[5]={}; Int_t nsets=1/*LHC10bc*/+2/*LHC10de*/+2/*LHC10h*/+3/*MC*/; periodsname=new TString[nsets]; cout<<"Creating the file of the Bethe Bloch"<<endl; TFile* fout=new TFile("BetheBlochTPC.root","recreate"); for(Int_t iperiod=0;iperiod<nperiods;iperiod++){ cout<<"Period "<<iperiod<<" : "; if(iperiod==0){ //LHC10bc alephParameters[0] = 0.0283086/0.97; alephParameters[1] = 2.63394e+01; alephParameters[2] = 5.04114e-11; alephParameters[3] = 2.12543e+00; alephParameters[4] = 4.88663e+00; periodsname[0]="dataLHC10bc"; } if(iperiod==1){ //LHC10de,low energy if(set==0){ alephParameters[0] = 1.63246/50.; alephParameters[1] = 2.20028e+01; alephParameters[2] = TMath::Exp(-2.48879e+01); alephParameters[3] = 2.39804e+00; alephParameters[4] = 5.12090e+00; periodsname[1]="dataLHC10deold"; } if(set==1){ alephParameters[0] = 1.34490e+00/50.; alephParameters[1] = 2.69455e+01; alephParameters[2] = TMath::Exp(-2.97552e+01); alephParameters[3] = 2.35339e+00; alephParameters[4] = 5.98079e+00; periodsname[2]="dataLHC10denew"; } } if(iperiod==2){//LHC10h if(set==0){//pass1 alephParameters[0]=1.25202/50.; alephParameters[1]=2.74992e+01; alephParameters[2]=TMath::Exp(-3.31517e+01); alephParameters[3]=2.46246; alephParameters[4]=6.78938; periodsname[3]="dataLHC10hpass1"; } if (set==1){//pass2 (AOD044) alephParameters[0]=1.25202/50.; alephParameters[1]=2.74992e+01; alephParameters[2]=TMath::Exp(-3.31517e+01); alephParameters[3]=2.46246; alephParameters[4]=6.78938; periodsname[4]="dataLHC10hpass2"; } } if(iperiod==3){ //MC if(set==0){ alephParameters[0] = 2.15898e+00/50.; alephParameters[1] = 1.75295e+01; alephParameters[2] = 3.40030e-09; alephParameters[3] = 1.96178e+00; alephParameters[4] = 3.91720e+00; periodsname[5]="MCold"; } if(set==1){ //new alephParameters[0] = 1.44405/50; alephParameters[1] = 2.35409e+01; alephParameters[2] = TMath::Exp(-2.90330e+01); alephParameters[3] = 2.10681; alephParameters[4] = 4.62254; periodsname[6]="MCnew"; } if(set==2){ //new BB from Francesco alephParameters[0] = 0.029021; alephParameters[1] = 25.4181; alephParameters[2] = 4.66596e-08; alephParameters[3] = 1.90008; alephParameters[4] = 4.63783; periodsname[7]="MCBBFrancesco"; } if(set==3){ //low energy 2011 alephParameters[0] = 0.0207667; alephParameters[1] = 29.9936; alephParameters[2] = 3.87866e-11; alephParameters[3] = 2.17291; alephParameters[4] = 7.1623; //periodsname[8]="MClowen2011"; } } //cout<<periodsname[iperiod]<<endl; tpcResp->SetBetheBlochParameters(alephParameters[0],alephParameters[1],alephParameters[2],alephParameters[3],alephParameters[4]); cout<<"here"<<endl; for(Int_t ipart=0;ipart<npart;ipart++){ const Int_t n=1000; Double_t p[n],bethe[n]; for(Int_t k=0;k<n;k++){ //loop on the momentum steps p[k]=0.0001+k*4./n; //limits 0.-4. GeV/c //cout<<p[k]<<"\t"; //bethe[k]=-tpcResp->Bethe(p[k]/masses[ipart]); AliPID::EParticleType ptype=AliPID::kKaon; if(ipart==1) ptype=AliPID::kPion; if(ipart==2) ptype=AliPID::kElectron; if(ipart==3) ptype=AliPID::kProton; bethe[k]=tpcResp->GetExpectedSignal(p[k],ptype); } //cout<<endl; TGraph *gr=new TGraph(n,p,bethe); gr->SetName(Form("%sP%d",partnames[ipart].Data(),iperiod)); gr->SetTitle(Form("%sP%d;p (GeV/c);",partnames[ipart].Data(),iperiod)); gr->SetLineColor(ipart+1); gr->SetMarkerColor(ipart+1); gr->GetYaxis()->SetRangeUser(35,100); cBethe->cd(); if(iperiod==0 && ipart==0)gr->DrawClone("AL"); else gr->DrawClone("L"); fout->cd(); gr->Write(); } } TParameter<int> sett; sett.SetVal(set); fout->cd(); sett.Write(); fout->Close(); } void DrawOutputCentrality(TString partname="D0",TString textleg="",TString path="./", Bool_t superimpose=kFALSE,TString suffixdir="",TString filename=/*"AnalysisResults.root"*/"PWG3histograms.root"){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPalette(1); TString listname="outputCentrCheck",partname2="",path2="",suffixdir2="",filename2="PWG3histograms.root"; // if(superimpose){ // cout<<"Enter the names:\n>"; // cin>>name1; // cout<<">"; // cin>>name2; // } // TString listname="outputTrack",name1="",name2=""; TString tmp="y"; if(superimpose){ cout<<"##Second file\n"; cout<<"Enter the name:\n"; cout<<">"; cin>>partname2; cout<<"Are they in the same output file? (y/n)"<<endl; cin>>tmp; if(tmp=="n"){ cout<<"Path: \n"; cout<<">"; cin>>path2; cout<<"Dir name:\n"; cout<<">"; cin>>suffixdir2; cout<<"Filename: "<<endl; cout<<">"; cin>>filename2; } } // Int_t nhist=1; // TString *name=0x0; // if(superimpose){ // cout<<"Number of histogram to superimpose: "; // cin>>nhist; // name=new TString[nhist]; // for (Int_t j=0;j<nhist;j++){ // cout<<">"; // cin>>name[j]; // } // } TList* list; TH1F * hstat; TString dirname="PWG3_D2H_QA",dirname2=dirname; dirname+=suffixdir; dirname2+=suffixdir2; Bool_t isRead=ReadFile(list,hstat,listname,partname.Data(),path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } TPaveText *pvtxt=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt->SetBorderSize(0); pvtxt->SetFillStyle(0); pvtxt->AddText(partname); TList* llist; TH1F* hhstat; if(superimpose){ isRead=ReadFile(llist,hhstat,listname,partname2.Data(),path2,filename2,dirname2); if(!isRead) return; if(!llist || !hhstat){ cout<<":-( null pointers..."<<endl; return; } TText *redtext=pvtxt->AddText(partname2); redtext->SetTextColor(kRed); } TCanvas* cst=new TCanvas("cst","Stat"); cst->SetGridy(); cst->cd(); Int_t nevents=hstat->GetBinContent(1); hstat->Draw("htext0"); cst->SaveAs(Form("%s%s.png",hstat->GetName(),textleg.Data())); cst->SaveAs(Form("%s%s.eps",hstat->GetName(),textleg.Data())); Int_t nevents080=1,nnevents080=1; //TCanvas *spare=new TCanvas("sparecv","Spare"); for(Int_t i=0;i<list->GetEntries();i++){ TClass* objtype=list->At(i)->IsA(); TString tpname=objtype->GetName(); if(tpname=="TH1F"){ TH1F* h=(TH1F*)list->At(i); TH1F* hh=0x0; if(superimpose){ hh=(TH1F*)llist->At(i); } if(!h || (superimpose && !hh)){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } if(superimpose){ hhstat->SetLineColor(kRed); hh->SetLineColor(kRed); } TCanvas* c=new TCanvas(Form("c%s",h->GetName()),h->GetName()); TPaveText *pvtxt2=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt2->SetBorderSize(0); pvtxt2->SetFillStyle(0); c->cd(); c->SetGrid(); c->SetLogy(); Int_t entries=h->Integral(); pvtxt2->AddText(Form("%.1f %s of the events",(Double_t)entries/(Double_t)nevents*100,"%")); h->Draw(); if(superimpose) { hh->Draw("sames"); pvtxt->Draw(); } pvtxt2->Draw(); c->SaveAs(Form("%s%s.pdf",c->GetName(),textleg.Data())); c->SaveAs(Form("%s%s.eps",c->GetName(),textleg.Data())); } if(tpname=="TH2F"){ TH2F* hhh=(TH2F*)list->At(i); if(!hhh){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } TCanvas* c=new TCanvas(Form("c%s",hhh->GetName()),hhh->GetName()); TPaveText *pvtxt3=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt3->SetBorderSize(0); pvtxt3->SetFillStyle(0); c->cd(); c->SetGrid(); Int_t entries=hhh->Integral(); pvtxt3->AddText(Form("%.1f %s of the events",(Double_t)entries/(Double_t)nevents*100,"%")); hhh->Draw("colz"); c->SetLogz(); pvtxt3->Draw(); c->SaveAs(Form("%s%s.pdf",c->GetName(),textleg.Data())); c->SaveAs(Form("%s%s.eps",c->GetName(),textleg.Data())); } } listname="countersCentrality"; isRead=ReadFile(list,hstat,listname,partname.Data(),path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } if(superimpose){ isRead=ReadFile(llist,hhstat,listname,partname2.Data(),path2,filename2,dirname2); if(!isRead) return; if(!llist || !hhstat){ cout<<":-( null pointers..."<<endl; return; } TText *redtext=pvtxt->AddText(partname2); redtext->SetTextColor(kRed); } TH1F* hallcntr=0x0; TH1F* hhallcntr=0x0; cout<<"normalizing to 0-80% as a check"<<endl; Int_t ncentr=10;//check this TH1F* h020=0x0; TH1F* h2080=0x0; TH1F* hh020=0x0; TH1F* hh2080=0x0; TCanvas *cvnocnt=new TCanvas("cvnocnt","No Centrality estimation",800,400); cvnocnt->Divide(2,1); TCanvas *ccent=0x0; for(Int_t i=0;i<list->GetEntries();i++){ AliCounterCollection* coll=(AliCounterCollection*)list->At(i); AliCounterCollection* colle=0x0; if(superimpose) colle=(AliCounterCollection*)llist->At(i); coll->SortRubric("run");//sort by run number h020=0x0; h2080=0x0; hh020=0x0; hh2080=0x0; hallcntr=0x0; hhallcntr=0x0; TH1F* hbad=(TH1F*)coll->Get("run",Form("centralityclass:-990_-980")); cvnocnt->cd(i+1); if(hbad) hbad->Draw(); ccent=new TCanvas(Form("ccent%s",coll->GetName()),Form("Centrality vs Run (%s)",coll->GetName()),1400,800); ccent->SetTicky(); ccent->Divide(4,2); TH1F* hh=0x0; for(Int_t ic=0;ic<8/*ncentr*/;ic++){ //normalizing to 0-80% as a check TH1F* h=(TH1F*)coll->Get("run",Form("centralityclass:%d_%d",ic*10,ic*10+10)); h->SetName(Form("h%d%d",i,ic)); if(!hallcntr) { hallcntr=(TH1F*)h->Clone("hallcntr"); hallcntr->Sumw2(); } else { hallcntr->Add(h); } nevents080+=h->Integral(); if(superimpose){ hh=(TH1F*)colle->Get("run",Form("centralityclass:%d_%d",ic*10,ic*10+10)); hh->SetName(Form("hh%d%d",i,ic)); if(!hhallcntr) { hhallcntr=(TH1F*)hh->Clone("hhallcntr"); hhallcntr->Sumw2(); }else hhallcntr->Add(hh); nnevents080+=hh->Integral(); } } for(Int_t ic=0;ic<ncentr;ic++){ TH1F* h=(TH1F*)coll->Get("run",Form("centralityclass:%d_%d",ic*10,ic*10+10)); h->SetName(Form("h%d%d",i,ic)); h->Sumw2(); if(ic>=0 && ic<=1){ //0-20 if(!h020) { h020=(TH1F*)h->Clone(Form("h020%s",coll->GetName())); h020->SetTitle(Form("Centrality 0-20 %s",coll->GetName())); if(superimpose){ hh020=(TH1F*)hh->Clone(Form("hh020%s",coll->GetName())); hh020->SetTitle(Form("Centrality 0-20 %s",coll->GetName())); } } else { h020->Add(h); if(superimpose)hh020->Add(hh); } } if(ic>=2 && ic<=7){ //20-80 if(!h2080) { h2080=(TH1F*)h->Clone(Form("h2080%s",coll->GetName())); h2080->SetTitle(Form("Centrality 20-80 %s",coll->GetName())); if(superimpose){ hh2080=(TH1F*)hh->Clone(Form("hh2080%s",coll->GetName())); hh2080->SetTitle(Form("Centrality 20-80 %s",coll->GetName())); } } else { h2080->Add(h); if(superimpose)hh2080->Add(hh); } } h->Divide(hallcntr); if(ic<8){ ccent->cd(ic+1); h->GetYaxis()->SetLabelSize(0.05); h->GetYaxis()->SetTitleOffset(1.5); h->SetMinimum(0); //h->GetYaxis()->SetRangeUser(0.,0.15); h->DrawClone(); } /* if(ic==0&&i==0){ spare->cd(); h->Draw(); } */ // ccent->cd(1); // h->SetLineColor(ic+1); // if(ic==0)h->DrawClone(); // else h->DrawClone("sames"); } h020->Divide(hallcntr); if(superimpose){ hh020->Divide(hhallcntr); hh020->SetLineColor(2); hh020->SetMarkerColor(2); } /*//draw 0-20 and 20-80 in the multi pad canvas (increase divisions before uncommenting) ccent->cd(ncentr+1); h020->DrawClone(); if(superimpose){ hh020->DrawClone("sames"); } */ TCanvas* cv020=new TCanvas(Form("cv020-%d",i),"0-20% vs run number",1400,600); cv020->cd(); cv020->SetTicky(); h020->GetYaxis()->SetRangeUser(0.,1.); h020->DrawClone(); if(superimpose)hh020->DrawClone("sames"); cv020->SaveAs(Form("cv020-%d.pdf",i)); cv020->SaveAs(Form("cv020-%d.eps",i)); h2080->Divide(hallcntr); if(superimpose) { hh2080->Divide(hhallcntr); hh2080->SetLineColor(2); hh2080->SetMarkerColor(2); } /* ccent->cd(ncentr+2); h2080->DrawClone(); if(superimpose){ hh2080->DrawClone("sames"); } */ TCanvas* cv2080=new TCanvas(Form("cv2080-%d",i),"20-80% vs run number",1400,600); cv2080->cd(); cv2080->SetTicky(); h2080->GetYaxis()->SetRangeUser(0.,1.); h2080->DrawClone(); if(superimpose)hh2080->DrawClone("sames"); cv2080->SaveAs(Form("cv2080-%d.pdf",i)); cv2080->SaveAs(Form("cv2080-%d.eps",i)); ccent->SaveAs(Form("%s%s.pdf",ccent->GetName(),textleg.Data())); ccent->SaveAs(Form("%s%s.eps",ccent->GetName(),textleg.Data())); } } void DrawProjections(TString partname="D0",TString h2dname="hMultvsPercentile",Int_t groupnbins=5,Float_t fitmin=15,Float_t fitmax=50,TString direction="X",TString path="./",TString suffixdir="", TString filename="AnalysisResults.root", TString fitfunc="pol0"/*option "nofit" does not fit*/){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPalette(1); TString listname="outputCentrCheck"; TString dirname="PWG3_D2H_QA"; dirname+=suffixdir; TList* list; TH1F * hstat; Bool_t isRead=ReadFile(list,hstat,listname,partname,path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } Double_t nevents=hstat->GetBinContent(5); //ev good vertex TH2F* h2=(TH2F*)list->FindObject(h2dname); if(!h2){ cout<<h2dname.Data()<<" not found"<<endl; list->ls(); return; } TCanvas* cv2d=new TCanvas("cv2d",h2->GetName()); cv2d->cd(); cv2d->SetLogz(); cv2d->SetGrid(); h2->Draw("colz"); TPaveText *pvst=new TPaveText(0.6,0.2,0.9,0.7,"NDC"); pvst->SetBorderSize(0); pvst->SetFillStyle(0); pvst->AddText("Bin -> Cont/nEvVtx"); //nsteps=group bins in the Y(X) direction if projecting on the X(Y) direction Int_t nsteps=0; if(direction=="X") nsteps=h2->GetNbinsY()/groupnbins; if(direction=="Y") nsteps=h2->GetNbinsX()/groupnbins; cout<<"Grouping bins by " <<groupnbins<<" I obtaine "<<nsteps<<" projections"<<endl; TCanvas *cvpj=new TCanvas(Form("cvpj%s%s",direction.Data(),h2dname.Data()),Form("cvpj%s",direction.Data()),1200,800); cvpj->Divide((Int_t)(nsteps/3)+1,3); TFile* fout=new TFile(Form("proj%s%s.root",direction.Data(),h2dname.Data()), "recreate"); //Float_t maxx[nsteps]; //Float_t maxx[12]={9000,9000,6000,4000,2000,1400,800,500,200,100,40,25}; Double_t integralpernev[nsteps]; Double_t minx=0,maxx=0; if(direction=="X"){ minx=h2->GetYaxis()->GetXmin(); maxx=h2->GetYaxis()->GetXmax(); } if(direction=="Y"){ minx=h2->GetXaxis()->GetXmin(); maxx=h2->GetXaxis()->GetXmax(); } printf("Plotting from %.1f to %.1f\n",minx,maxx); TCanvas *cintegral=new TCanvas("cintegral","Integral of each projection"); TH1F* hint=new TH1F("hint","Integral of each projection;Centrality (%);Entries",nsteps,minx,maxx); Double_t minint=999999999,maxint=0; for(Int_t i=0;i<nsteps;i++){ TH1F* h=0x0; // if(direction=="X")h=(TH1F*)h2->ProjectionX(Form("px%d",i),i+kbins,i+2*kbins); // if(direction=="Y")h=(TH1F*)h2->ProjectionY(Form("py%d",i),i+kbins,i+2*kbins); if(direction=="X")h=(TH1F*)h2->ProjectionX(Form("px%d",i),groupnbins*i+1,groupnbins*(i+1)); if(direction=="Y")h=(TH1F*)h2->ProjectionY(Form("py%d",i),groupnbins*i+1,groupnbins*(i+1)); Double_t projint=h->Integral(); cout<<"Integral of projection "<<i<<" = "<<projint<<endl; hint->SetBinContent(i+1,projint); hint->SetBinError(i+1,TMath::Sqrt(projint)); if(projint<1e-7) continue; if(minint>projint) minint=projint; if(projint>maxint) maxint=projint; integralpernev[i]=h->Integral()/nevents; TPaveText *pvtxt=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt->SetBorderSize(0); pvtxt->SetFillStyle(0); pvtxt->AddText(Form("%.0f - %.0f",h2->GetYaxis()->GetBinLowEdge(groupnbins*i+1),h2->GetYaxis()->GetBinLowEdge(groupnbins*(i+1)))); pvst->AddText(Form("%.0f - %.0f -> %.2f",h2->GetYaxis()->GetBinLowEdge(groupnbins*i+1),h2->GetYaxis()->GetBinLowEdge((groupnbins*(i+1))),integralpernev[i])); cvpj->cd(i+1); //h->GetXaxis()->SetRangeUser(0,maxx[i]); h->Draw(); pvtxt->Draw(); fout->cd(); h->Write(); } cvpj->SaveAs(Form("cvpj%s%s.pdf",direction.Data(),h2dname.Data())); cvpj->SaveAs(Form("cvpj%s%s.eps",direction.Data(),h2dname.Data())); cv2d->cd(); pvst->Draw(); cv2d->SaveAs(Form("%s.pdf",h2->GetName())); cv2d->SaveAs(Form("%s.eps",h2->GetName())); cintegral->cd(); hint->SetMarkerStyle(20); hint->Draw("PE"); if(!fitfunc.Contains("nofit")){ hint->Fit(fitfunc.Data(),"RL","PE",fitmin,fitmax); TF1* fpolfit=hint->GetFunction(fitfunc.Data()); TPaveText *txtvar=new TPaveText(0.3,0.1,0.9,0.4,"NDC"); txtvar->SetBorderSize(0); txtvar->SetFillStyle(0); //txtvar->AddText(Form("Full spread %.0f- %.0f",maxint,minint)); txtvar->AddText(Form("Fit in %.1f-%.1f; ",fitmin,fitmax)); for(Int_t ipar=0;ipar<fpolfit->GetNpar();ipar++){ txtvar->AddText(Form("par%d = %.0f, ",ipar, fpolfit->GetParameter(ipar))); } txtvar->AddText(Form("#tilde{#chi}^{2} = %.2f",fpolfit->GetChisquare()/fpolfit->GetNDF())); txtvar->AddText(Form("bin width = %.1f %s",hint->GetBinWidth(3),"%")); txtvar->Draw(); } fout->cd(); hint->Write(); cintegral->SaveAs(Form("%s.pdf",hint->GetName())); cintegral->SaveAs(Form("%s.eps",hint->GetName())); } void DrawEventSelection(TString partname="D0", TString path="./",TString suffixdir="",TString filename="AnalysisResults.root"){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPalette(1); gStyle->SetOptStat(0); TString listname="outputEvSel"; TString dirname="PWG3_D2H_QA"; dirname+=suffixdir; TList* list; TH1F * hstat; Bool_t isRead=ReadFile(list,hstat,listname,partname,path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } //Double_t neventsgv=hstat->Integral(5,5); //ev good vertex for(Int_t i=0;i<list->GetEntries();i++){ TClass* objtype=list->At(i)->IsA(); TString tpname=objtype->GetName(); if(tpname=="TH1F"){ TH1F* htmp=(TH1F*)list->At(i); TCanvas* c=new TCanvas(Form("c%s",htmp->GetName()),Form("c%s",htmp->GetName())); c->cd(); htmp->Draw(); c->SaveAs(Form("%s.pdf",htmp->GetName())); c->SaveAs(Form("%s.eps",htmp->GetName())); } if(tpname=="TH2F"){ TH2F* htmp=(TH2F*)list->At(i); TCanvas* c=new TCanvas(Form("c%s",htmp->GetName()),Form("c%s",htmp->GetName()),1200,800); c->cd(); htmp->SetMarkerSize(1.3); htmp->Draw("colzhtext45"); c->SaveAs(Form("%s.pdf",htmp->GetName())); c->SaveAs(Form("%s.eps",htmp->GetName())); } } AliCounterCollection* coll=(AliCounterCollection*)list->FindObject("trigCounter"); if(!coll) { cout<<"Trigger counter not found"<<endl; return; } coll->SortRubric("run");//sort by run number TString collname=coll->GetName(); TString keywords=coll->GetKeyWords("triggertype"); Int_t nkeys=keywords.CountChar(',')+1; TString *words = new TString[nkeys]; for(Int_t k=0;k<nkeys;k++) words[k]=""; printf("Keywords: "); Int_t count=0; for(Int_t l=0;l<keywords.Length();l++){ if(keywords[l] != ',') words[count]+=keywords[l]; else { printf("%s ",words[count].Data()); count++; } } cout<<endl; TH1D** htrig=new TH1D*[nkeys]; //each trigger type in one histogram of counts vs run TH1D** htrignorm=new TH1D*[nkeys]; //normalized to the counts in kAny TCanvas* ctrigfraction=new TCanvas("cvtrigfrac","Fraction of given trigger type vs run",1400,800); TLegend* legtr=new TLegend(0.15,0.5,0.35,0.8); legtr->SetBorderSize(0); legtr->SetFillStyle(0); for(Int_t k=0;k<nkeys;k++){ htrig[k]=coll->Get("run",Form("triggertype:%s",words[k].Data())); htrig[k]->SetName(Form("h%s",words[k].Data())); htrig[k]->SetTitle("Trigger type;RUN; counts"); htrig[k]->SetMarkerColor(k+1); htrig[k]->SetMarkerStyle(k+20); htrig[k]->Sumw2(); legtr->AddEntry(htrig[k],Form("%s",words[k].Data()),"P"); //drawings //1) counts of a given trigger over counts in kAny htrignorm[k]=(TH1D*)htrig[k]->Clone(Form("h%snormAny",words[k].Data())); htrignorm[k]->SetTitle("Trigger type over ANY trigger;RUN; counts/countsANY"); htrignorm[k]->Divide(htrig[k],htrig[0],1.,1.,"B"); htrignorm[k]->GetXaxis()->SetRangeUser(0,1.1); ctrigfraction->cd(); if(k>0)htrignorm[k]->Draw("PEsames"); else htrignorm[k]->Draw("PE"); } ctrigfraction->cd(); legtr->Draw(); ctrigfraction->SaveAs("TrgFractionOverANY.pdf"); ctrigfraction->SaveAs("TrgFractionOverANY.eps"); delete [] words; } Draw track and event selection histograms superimposed (C.Bianchin, A.M.Veen) #if !defined(__CINT__) || defined(__MAKECINT__) #include <Riostream.h> #include <fstream> #include <TFile.h> #include <TString.h> #include <TH2F.h> #include <TH1F.h> #include <TF1.h> #include <TGraph.h> #include <TDirectoryFile.h> #include <TList.h> #include <TCanvas.h> #include <TLegend.h> #include <TPaveText.h> #include <TPaveStats.h> #include <TStyle.h> #include <TClass.h> #include <TDatabasePDG.h> #include <TParameter.h> #include <AliCounterCollection.h> #include <AliRDHFCuts.h> #endif /* $Id$ */ TString *periodsname; //read the file and take list and stat Bool_t ReadFile(TList* &list,TH1F* &hstat, TString listname,TString partname,TString path="./",TString filename=/*"AnalysisResults.root"*/"PWG3histograms.root", TString dirname="PWG3_D2H_QA"); Bool_t ReadFileMore(TList* &list,TH1F* &hstat, AliRDHFCuts* &cutobj, TString listname,TString partname,TString path="./",TString filename=/*"AnalysisResults.root"*/"PWG3histograms.root", TString dirname="PWG3_D2H_QA"); void SuperimposeBBToTPCSignal(Int_t period /*0=LHC10bc, 1=LHC10d, 2=LHC10h*/,TCanvas* cpid, Int_t set); void TPCBetheBloch(Int_t set); Bool_t ReadFilesForCompilation(TString inputtextfile, TList**& lists, Int_t&numb, TString*& legend); void CompilationEvSelection(Int_t n,TList** lists, TString* legend); void CompilationTrackSelection(Int_t n,TList** lists, TString* legend); Bool_t ReadFile(TList* &list,TH1F* &hstat, TString listname,TString partname,TString path,TString filename, TString dirname){ TString hstatname="nEntriesQA", cutobjname=""; filename.Prepend(path); listname+=partname; hstatname+=partname; TFile* f=new TFile(filename.Data()); if(!f->IsOpen()){ cout<<filename.Data()<<" not found"<<endl; return kFALSE; } TDirectoryFile* dir=(TDirectoryFile*)f->Get(dirname); if(!dir){ cout<<dirname.Data()<<" not found in "<<filename.Data()<<endl; f->ls(); return kFALSE; } list=(TList*)dir->Get(listname); if(!list){ cout<<"List "<<listname.Data()<<" not found"<<endl; dir->ls(); return kFALSE; } hstat=(TH1F*)dir->Get(hstatname); if(!hstat){ cout<<hstatname.Data()<<" not found"<<endl; return kFALSE; } return kTRUE; } Bool_t ReadFileMore(TList* &list,TH1F* &hstat, AliRDHFCuts* &cutobj, TString listname,TString partname,TString path,TString filename,TString dirname){ TString hstatname="nEntriesQA", cutobjname=""; filename.Prepend(path); listname+=partname; hstatname+=partname; if(partname.Contains("Dplus")) cutobjname="AnalysisCuts";//"DplustoKpipiCutsStandard"; else{ if(partname.Contains("D0")) cutobjname="D0toKpiCutsStandard";//"D0toKpiCuts" else{ if(partname.Contains("Dstar")) cutobjname="DStartoKpipiCuts"; else{ if(partname.Contains("Ds")) cutobjname="DstoKKpiCuts"; else{ if(partname.Contains("D04")) cutobjname="D0toKpipipiCuts"; else{ if(partname.Contains("Lc")) cutobjname="LctopKpiAnalysisCuts"; } } } } } TFile* f=new TFile(filename.Data()); if(!f->IsOpen()){ cout<<filename.Data()<<" not found"<<endl; return kFALSE; } TDirectoryFile* dir=(TDirectoryFile*)f->Get(dirname); if(!dir){ cout<<dirname.Data()<<" not found in "<<filename.Data()<<endl; return kFALSE; } list=(TList*)dir->Get(listname); if(!list){ cout<<"List "<<listname.Data()<<" not found"<<endl; dir->ls(); return kFALSE; } hstat=(TH1F*)dir->Get(hstatname); if(!hstat){ cout<<hstatname.Data()<<" not found"<<endl; return kFALSE; } cutobj=(AliRDHFCuts*)dir->Get(cutobjname); if(!cutobj){ cout<<cutobjname.Data()<<" not found"<<endl; return kFALSE; } return kTRUE; } //draw "track related" histograms (list "outputTrack") void DrawOutputTrack(TString partname="D0",TString textleg="",TString path="./", Bool_t superimpose=kFALSE, TString suffixdir="",TString filename=/*"AnalysisResults.root"*/"PWG3histograms.root", Bool_t normint=kTRUE /*normalize at integral, or at nevents*/){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPalette(1); TString listname="outputTrack",name1="",name2="",path2="",filename2="PWG3histograms.root",legtext1="",legtext2="",suffixdir2=""; TString tmp="y"; if(superimpose){ cout<<"Enter the names:\n>"; cin>>name1; cout<<">"; cin>>name2; cout<<"Are they in the same output file? (y/n)"<<endl; cin>>tmp; if(tmp=="n"){ cout<<"Path: \n"; cout<<">"; cin>>path2; cout<<"Filename: "<<endl; cout<<">"; cin>>filename2; cout<<"Suffix in the dir name, if any (otherwhise write no)\n>"; cin>>suffixdir2; if(suffixdir2=="no") suffixdir2=""; cout<<"Text in the legend:\n 1)"; cin>>legtext1; cout<<"2)"; cin>>legtext2; } } Float_t nevents,nevents2; TList* list; TH1F * hstat; TString dirname="PWG3_D2H_QA"; //dirname+=suffixdir; Bool_t isRead=ReadFile(list,hstat,listname,Form("%s%s",partname.Data(),name1.Data()),path,filename,Form("%s%s",dirname.Data(),suffixdir.Data())); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } nevents=hstat->GetBinContent(1); TPaveText *pvtxt=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt->SetBorderSize(0); pvtxt->SetFillStyle(0); pvtxt->AddText(legtext1); TList* llist; TH1F* hhstat; if(superimpose){ isRead=ReadFile(llist,hhstat,listname,Form("%s%s",partname.Data(),name2.Data()),path2,filename2,Form("%s%s",dirname.Data(),suffixdir2.Data())); if(!isRead) return; if(!llist || !hhstat){ cout<<":-( null pointers..."<<endl; return; } nevents2=hhstat->GetBinContent(1); TText *redtext=pvtxt->AddText(legtext2); redtext->SetTextColor(kRed); hhstat->Scale(hstat->Integral()/hhstat->Integral()); } for(Int_t i=0;i<list->GetEntries();i++){ TH1F* h=(TH1F*)list->At(i); TH1F* hh=0x0; TH1F* hr=0x0; if(superimpose){ hh=(TH1F*)llist->At(i); hr=(TH1F*)hh->Clone(Form("%s_ratio",hh->GetName())); if(hh && TMath::Abs(hh->Integral()) > 1e-6)hh->Scale(h->Integral()/hh->Integral()); } if(!h || (superimpose && !hh)){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } if(superimpose){ if(normint) hh->Scale(h->Integral()/hh->Integral()); else hh->Scale(nevents/nevents2); hhstat->SetLineColor(kRed); hh->SetLineColor(kRed); hr->Divide(h); } TCanvas* c=new TCanvas(Form("c%s",h->GetName()),h->GetName()); c->cd(); c->SetGrid(); TString hname=h->GetName(); if(!hname.Contains("nCls")){ c->SetLogy(); if(hname.Contains("Layer")){ for(Int_t ibin=1;ibin<=h->GetNbinsX();ibin++){ h->GetXaxis()->SetBinLabel(ibin+1,Form("%d",ibin)); } h->GetXaxis()->SetLabelSize(0.06); h->GetXaxis()->SetRangeUser(0,6); //comment to see ntracks! } //h->SetMinimum(1); h->Draw(); if(superimpose) { hh->Draw("sames"); TCanvas* c2=new TCanvas(Form("c2%s",h->GetName()),h->GetName()); c2->cd(); c2->SetGrid(); hr->Draw(); c2->SaveAs(Form("%s%s%s%sRatio.png",c->GetName(),name1.Data(),name2.Data(),textleg.Data())); } } else { h->Draw("htext0"); if(superimpose)hh->Draw("htext0sames"); } c->cd(); pvtxt->Draw(); c->SaveAs(Form("%s%s%s%s.png",c->GetName(),name1.Data(),name2.Data(),textleg.Data())); c->SaveAs(Form("%s%s%s%s.eps",c->GetName(),name1.Data(),name2.Data(),textleg.Data())); } TCanvas* cst=new TCanvas("cst","Stat"); cst->SetGridy(); cst->cd(); hstat->Draw("htext0"); if(superimpose) { hhstat->Draw("htext0sames"); pvtxt->Draw(); } cst->SaveAs(Form("%s%s.png",hstat->GetName(),textleg.Data())); cst->SaveAs(Form("%s%s.eps",hstat->GetName(),textleg.Data())); TH1F* hd0fb4=(TH1F*)list->FindObject("hd0TracksFilterBit4"); TH1F* hd0SPD1=(TH1F*)list->FindObject("hd0TracksSPDin"); TH1F* hd0SPDany=(TH1F*)list->FindObject("hd0TracksSPDany"); TH1F* hd0TPCITScuts=(TH1F*)list->FindObject("hd0TracksTPCITSSPDany"); TH1F* hhd0fb4=0x0; TH1F* hhd0SPD1=0x0; TH1F* hhd0SPDany=0x0; TH1F* hhd0TPCITScuts=0x0; if(superimpose){ hhd0fb4=(TH1F*)llist->FindObject("hd0TracksFilterBit4"); hhd0SPD1=(TH1F*)llist->FindObject("hd0TracksSPDin"); hhd0SPDany=(TH1F*)llist->FindObject("hd0TracksSPDany"); hhd0TPCITScuts=(TH1F*)llist->FindObject("hd0TracksTPCITSSPDany"); } if(hd0fb4 && hd0SPD1 && hd0SPDany && hd0TPCITScuts){ TCanvas* ctrsel=new TCanvas("ctrsel","Track Sel"); ctrsel->SetLogy(); hd0SPD1->SetLineColor(kCyan+3); hd0SPD1->Draw(); ctrsel->Update(); TPaveStats *st1=(TPaveStats*)hd0SPD1->GetListOfFunctions()->FindObject("stats"); st1->SetTextColor(kCyan+3); st1->SetY1NDC(0.71); st1->SetY2NDC(0.9); hd0SPDany->SetLineColor(4); hd0SPDany->Draw("sames"); ctrsel->Update(); TPaveStats *st2=(TPaveStats*)hd0SPDany->GetListOfFunctions()->FindObject("stats"); st2->SetY1NDC(0.51); st2->SetY2NDC(0.7); st2->SetTextColor(4); hd0fb4->SetLineColor(2); hd0fb4->Draw("sames"); ctrsel->Update(); TPaveStats *st3=(TPaveStats*)hd0fb4->GetListOfFunctions()->FindObject("stats"); st3->SetY1NDC(0.31); st3->SetY2NDC(0.5); st3->SetTextColor(2); hd0TPCITScuts->SetLineColor(kGreen+1); hd0TPCITScuts->Draw("sames"); ctrsel->Update(); TPaveStats *st4=(TPaveStats*)hd0TPCITScuts->GetListOfFunctions()->FindObject("stats"); st4->SetY1NDC(0.71); st4->SetY2NDC(0.9); st4->SetX1NDC(0.55); st4->SetX2NDC(0.75); st4->SetTextColor(kGreen+1); ctrsel->Modified(); TLegend* leg=new TLegend(0.15,0.5,0.45,0.78); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->AddEntry(hd0SPD1,"kITSrefit+SPD inner","L"); leg->AddEntry(hd0SPDany,"kITSrefit+SPD any","L"); leg->AddEntry(hd0TPCITScuts,"TPC+ITS cuts+SPD any","L"); leg->AddEntry(hd0fb4,"Filter Bit 4","L"); leg->Draw(); if(superimpose && hhd0fb4 && hhd0SPD1 && hhd0SPDany && hhd0TPCITScuts){ hhd0SPD1->SetLineColor(kCyan+3); hhd0SPD1->SetStats(0); hhd0SPD1->SetLineStyle(3); hhd0SPDany->SetLineColor(4); hhd0SPDany->SetStats(0); hhd0SPDany->SetLineStyle(3); hhd0TPCITScuts->SetLineColor(kGreen+1); hhd0TPCITScuts->SetStats(0); hhd0TPCITScuts->SetLineStyle(3); hhd0fb4->SetLineColor(2); hhd0fb4->SetStats(0); hhd0fb4->SetLineStyle(3); ctrsel->cd(); hhd0SPD1->Draw("sames"); hhd0SPDany->Draw("sames"); hhd0TPCITScuts->Draw("sames"); hhd0fb4->Draw("sames"); } ctrsel->SaveAs("ImpactParameterTrackSel.eps"); ctrsel->SaveAs("ImpactParameterTrackSel.png"); } } //draw "pid related" histograms (list "outputPID") //period=-999 to draw the pull instead of the cut void DrawOutputPID(TString partname="D0", Int_t mode=0/*0=with pull, 1=with nsigma*/,TString textleg="",TString path="./",TString suffixdir="", TString filename="AnalysisResults.root"){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetOptStat(0); gStyle->SetPalette(1); Int_t period=2 ,set=0; if(mode==1){ cout<<"Choose period: \n-LHC10h -> 2;\n-LHC10de -> 1;\n-LHC10bc -> 0"<<endl; cin>>period; if(period>0){ cout<<"Choose set: "<<endl; if(period==2) cout<<"-pass1 -> 0;\n-pass2 -> 1"<<endl; cin>>set; } } TString listname="outputPid"; TString dirname="PWG3_D2H_QA"; dirname+=suffixdir; TList* list; TH1F * hstat; //needed only for mode 1 AliRDHFCuts* cutobj; AliAODPidHF* aodpid; Double_t nsigmaTOF=0; Double_t nsigmaTPC[3]={},plimTPC[2]={}; if(mode==1){ Bool_t isRead=ReadFileMore(list,hstat,cutobj,listname,partname+suffixdir,path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } aodpid=(AliAODPidHF*)cutobj->GetPidHF(); if(!aodpid){ cout<<"PidHF object not found! cannot get the nsigma values"<<endl; return; } nsigmaTOF=aodpid->GetSigma(3); nsigmaTPC[0]=aodpid->GetSigma(0); nsigmaTPC[1]=aodpid->GetSigma(1); nsigmaTPC[2]=aodpid->GetSigma(2); aodpid->GetPLimit(plimTPC); }else{ Bool_t isRead=ReadFile(list,hstat,listname,partname+suffixdir,path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } } TPaveText *txtsigmaTOF=new TPaveText(0.1,0.65,0.5,0.9,"NDC"); txtsigmaTOF->SetBorderSize(0); txtsigmaTOF->SetFillStyle(0); txtsigmaTOF->AddText(Form("nsigmacut from cutobj = %.1f",nsigmaTOF)); TLine lTOF; lTOF.SetLineColor(kMagenta+1); lTOF.SetLineStyle(2); lTOF.SetLineWidth(3); TPaveText *txtsigmaTPC=new TPaveText(0.3,0.6,0.6,0.9,"NDC"); txtsigmaTPC->SetBorderSize(0); txtsigmaTPC->SetFillStyle(0); txtsigmaTPC->AddText("nsigmacut from cutobj \n"); txtsigmaTPC->AddText(Form("p < %.1f : %.1f \n",plimTPC[0],nsigmaTPC[0])); txtsigmaTPC->AddText(Form("%.1f < p < %.1f : %.1f \n",plimTPC[0],plimTPC[1],nsigmaTPC[1])); txtsigmaTPC->AddText(Form("p > %.1f : %.1f \n",plimTPC[1],nsigmaTPC[2])); TLine lTPC; lTPC.SetLineColor(kMagenta+1); lTPC.SetLineStyle(2); lTPC.SetLineWidth(3); // TCanvas *ctest=new TCanvas("text","Test text"); // ctest->cd(); // txtsigmaTPC->Draw(); // txtsigmaTOF->Draw(); for(Int_t i=0;i<list->GetEntries();i++){ TClass* objtype=list->At(i)->IsA(); TString tpname=objtype->GetName(); if(tpname=="TH1F"){ TH1F* h=(TH1F*)list->At(i); if(!h){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } //h->Scale(1./h->Integral("width")); TCanvas* c=new TCanvas(Form("c%s",h->GetName()),h->GetName()); c->SetLogz(); c->cd(); h->Draw(); //write c->SaveAs(Form("%s%s.png",h->GetName(),textleg.Data())); c->SaveAs(Form("%s%s.eps",h->GetName(),textleg.Data())); TFile* fout=new TFile(Form("%s.root",h->GetName()),"recreate"); fout->cd(); c->Write(); } if(tpname=="TH2F"){ TH2F* h=(TH2F*)list->At(i); if(!h){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } TString hname=h->GetName(); h->Sumw2(); if(h->Integral("width")==0) {cout<<"Empty histogram, skip\n"; continue;} h->Scale(1./h->Integral("width")); Double_t maxzaxis=h->GetBinContent(h->GetMaximumBin()); Double_t minzaxis=h->GetBinContent(h->GetMinimumBin()); printf("Minimum = %f, maximum = %f\n",minzaxis,maxzaxis); TH2F* hallzrange=(TH2F*)h->Clone(Form("%swholez",hname.Data())); hallzrange->SetAxisRange(1e-07,maxzaxis,"Z"); //hallzrange->SetAxisRange(minzaxis,maxzaxis,"Z"); TCanvas* cwholez=new TCanvas(Form("c%swholez",hname.Data()),Form("%s down to lowest z",hname.Data())); cwholez->SetLogz(); hallzrange->Draw("colz"); cwholez->SaveAs(Form("%swholez.png",h->GetName())); cwholez->SaveAs(Form("%swholez.eps",h->GetName())); if(hname.Contains("hTOFtimeKaonHyptime")){ TCanvas* cz=new TCanvas(Form("c%szoom",hname.Data()),Form("%szoom",hname.Data())); cz->SetLogz(); TH2F* hz=(TH2F*)h->Clone(Form("%sz",hname.Data())); hz->Draw("colz"); hz->SetAxisRange(-1500,1500,"Y"); hz->SetAxisRange(0.,5.,"X"); //write cz->SaveAs(Form("%szoom.png",h->GetName())); cz->SaveAs(Form("%szoom.eps",h->GetName())); } TCanvas* c=new TCanvas(Form("c%s",hname.Data()),hname.Data()); c->SetLogz(); //c->SetLogx(); TCanvas* c2=new TCanvas(Form("c2%s",hname.Data()),hname.Data()); c2->SetLogz(); c->cd(); h->DrawClone("colz"); if (hname.Contains("Sig") || hname.Contains("sigma"))h->SetAxisRange(-5,5,"Y"); c2->cd(); //if (hname.Contains("TOFtime"))h->SetAxisRange(-1500,1500,"Y"); h->SetAxisRange(0.,5.,"X"); h->Draw("colz"); //TCanvas *test=new TCanvas("test","test"); if(mode==0){ //mean and pull, code from Jens Wiechula TF1 fg("fg","gaus",-2.,2.); // fit range +- 2 sigma TLine l; TObjArray arr; //h->Draw("colz"); fg.SetParameters(1,0,1); h->FitSlicesY(&fg,0,-1,0,"NQR",&arr); TH1 *hM=(TH1*)arr.At(1); hM->SetMarkerStyle(20); hM->SetMarkerSize(.5); hM->DrawClone("sames"); TH1 *hS=(TH1*)arr.At(2); hS->SetMarkerStyle(20); hS->SetMarkerSize(.5); hS->SetMarkerColor(kRed); hS->SetLineColor(kRed); hS->DrawClone("same"); l.SetLineColor(kBlack); l.DrawLine(.2,0,20,0); l.SetLineColor(kRed); l.DrawLine(.2,1,20,1); }else{ //mode 1 if(hname.Contains("TOFsigma")) { c->cd(); txtsigmaTOF->Draw(); lTOF.DrawLine(.2,nsigmaTOF,20,nsigmaTOF); lTOF.DrawLine(.2,-1*nsigmaTOF,4.,-1*nsigmaTOF); } if(hname.Contains("TPCsigma")){ c->cd(); txtsigmaTPC->Draw(); lTPC.DrawLine(0.,nsigmaTPC[0],plimTPC[0],nsigmaTPC[0]); lTPC.DrawLine(plimTPC[0],nsigmaTPC[1],plimTPC[1],nsigmaTPC[1]); lTPC.DrawLine(plimTPC[1],nsigmaTPC[2],4,nsigmaTPC[2]); lTPC.DrawLine(0.,-1*nsigmaTPC[0],plimTPC[0],-1*nsigmaTPC[0]); lTPC.DrawLine(plimTPC[0],-1*nsigmaTPC[1],plimTPC[1],-1*nsigmaTPC[1]); lTPC.DrawLine(plimTPC[1],-1*nsigmaTPC[2],4,-1*nsigmaTPC[2]); } if(hname.Contains("TPCsigvsp")){ SuperimposeBBToTPCSignal(period,c,set); } } //write c->SaveAs(Form("%s%d.png",h->GetName(),mode)); c->SaveAs(Form("%s%d.eps",h->GetName(),mode)); c2->SaveAs(Form("%s2%d.png",h->GetName(),mode)); c2->SaveAs(Form("%s2%d.eps",h->GetName(),mode)); TFile* fout=new TFile(Form("%s%d.root",h->GetName(),mode),"recreate"); fout->cd(); c->Write(); c2->Write(); } } } void SuperimposeBBToTPCSignal(Int_t period /*0=LHC10bc, 1=LHC10d, 2=LHC10h*/,TCanvas* cpid,Int_t set /*see below*/){ TFile* fBethe=new TFile("BetheBlochTPC.root"); if(!fBethe->IsOpen()){ TPCBetheBloch(set); fBethe=new TFile("BetheBlochTPC.root"); } const Int_t npart=4; TString partnames[npart]={"Kaon","Pion","Electron","Proton"}; for(Int_t ipart=0;ipart<npart;ipart++){ TString grname=Form("%sP%d",partnames[ipart].Data(),period); TGraph* gr=(TGraph*)fBethe->Get(grname); cpid->cd(); gr->SetLineColor(1); gr->SetLineWidth(2); gr->Draw("L"); } //cpid->SaveAs(Form("%sBB.png",hname.Data())); } //draw and save Bethe Bloch from TPC in different periods void TPCBetheBloch(Int_t set){ gStyle->SetOptTitle(0); gStyle->SetCanvasColor(0); AliTPCPIDResponse *tpcResp=new AliTPCPIDResponse(); const Int_t npart=4; //Double_t masses[npart]={TDatabasePDG::Instance()->GetParticle(321)->Mass()/*Kaon*/,TDatabasePDG::Instance()->GetParticle(211)->Mass()/*Pion*/,TDatabasePDG::Instance()->GetParticle(11)->Mass()/*Electron*/,TDatabasePDG::Instance()->GetParticle(2212)->Mass()/*Proton*/}; TString partnames[npart]={"Kaon","Pion","Electron","Proton"}; //printf("%s = %.4f,%s = %.4f,%s = %.4f\n",partnames[0].Data(),masses[0],partnames[1].Data(),masses[1],partnames[2].Data(),masses[2]); TCanvas *cBethe=new TCanvas("cBethe","Bethe Bloch K pi e p"); Int_t nperiods=4; //LHC10b+c, LHC10d, LHC10h, MC Double_t alephParameters[5]={}; Int_t nsets=1/*LHC10bc*/+2/*LHC10de*/+2/*LHC10h*/+3/*MC*/; periodsname=new TString[nsets]; cout<<"Creating the file of the Bethe Bloch"<<endl; TFile* fout=new TFile("BetheBlochTPC.root","recreate"); for(Int_t iperiod=0;iperiod<nperiods;iperiod++){ cout<<"Period "<<iperiod<<" : "; if(iperiod==0){ //LHC10bc alephParameters[0] = 0.0283086/0.97; alephParameters[1] = 2.63394e+01; alephParameters[2] = 5.04114e-11; alephParameters[3] = 2.12543e+00; alephParameters[4] = 4.88663e+00; periodsname[0]="dataLHC10bc"; } if(iperiod==1){ //LHC10de,low energy if(set==0){ alephParameters[0] = 1.63246/50.; alephParameters[1] = 2.20028e+01; alephParameters[2] = TMath::Exp(-2.48879e+01); alephParameters[3] = 2.39804e+00; alephParameters[4] = 5.12090e+00; periodsname[1]="dataLHC10deold"; } if(set==1){ alephParameters[0] = 1.34490e+00/50.; alephParameters[1] = 2.69455e+01; alephParameters[2] = TMath::Exp(-2.97552e+01); alephParameters[3] = 2.35339e+00; alephParameters[4] = 5.98079e+00; periodsname[2]="dataLHC10denew"; } } if(iperiod==2){//LHC10h if(set==0){//pass1 alephParameters[0]=1.25202/50.; alephParameters[1]=2.74992e+01; alephParameters[2]=TMath::Exp(-3.31517e+01); alephParameters[3]=2.46246; alephParameters[4]=6.78938; periodsname[3]="dataLHC10hpass1"; } if (set==1){//pass2 (AOD044) alephParameters[0]=1.25202/50.; alephParameters[1]=2.74992e+01; alephParameters[2]=TMath::Exp(-3.31517e+01); alephParameters[3]=2.46246; alephParameters[4]=6.78938; periodsname[4]="dataLHC10hpass2"; } } if(iperiod==3){ //MC if(set==0){ alephParameters[0] = 2.15898e+00/50.; alephParameters[1] = 1.75295e+01; alephParameters[2] = 3.40030e-09; alephParameters[3] = 1.96178e+00; alephParameters[4] = 3.91720e+00; periodsname[5]="MCold"; } if(set==1){ //new alephParameters[0] = 1.44405/50; alephParameters[1] = 2.35409e+01; alephParameters[2] = TMath::Exp(-2.90330e+01); alephParameters[3] = 2.10681; alephParameters[4] = 4.62254; periodsname[6]="MCnew"; } if(set==2){ //new BB from Francesco alephParameters[0] = 0.029021; alephParameters[1] = 25.4181; alephParameters[2] = 4.66596e-08; alephParameters[3] = 1.90008; alephParameters[4] = 4.63783; periodsname[7]="MCBBFrancesco"; } if(set==3){ //low energy 2011 alephParameters[0] = 0.0207667; alephParameters[1] = 29.9936; alephParameters[2] = 3.87866e-11; alephParameters[3] = 2.17291; alephParameters[4] = 7.1623; //periodsname[8]="MClowen2011"; } } //cout<<periodsname[iperiod]<<endl; tpcResp->SetBetheBlochParameters(alephParameters[0],alephParameters[1],alephParameters[2],alephParameters[3],alephParameters[4]); cout<<"here"<<endl; for(Int_t ipart=0;ipart<npart;ipart++){ const Int_t n=1000; Double_t p[n],bethe[n]; for(Int_t k=0;k<n;k++){ //loop on the momentum steps p[k]=0.0001+k*4./n; //limits 0.-4. GeV/c //cout<<p[k]<<"\t"; //bethe[k]=-tpcResp->Bethe(p[k]/masses[ipart]); AliPID::EParticleType ptype=AliPID::kKaon; if(ipart==1) ptype=AliPID::kPion; if(ipart==2) ptype=AliPID::kElectron; if(ipart==3) ptype=AliPID::kProton; bethe[k]=tpcResp->GetExpectedSignal(p[k],ptype); } //cout<<endl; TGraph *gr=new TGraph(n,p,bethe); gr->SetName(Form("%sP%d",partnames[ipart].Data(),iperiod)); gr->SetTitle(Form("%sP%d;p (GeV/c);",partnames[ipart].Data(),iperiod)); gr->SetLineColor(ipart+1); gr->SetMarkerColor(ipart+1); gr->GetYaxis()->SetRangeUser(35,100); cBethe->cd(); if(iperiod==0 && ipart==0)gr->DrawClone("AL"); else gr->DrawClone("L"); fout->cd(); gr->Write(); } } TParameter<int> sett; sett.SetVal(set); fout->cd(); sett.Write(); fout->Close(); } void DrawOutputCentrality(TString partname="D0",TString textleg="",TString path="./", Bool_t superimpose=kFALSE,TString suffixdir="",TString filename=/*"AnalysisResults.root"*/"PWG3histograms.root"){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPalette(1); TString listname="outputCentrCheck",partname2="",path2="",suffixdir2="",filename2="PWG3histograms.root"; // if(superimpose){ // cout<<"Enter the names:\n>"; // cin>>name1; // cout<<">"; // cin>>name2; // } // TString listname="outputTrack",name1="",name2=""; TString tmp="y"; if(superimpose){ cout<<"##Second file\n"; cout<<"Enter the name:\n"; cout<<">"; cin>>partname2; cout<<"Are they in the same output file? (y/n)"<<endl; cin>>tmp; if(tmp=="n"){ cout<<"Path: \n"; cout<<">"; cin>>path2; cout<<"Dir name:\n"; cout<<">"; cin>>suffixdir2; cout<<"Filename: "<<endl; cout<<">"; cin>>filename2; } } // Int_t nhist=1; // TString *name=0x0; // if(superimpose){ // cout<<"Number of histogram to superimpose: "; // cin>>nhist; // name=new TString[nhist]; // for (Int_t j=0;j<nhist;j++){ // cout<<">"; // cin>>name[j]; // } // } TList* list; TH1F * hstat; TString dirname="PWG3_D2H_QA",dirname2=dirname; dirname+=suffixdir; dirname2+=suffixdir2; Bool_t isRead=ReadFile(list,hstat,listname,partname.Data(),path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } TPaveText *pvtxt=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt->SetBorderSize(0); pvtxt->SetFillStyle(0); pvtxt->AddText(partname); TList* llist; TH1F* hhstat; if(superimpose){ isRead=ReadFile(llist,hhstat,listname,partname2.Data(),path2,filename2,dirname2); if(!isRead) return; if(!llist || !hhstat){ cout<<":-( null pointers..."<<endl; return; } TText *redtext=pvtxt->AddText(partname2); redtext->SetTextColor(kRed); } TCanvas* cst=new TCanvas("cst","Stat"); cst->SetGridy(); cst->cd(); Int_t nevents=hstat->GetBinContent(1); hstat->Draw("htext0"); cst->SaveAs(Form("%s%s.png",hstat->GetName(),textleg.Data())); cst->SaveAs(Form("%s%s.eps",hstat->GetName(),textleg.Data())); Int_t nevents080=1,nnevents080=1; //TCanvas *spare=new TCanvas("sparecv","Spare"); for(Int_t i=0;i<list->GetEntries();i++){ TClass* objtype=list->At(i)->IsA(); TString tpname=objtype->GetName(); if(tpname=="TH1F"){ TH1F* h=(TH1F*)list->At(i); TH1F* hh=0x0; if(superimpose){ hh=(TH1F*)llist->At(i); } if(!h || (superimpose && !hh)){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } if(superimpose){ hhstat->SetLineColor(kRed); hh->SetLineColor(kRed); } TCanvas* c=new TCanvas(Form("c%s",h->GetName()),h->GetName()); TPaveText *pvtxt2=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt2->SetBorderSize(0); pvtxt2->SetFillStyle(0); c->cd(); c->SetGrid(); c->SetLogy(); Int_t entries=h->Integral(); pvtxt2->AddText(Form("%.1f %s of the events",(Double_t)entries/(Double_t)nevents*100,"%")); h->Draw(); if(superimpose) { hh->Draw("sames"); pvtxt->Draw(); } pvtxt2->Draw(); c->SaveAs(Form("%s%s.pdf",c->GetName(),textleg.Data())); c->SaveAs(Form("%s%s.eps",c->GetName(),textleg.Data())); } if(tpname=="TH2F"){ TH2F* hhh=(TH2F*)list->At(i); if(!hhh){ cout<<"Histogram "<<i<<" not found"<<endl; continue; } TCanvas* c=new TCanvas(Form("c%s",hhh->GetName()),hhh->GetName()); TPaveText *pvtxt3=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt3->SetBorderSize(0); pvtxt3->SetFillStyle(0); c->cd(); c->SetGrid(); Int_t entries=hhh->Integral(); pvtxt3->AddText(Form("%.1f %s of the events",(Double_t)entries/(Double_t)nevents*100,"%")); hhh->Draw("colz"); c->SetLogz(); pvtxt3->Draw(); c->SaveAs(Form("%s%s.pdf",c->GetName(),textleg.Data())); c->SaveAs(Form("%s%s.eps",c->GetName(),textleg.Data())); } } listname="countersCentrality"; isRead=ReadFile(list,hstat,listname,partname.Data(),path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } if(superimpose){ isRead=ReadFile(llist,hhstat,listname,partname2.Data(),path2,filename2,dirname2); if(!isRead) return; if(!llist || !hhstat){ cout<<":-( null pointers..."<<endl; return; } TText *redtext=pvtxt->AddText(partname2); redtext->SetTextColor(kRed); } TH1F* hallcntr=0x0; TH1F* hhallcntr=0x0; cout<<"normalizing to 0-80% as a check"<<endl; Int_t ncentr=10;//check this TH1F* h020=0x0; TH1F* h2080=0x0; TH1F* hh020=0x0; TH1F* hh2080=0x0; TCanvas *cvnocnt=new TCanvas("cvnocnt","No Centrality estimation",800,400); cvnocnt->Divide(2,1); TCanvas *ccent=0x0; for(Int_t i=0;i<list->GetEntries();i++){ AliCounterCollection* coll=(AliCounterCollection*)list->At(i); AliCounterCollection* colle=0x0; if(superimpose) colle=(AliCounterCollection*)llist->At(i); coll->SortRubric("run");//sort by run number h020=0x0; h2080=0x0; hh020=0x0; hh2080=0x0; hallcntr=0x0; hhallcntr=0x0; TH1F* hbad=(TH1F*)coll->Get("run",Form("centralityclass:-990_-980")); cvnocnt->cd(i+1); if(hbad) hbad->Draw(); ccent=new TCanvas(Form("ccent%s",coll->GetName()),Form("Centrality vs Run (%s)",coll->GetName()),1400,800); ccent->SetTicky(); ccent->Divide(4,2); TH1F* hh=0x0; for(Int_t ic=0;ic<8/*ncentr*/;ic++){ //normalizing to 0-80% as a check TH1F* h=(TH1F*)coll->Get("run",Form("centralityclass:%d_%d",ic*10,ic*10+10)); h->SetName(Form("h%d%d",i,ic)); if(!hallcntr) { hallcntr=(TH1F*)h->Clone("hallcntr"); hallcntr->Sumw2(); } else { hallcntr->Add(h); } nevents080+=h->Integral(); if(superimpose){ hh=(TH1F*)colle->Get("run",Form("centralityclass:%d_%d",ic*10,ic*10+10)); hh->SetName(Form("hh%d%d",i,ic)); if(!hhallcntr) { hhallcntr=(TH1F*)hh->Clone("hhallcntr"); hhallcntr->Sumw2(); }else hhallcntr->Add(hh); nnevents080+=hh->Integral(); } } for(Int_t ic=0;ic<ncentr;ic++){ TH1F* h=(TH1F*)coll->Get("run",Form("centralityclass:%d_%d",ic*10,ic*10+10)); h->SetName(Form("h%d%d",i,ic)); h->Sumw2(); if(ic>=0 && ic<=1){ //0-20 if(!h020) { h020=(TH1F*)h->Clone(Form("h020%s",coll->GetName())); h020->SetTitle(Form("Centrality 0-20 %s",coll->GetName())); if(superimpose){ hh020=(TH1F*)hh->Clone(Form("hh020%s",coll->GetName())); hh020->SetTitle(Form("Centrality 0-20 %s",coll->GetName())); } } else { h020->Add(h); if(superimpose)hh020->Add(hh); } } if(ic>=2 && ic<=7){ //20-80 if(!h2080) { h2080=(TH1F*)h->Clone(Form("h2080%s",coll->GetName())); h2080->SetTitle(Form("Centrality 20-80 %s",coll->GetName())); if(superimpose){ hh2080=(TH1F*)hh->Clone(Form("hh2080%s",coll->GetName())); hh2080->SetTitle(Form("Centrality 20-80 %s",coll->GetName())); } } else { h2080->Add(h); if(superimpose)hh2080->Add(hh); } } h->Divide(hallcntr); if(ic<8){ ccent->cd(ic+1); h->GetYaxis()->SetLabelSize(0.05); h->GetYaxis()->SetTitleOffset(1.5); h->SetMinimum(0); //h->GetYaxis()->SetRangeUser(0.,0.15); h->DrawClone(); } /* if(ic==0&&i==0){ spare->cd(); h->Draw(); } */ // ccent->cd(1); // h->SetLineColor(ic+1); // if(ic==0)h->DrawClone(); // else h->DrawClone("sames"); } h020->Divide(hallcntr); if(superimpose){ hh020->Divide(hhallcntr); hh020->SetLineColor(2); hh020->SetMarkerColor(2); } /*//draw 0-20 and 20-80 in the multi pad canvas (increase divisions before uncommenting) ccent->cd(ncentr+1); h020->DrawClone(); if(superimpose){ hh020->DrawClone("sames"); } */ TCanvas* cv020=new TCanvas(Form("cv020-%d",i),"0-20% vs run number",1400,600); cv020->cd(); cv020->SetTicky(); h020->GetYaxis()->SetRangeUser(0.,1.); h020->DrawClone(); if(superimpose)hh020->DrawClone("sames"); cv020->SaveAs(Form("cv020-%d.pdf",i)); cv020->SaveAs(Form("cv020-%d.eps",i)); h2080->Divide(hallcntr); if(superimpose) { hh2080->Divide(hhallcntr); hh2080->SetLineColor(2); hh2080->SetMarkerColor(2); } /* ccent->cd(ncentr+2); h2080->DrawClone(); if(superimpose){ hh2080->DrawClone("sames"); } */ TCanvas* cv2080=new TCanvas(Form("cv2080-%d",i),"20-80% vs run number",1400,600); cv2080->cd(); cv2080->SetTicky(); h2080->GetYaxis()->SetRangeUser(0.,1.); h2080->DrawClone(); if(superimpose)hh2080->DrawClone("sames"); cv2080->SaveAs(Form("cv2080-%d.pdf",i)); cv2080->SaveAs(Form("cv2080-%d.eps",i)); ccent->SaveAs(Form("%s%s.pdf",ccent->GetName(),textleg.Data())); ccent->SaveAs(Form("%s%s.eps",ccent->GetName(),textleg.Data())); } } void DrawProjections(TString partname="D0",TString h2dname="hMultvsPercentile",Int_t groupnbins=5,Float_t fitmin=15,Float_t fitmax=50,TString direction="X",TString path="./",TString suffixdir="", TString filename="AnalysisResults.root", TString fitfunc="pol0"/*option "nofit" does not fit*/){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPalette(1); TString listname="outputCentrCheck"; TString dirname="PWG3_D2H_QA"; dirname+=suffixdir; TList* list; TH1F * hstat; Bool_t isRead=ReadFile(list,hstat,listname,partname,path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } Double_t nevents=hstat->GetBinContent(5); //ev good vertex TH2F* h2=(TH2F*)list->FindObject(h2dname); if(!h2){ cout<<h2dname.Data()<<" not found"<<endl; list->ls(); return; } TCanvas* cv2d=new TCanvas("cv2d",h2->GetName()); cv2d->cd(); cv2d->SetLogz(); cv2d->SetGrid(); h2->Draw("colz"); TPaveText *pvst=new TPaveText(0.6,0.2,0.9,0.7,"NDC"); pvst->SetBorderSize(0); pvst->SetFillStyle(0); pvst->AddText("Bin -> Cont/nEvVtx"); //nsteps=group bins in the Y(X) direction if projecting on the X(Y) direction Int_t nsteps=0; if(direction=="X") nsteps=h2->GetNbinsY()/groupnbins; if(direction=="Y") nsteps=h2->GetNbinsX()/groupnbins; cout<<"Grouping bins by " <<groupnbins<<" I obtaine "<<nsteps<<" projections"<<endl; TCanvas *cvpj=new TCanvas(Form("cvpj%s%s",direction.Data(),h2dname.Data()),Form("cvpj%s",direction.Data()),1200,800); cvpj->Divide((Int_t)(nsteps/3)+1,3); TFile* fout=new TFile(Form("proj%s%s.root",direction.Data(),h2dname.Data()), "recreate"); //Float_t maxx[nsteps]; //Float_t maxx[12]={9000,9000,6000,4000,2000,1400,800,500,200,100,40,25}; Double_t integralpernev[nsteps]; Double_t minx=0,maxx=0; if(direction=="X"){ minx=h2->GetYaxis()->GetXmin(); maxx=h2->GetYaxis()->GetXmax(); } if(direction=="Y"){ minx=h2->GetXaxis()->GetXmin(); maxx=h2->GetXaxis()->GetXmax(); } printf("Plotting from %.1f to %.1f\n",minx,maxx); TCanvas *cintegral=new TCanvas("cintegral","Integral of each projection"); TH1F* hint=new TH1F("hint","Integral of each projection;Centrality (%);Entries",nsteps,minx,maxx); Double_t minint=999999999,maxint=0; for(Int_t i=0;i<nsteps;i++){ TH1F* h=0x0; // if(direction=="X")h=(TH1F*)h2->ProjectionX(Form("px%d",i),i+kbins,i+2*kbins); // if(direction=="Y")h=(TH1F*)h2->ProjectionY(Form("py%d",i),i+kbins,i+2*kbins); if(direction=="X")h=(TH1F*)h2->ProjectionX(Form("px%d",i),groupnbins*i+1,groupnbins*(i+1)); if(direction=="Y")h=(TH1F*)h2->ProjectionY(Form("py%d",i),groupnbins*i+1,groupnbins*(i+1)); Double_t projint=h->Integral(); cout<<"Integral of projection "<<i<<" = "<<projint<<endl; hint->SetBinContent(i+1,projint); hint->SetBinError(i+1,TMath::Sqrt(projint)); if(projint<1e-7) continue; if(minint>projint) minint=projint; if(projint>maxint) maxint=projint; integralpernev[i]=h->Integral()/nevents; TPaveText *pvtxt=new TPaveText(0.6,0.6,0.9,0.9,"NDC"); pvtxt->SetBorderSize(0); pvtxt->SetFillStyle(0); pvtxt->AddText(Form("%.0f - %.0f",h2->GetYaxis()->GetBinLowEdge(groupnbins*i+1),h2->GetYaxis()->GetBinLowEdge(groupnbins*(i+1)))); pvst->AddText(Form("%.0f - %.0f -> %.2f",h2->GetYaxis()->GetBinLowEdge(groupnbins*i+1),h2->GetYaxis()->GetBinLowEdge((groupnbins*(i+1))),integralpernev[i])); cvpj->cd(i+1); //h->GetXaxis()->SetRangeUser(0,maxx[i]); h->Draw(); pvtxt->Draw(); fout->cd(); h->Write(); } cvpj->SaveAs(Form("cvpj%s%s.pdf",direction.Data(),h2dname.Data())); cvpj->SaveAs(Form("cvpj%s%s.eps",direction.Data(),h2dname.Data())); cv2d->cd(); pvst->Draw(); cv2d->SaveAs(Form("%s.pdf",h2->GetName())); cv2d->SaveAs(Form("%s.eps",h2->GetName())); cintegral->cd(); hint->SetMarkerStyle(20); hint->Draw("PE"); if(!fitfunc.Contains("nofit")){ hint->Fit(fitfunc.Data(),"RL","PE",fitmin,fitmax); TF1* fpolfit=hint->GetFunction(fitfunc.Data()); TPaveText *txtvar=new TPaveText(0.3,0.1,0.9,0.4,"NDC"); txtvar->SetBorderSize(0); txtvar->SetFillStyle(0); //txtvar->AddText(Form("Full spread %.0f- %.0f",maxint,minint)); txtvar->AddText(Form("Fit in %.1f-%.1f; ",fitmin,fitmax)); for(Int_t ipar=0;ipar<fpolfit->GetNpar();ipar++){ txtvar->AddText(Form("par%d = %.0f, ",ipar, fpolfit->GetParameter(ipar))); } txtvar->AddText(Form("#tilde{#chi}^{2} = %.2f",fpolfit->GetChisquare()/fpolfit->GetNDF())); txtvar->AddText(Form("bin width = %.1f %s",hint->GetBinWidth(3),"%")); txtvar->Draw(); } fout->cd(); hint->Write(); cintegral->SaveAs(Form("%s.pdf",hint->GetName())); cintegral->SaveAs(Form("%s.eps",hint->GetName())); } void DrawEventSelection(TString partname="D0", TString path="./",TString suffixdir="",TString filename="AnalysisResults.root"){ gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetPalette(1); gStyle->SetOptStat(0); TString listname="outputEvSel"; TString dirname="PWG3_D2H_QA"; dirname+=suffixdir; TList* list; TH1F * hstat; Bool_t isRead=ReadFile(list,hstat,listname,partname,path,filename,dirname); if(!isRead) return; if(!list || !hstat){ cout<<":-( null pointers..."<<endl; return; } //Double_t neventsgv=hstat->Integral(5,5); //ev good vertex for(Int_t i=0;i<list->GetEntries();i++){ TClass* objtype=list->At(i)->IsA(); TString tpname=objtype->GetName(); if(tpname=="TH1F"){ TH1F* htmp=(TH1F*)list->At(i); TCanvas* c=new TCanvas(Form("c%s",htmp->GetName()),Form("c%s",htmp->GetName())); c->cd(); htmp->Draw(); c->SaveAs(Form("%s.pdf",htmp->GetName())); c->SaveAs(Form("%s.eps",htmp->GetName())); } if(tpname=="TH2F"){ TH2F* htmp=(TH2F*)list->At(i); TCanvas* c=new TCanvas(Form("c%s",htmp->GetName()),Form("c%s",htmp->GetName()),1200,800); c->cd(); htmp->SetMarkerSize(1.3); htmp->Draw("colzhtext45"); c->SaveAs(Form("%s.pdf",htmp->GetName())); c->SaveAs(Form("%s.eps",htmp->GetName())); } } AliCounterCollection* coll=(AliCounterCollection*)list->FindObject("trigCounter"); if(!coll) { cout<<"Trigger counter not found"<<endl; return; } coll->SortRubric("run");//sort by run number TString collname=coll->GetName(); TString keywords=coll->GetKeyWords("triggertype"); Int_t nkeys=keywords.CountChar(',')+1; TString *words = new TString[nkeys]; for(Int_t k=0;k<nkeys;k++) words[k]=""; printf("Keywords: "); Int_t count=0; for(Int_t l=0;l<keywords.Length();l++){ if(keywords[l] != ',') words[count]+=keywords[l]; else { printf("%s ",words[count].Data()); count++; } } cout<<endl; TH1D** htrig=new TH1D*[nkeys]; //each trigger type in one histogram of counts vs run TH1D** htrignorm=new TH1D*[nkeys]; //normalized to the counts in kAny TCanvas* ctrigfraction=new TCanvas("cvtrigfrac","Fraction of given trigger type vs run",1400,800); TLegend* legtr=new TLegend(0.15,0.5,0.35,0.8); legtr->SetBorderSize(0); legtr->SetFillStyle(0); for(Int_t k=0;k<nkeys;k++){ htrig[k]=coll->Get("run",Form("triggertype:%s",words[k].Data())); htrig[k]->SetName(Form("h%s",words[k].Data())); htrig[k]->SetTitle("Trigger type;RUN; counts"); htrig[k]->SetMarkerColor(k+1); htrig[k]->SetMarkerStyle(k+20); htrig[k]->Sumw2(); legtr->AddEntry(htrig[k],Form("%s",words[k].Data()),"P"); //drawings //1) counts of a given trigger over counts in kAny htrignorm[k]=(TH1D*)htrig[k]->Clone(Form("h%snormAny",words[k].Data())); htrignorm[k]->SetTitle("Trigger type over ANY trigger;RUN; counts/countsANY"); htrignorm[k]->Divide(htrig[k],htrig[0],1.,1.,"B"); htrignorm[k]->GetXaxis()->SetRangeUser(0,1.1); ctrigfraction->cd(); if(k>0)htrignorm[k]->Draw("PEsames"); else htrignorm[k]->Draw("PE"); } ctrigfraction->cd(); legtr->Draw(); ctrigfraction->SaveAs("TrgFractionOverANY.pdf"); ctrigfraction->SaveAs("TrgFractionOverANY.eps"); delete [] words; //draw number of events per trigger TH2F* hTrigMul=(TH2F*)list->FindObject("hTrigMul"); TH1F *hnEvPerTrig=(TH1F*)hTrigMul->ProjectionX("hnEvPerTrig"); hnEvPerTrig->SetTitle("Number of events per trigger"); TCanvas* cnev=new TCanvas("cnev","Number of events",1400,800); cnev->cd(); hnEvPerTrig->Draw("htext0"); cnev->SaveAs(Form("%s.pdf",cnev->GetName())); cnev->SaveAs(Form("%s.eps",cnev->GetName())); //draw number of events selected per trigger TH2F* hTrigMulSel=(TH2F*)list->FindObject("hTrigMulSel"); TH1F *hnEvPerTrigSel=(TH1F*)hTrigMulSel->ProjectionX("hnEvPerTrigSel"); hnEvPerTrigSel->SetTitle("Number of events selected per trigger"); TCanvas* cnevs=new TCanvas("cnevs","Number of events selected",1400,800); cnevs->cd(); hnEvPerTrigSel->Draw("htext0"); cnevs->SaveAs(Form("%s%s.pdf",cnevs->GetName(),suffixdir.Data())); cnevs->SaveAs(Form("%s%s.eps",cnevs->GetName(),suffixdir.Data())); TH1F* hnEvSelPerc=(TH1F*)hnEvPerTrigSel->Clone("hnEvSelFrac"); hnEvSelPerc->SetTitle("Fraction of event selected per trigger"); hnEvSelPerc->Divide(hnEvPerTrig); TCanvas* cnevsp=new TCanvas("cnevsp","Fraction of events selected",1400,800); cnevsp->cd(); hnEvSelPerc->Draw("htext0"); cnevsp->SaveAs(Form("%s%s.pdf",cnevsp->GetName(),suffixdir.Data())); cnevsp->SaveAs(Form("%s%s.eps",cnevsp->GetName(),suffixdir.Data())); } void WriteTextFileForCompilation(TString inputtextfile, Int_t analysistype){ //This method writes a text file with the name given in input containing the path of the QA output file, the directories and the lists of histograms to be read to perform a comparison of QA outputs // analysistype = 1 is the OutputTrack // analysistype = 2 is the OutputEventSelection // other outputs can be implemented // The paths and trigger type (or more in general the suffix of the directories to be read have to be set in this method) // The legend is set either equal to the trigger type if they are different, or it should be set manually // Run this methos before CompilationOfTriggeredEvents unless the text file has been already produced Printf("WARNING! Did you customize the parameters in the macro?"); const Int_t n=8; //customize this TString prepath="/data/Work/HFQA/LHC12QATrainOutputs/";//"./"; TString pathname[n]={"LHC12a/Train165/","LHC12b/Train166/","LHC12d/Train168/","LHC12e/Train170/","LHC12f/Train171/","LHC12g/Train172/"}; TString dirname[n]; TString listname[n]; ofstream myfile; myfile.open(inputtextfile); myfile<<n<<endl; TString filename="AnalysisResults.root"; TString basedirname="PWG3_D2H_QA"; TString trgnames[n];//={"INT7","EMC7","EMCJET7","EMCGAMMA7","INT8","EMC8","EMCJET8","EMCGAMMA8"}; //customize this TString baselistname="", partname="D00100"; TString legend[n]={"LHC12a165","LHC12b166","LHC12d168","LHC12e170","LHC12f171","LHC12g172"}; //Customize this if want it to be different from trgnames if(analysistype==1) baselistname="outputTrack"; if(analysistype==2) baselistname="outputEvSel"; //... others could be added //All in the same directory on your computer for(Int_t i=0;i<n;i++){ //set pathname[i]=prepath+pathname[i];//"./"; trgnames[i]="EMC7"; dirname[i]=basedirname+trgnames[i]; listname[i]=baselistname+partname+trgnames[i]; if(legend[i]=="") legend[i]=trgnames[i]; //Printf("Trigger name is %s",trgnames[i].Data()); //Printf("Legend is %s",legend[i].Data()); //write text file myfile<<endl; myfile<<endl; myfile<<pathname[i].Data()<<filename.Data()<<endl; myfile<<dirname[i].Data()<<endl; myfile<<listname[i].Data()<<endl; myfile<<legend[i].Data()<<endl; } myfile.close(); } Bool_t ReadFilesForCompilation(TString inputtextfile, TList**& lists, Int_t& numb, TString*& legend){ //Method to read the QA files indicated in the text file in input (to be written with WriteTextFileForCompilation() method) ifstream myfile; myfile.open(inputtextfile); if(!myfile.is_open()) Printf("No files found, did you make it correctly?"); Int_t n; myfile >> n; lists=new TList*[n]; legend= new TString[n]; numb=n; Int_t k=0; while(myfile){ TString filename; myfile>>filename; //Printf("Filename = %s",filename.Data()); TFile *fin=new TFile(filename); if(!fin->IsOpen()){ Printf("File %s not found",filename.Data()); return kFALSE; } TString dirname; myfile>>dirname; //Printf("Dirname = %s",dirname.Data()); TDirectoryFile* dir=(TDirectoryFile*)fin->Get(dirname); if(!dir){ Printf("Directory %s not found in %s",dirname.Data(),filename.Data()); fin->ls(); return kFALSE; } TString listname; myfile>>listname; //Printf("Listname = %s",listname.Data()); lists[k]=(TList*)dir->Get(listname); if(!lists[k]){ Printf("List %s not found in %s",listname.Data(),dirname.Data()); dir->ls(); return kFALSE; } TString temp; myfile>>temp; legend[k]=temp; Printf("Legend = %s",legend[k].Data()); if(!legend[k]){ Printf("Legend %s not found",filename.Data()); return kFALSE; } k++; if(k==n)return kTRUE;// Needed as the while loop does not always realise the end is reached. } return kTRUE; } void CompilationOfTriggeredEvents(TString inputtextfile,Int_t analysistype){ //This method draws the histograms superimposed // analysistype = 1 is the OutputTrack // analysistype = 2 is the OutputEventSelection // other outputs can be implemented TList **lists=0x0; Int_t n; TString* legend=0x0; Bool_t okread=ReadFilesForCompilation(inputtextfile,lists,n,legend); if(!okread){ Printf("Did you write %s with WriteTextFileForCompilation(%s)?",inputtextfile.Data(),inputtextfile.Data()); return; } if(analysistype==2){CompilationEvSelection(n,lists,legend);} if(analysistype==1){CompilationTrackSelection(n,lists,legend);} } void CompilationEvSelection(Int_t n,TList** lists, TString* legend){ // Specific method for EventSelection output (2) TCanvas *cnevs=new TCanvas("cnevs","Number of events selected",1400,800); TCanvas *cnevsp=new TCanvas("cnevsp","Fraction of events selected",1400,800); TH1F** hnEvPerTrig=new TH1F*[n]; TH1F** hnEvPerTrigSel=new TH1F*[n]; TH1F** hnEvSelPerc=new TH1F*[n]; TLegend* leg=new TLegend(0.15,0.5,0.45,0.78); leg->SetFillStyle(0); leg->SetBorderSize(0); Bool_t first=kTRUE; Int_t nentriesl=lists[0]->GetEntries(); TCanvas** c=new TCanvas*[nentriesl]; Int_t nth1f=0; for(Int_t i=0;i<n;i++){ TH2F* hTrigMul=(TH2F*)lists[i]->FindObject("hTrigMul"); hnEvPerTrig[i]=(TH1F*)hTrigMul->ProjectionX(Form("hnEvPerTrig%d",i)); hnEvPerTrig[i]->SetTitle("Number of events selected per trigger"); TH2F* hTrigMulSel=(TH2F*)lists[i]->FindObject("hTrigMulSel"); hnEvPerTrigSel[i]=(TH1F*)hTrigMulSel->ProjectionX(Form("hnEvPerTrigSel%d",i)); hnEvPerTrigSel[i]->SetTitle("Number of events selected per trigger"); hnEvPerTrigSel[i]->SetLineColor(i+1); hnEvPerTrigSel[i]->SetLineWidth(2); cnevs->cd(); if(i==0) hnEvPerTrigSel[i]->Draw(); else hnEvPerTrigSel[i]->Draw("sames"); hnEvSelPerc[i]=(TH1F*)hnEvPerTrigSel[i]->Clone(Form("hnEvSelFrac%d",i)); hnEvSelPerc[i]->SetTitle("Fraction of event selected per trigger"); hnEvSelPerc[i]->SetLineColor(i+1); hnEvSelPerc[i]->SetLineWidth(2); hnEvSelPerc[i]->Divide(hnEvPerTrig[i]); cnevsp->cd(); if(i==0) hnEvSelPerc[i]->Draw("htext0"); else hnEvSelPerc[i]->Draw("htext0sames"); nth1f=0; //restart counting per each file //fill legend leg->AddEntry(hnEvSelPerc[i],legend[i],"L"); for(Int_t j=0; j<nentriesl; j++){ TClass* objtype=lists[i]->At(j)->IsA(); TString tpname=objtype->GetName(); if (tpname=="TH1F"){ TH1F* htmp=(TH1F*)lists[i]->At(j); htmp->SetLineColor(1+i); if(htmp->Integral()>0) htmp->Scale(1./htmp->Integral()); if(first) { c[nth1f]=new TCanvas(Form("c%s",htmp->GetName()),Form("c%s",htmp->GetName())); c[nth1f]->cd(); htmp->Draw(); } else { c[nth1f]->cd(); htmp->Draw("sames"); } nth1f++; } } first=kFALSE; } for(Int_t j=0;j<nth1f;j++){ c[j]->cd(); leg->Draw(); c[j]->SaveAs(Form("%s.pdf",c[j]->GetName())); c[j]->SaveAs(Form("%s.eps",c[j]->GetName())); } cnevs->cd(); leg->Draw(); cnevs->SaveAs(Form("%s.eps",cnevs->GetName())); cnevs->SaveAs(Form("%s.pdf",cnevs->GetName())); cnevsp->cd(); leg->Draw(); cnevsp->SaveAs(Form("%s.eps",cnevsp->GetName())); cnevsp->SaveAs(Form("%s.pdf",cnevsp->GetName())); TCanvas *test=new TCanvas(); test->cd(); leg->Draw(); } void CompilationTrackSelection(Int_t n,TList** lists,TString* legend) { // Specific method for Track output (1) for(Int_t i=0;i<lists[0]->GetEntries();i++){ TObjArray* plotseth=new TObjArray(); TObjArray* plotsethr=new TObjArray(); for(Int_t j=0; j<n; j++){ TH1F* temph=(TH1F*)lists[j]->At(i); TH1F * temphr=0x0; TH1F * ploto=0x0; //0th plot to divide by // plot ratios and scale all plots to integral temphr= (TH1F*)temph->Clone(Form("%s_ratio",temph->GetName())); if(j==0)ploto = temphr; else ploto = (TH1F*)plotseth->At(0); temphr->Divide(ploto); if(temphr->Integral()>0){temphr-> Scale(1./temphr->Integral());}// take out for nonscaled ratios if(temph->Integral()>0){ temph-> Scale(1./temph->Integral());} plotseth->AddLast(new TH1F(*temph)); plotsethr->AddLast(new TH1F(*temphr)); } TH1F *h = (TH1F*)plotseth->At(0); TCanvas* c=new TCanvas(Form("c%s",h->GetName()),h->GetName()); c->cd(); c->SetGrid(); TString hname=h->GetName(); if(!hname.Contains("nCls")){ c->SetLogy(); if(hname.Contains("Layer")){ for(Int_t ibin=1;ibin<=h->GetNbinsX();ibin++){ h->GetXaxis()->SetBinLabel(ibin+1,Form("%d",ibin)); } h->GetXaxis()->SetLabelSize(0.06); h->GetXaxis()->SetRangeUser(0,6); //comment to see ntracks! } //h->SetMinimum(1); h->Draw(); TLegend* leg=new TLegend(0.15,0.5,0.45,0.78); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->AddEntry(h,legend[0],"L"); for(Int_t j=1; j<n; j++){ TH1F * h2 = (TH1F*)plotseth->At(j); h2->SetLineColor(1+j); h2->Draw("sames"); leg->AddEntry(h2,legend[j],"L"); } leg->Draw(); TCanvas* c2=new TCanvas(Form("c2%s",h->GetName()),h->GetName()); c2->cd(); c2->SetGrid(); TH1F *hr = (TH1F*)plotsethr->At(1); hr->SetLineColor(2); hr->Draw(); TLegend* leg2=new TLegend(0.15,0.5,0.45,0.78); leg2->SetFillStyle(0); leg2->SetBorderSize(0); TString ratioleg; ratioleg+=legend[1]; ratioleg+="/"; ratioleg+=legend[0]; leg2->AddEntry(hr,ratioleg,"L"); for(Int_t j=2; j<n; j++){ TH1F * hr2 = (TH1F*)plotsethr->At(j); hr2->SetLineColor(1+j); hr2->Draw("sames"); TString ratioleg2; ratioleg2+=legend[j]; ratioleg2+="/"; ratioleg2+=legend[0]; leg2->AddEntry(hr2,ratioleg2,"L"); } leg2->Draw(); c2->SaveAs(Form("%s%s%sRatio.pdf",c->GetName(),legend[0].Data(), legend[n-1].Data())); c2->SaveAs(Form("%s%s%sRatio.eps",c->GetName(),legend[0].Data(), legend[n-1].Data())); } else { h->Draw("htext0"); TLegend* leg=new TLegend(0.15,0.5,0.45,0.78); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->AddEntry(h,legend[0],"L"); for(Int_t j=1; j<n; j++){ TH1F * h2 = (TH1F*)plotseth->At(j); h2->SetLineColor(1+j); leg->AddEntry(h2,legend[j],"L"); h2->Draw("htext0sames"); } leg->Draw(); } c->cd(); c->SaveAs(Form("%s%s%s.eps",c->GetName(),legend[0].Data(), legend[n-1].Data())); c->SaveAs(Form("%s%s%s.pdf",c->GetName(),legend[0].Data(), legend[n-1].Data())); } Int_t check=0; Int_t maxfa=1; if(n<=10)maxfa=n; else cout<<"Warning: To many files for combinationplot, show only original"<<endl; TLegend* leg3=new TLegend(0.15,0.5,0.45,0.78); leg3->SetFillStyle(0); leg3->SetBorderSize(0); TCanvas* ctrsel=new TCanvas("ctrsel","Track Sel"); ctrsel->SetLogy(); for(Int_t i=0; i<maxfa; i++){ TH1F* hd0fb4=(TH1F*)lists[i]->FindObject("hd0TracksFilterBit4"); TH1F* hd0SPD1=(TH1F*)lists[i]->FindObject("hd0TracksSPDin"); TH1F* hd0SPDany=(TH1F*)lists[i]->FindObject("hd0TracksSPDany"); TH1F* hd0TPCITScuts=(TH1F*)lists[i]->FindObject("hd0TracksTPCITSSPDany"); if(hd0fb4 && hd0SPD1 && hd0SPDany && hd0TPCITScuts){ if(i==0){check=1;} else{if(check==0)return;} ctrsel->cd(); hd0SPD1->SetLineColor(kCyan+3); hd0SPDany->SetLineColor(4); hd0TPCITScuts->SetLineColor(kGreen+1); hd0fb4->SetLineColor(2); if(i==0){ hd0SPD1->Draw(); ctrsel->Update(); TPaveStats *st1=(TPaveStats*)hd0SPD1->GetListOfFunctions()->FindObject("stats"); st1->SetTextColor(kCyan+3); st1->SetY1NDC(0.71); st1->SetY2NDC(0.9); hd0SPDany->Draw("sames"); ctrsel->Update(); TPaveStats *st2=(TPaveStats*)hd0SPDany->GetListOfFunctions()->FindObject("stats"); st2->SetY1NDC(0.51); st2->SetY2NDC(0.7); st2->SetTextColor(4); hd0fb4->Draw("sames"); ctrsel->Update(); TPaveStats *st3=(TPaveStats*)hd0fb4->GetListOfFunctions()->FindObject("stats"); st3->SetY1NDC(0.31); st3->SetY2NDC(0.5); st3->SetTextColor(2); hd0TPCITScuts->Draw("sames"); ctrsel->Update(); TPaveStats *st4=(TPaveStats*)hd0TPCITScuts->GetListOfFunctions()->FindObject("stats"); st4->SetY1NDC(0.71); st4->SetY2NDC(0.9); st4->SetX1NDC(0.55); st4->SetX2NDC(0.75); st4->SetTextColor(kGreen+1); ctrsel->Modified(); leg3->AddEntry(hd0SPD1,"kITSrefit+SPD inner","L"); leg3->AddEntry(hd0SPDany,"kITSrefit+SPD any","L"); leg3->AddEntry(hd0TPCITScuts,"TPC+ITS cuts+SPD any","L"); leg3->AddEntry(hd0fb4,"Filter Bit 4","L"); leg3->AddEntry(hd0SPD1, legend[i], "L"); } else{ hd0SPD1->SetStats(0); hd0SPD1->SetLineStyle(i+1); hd0SPD1->Draw("sames"); hd0SPDany->SetStats(0); hd0SPDany->SetLineStyle(i+1); hd0TPCITScuts->SetStats(0); hd0TPCITScuts->SetLineStyle(i+1); hd0fb4->SetStats(0); hd0fb4->SetLineStyle(i+1); ctrsel->cd(); hd0SPD1->Draw("sames"); hd0SPDany->Draw("sames"); hd0TPCITScuts->Draw("sames"); hd0fb4->Draw("sames"); leg3->AddEntry(hd0SPD1, legend[i], "L"); } } } leg3->Draw(); ctrsel->SaveAs("ImpactParameterTrackSel.eps"); ctrsel->SaveAs("ImpactParameterTrackSel.pdf"); }
AliAnalysisTaskSE *AddTaskSigma0Femto(bool isMC = false, bool MomRes = false, bool etaPhiPlotsAtTPCRadii = false, TString trigger = "kINT7", const char *cutVariation = "0") { TString suffix; suffix.Form("%s", cutVariation); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskSigma0Run2()", "No analysis manager found."); return 0x0; } // ================== GetInputEventHandler ============================= AliVEventHandler *inputHandler = mgr->GetInputEventHandler(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); //========= Set Cutnumber for V0Reader ================================ TString cutnumberPhoton; cutnumberPhoton = "00200008400000002280920000"; TString cutnumberEvent = "00000000"; TString periodNameV0Reader = ""; Bool_t enableV0findingEffi = kFALSE; Bool_t fillHistos = kTRUE; Bool_t runLightOutput = kFALSE; if (suffix != "0" && suffix != "999") { runLightOutput = kTRUE; fillHistos = kFALSE; } if (suffix == "21") { // eta < 0.8 cutnumberPhoton = "0d200008400000002280920000"; } else if (suffix == "22") { // single pT > 0, gammapT > 0 cutnumberPhoton = "00200078400000002280920000"; } else if (suffix == "23") { // single pT > 0.050, gammapT > 0.150 cutnumberPhoton = "002000a8400000002280920000"; } else if (suffix == "24") { // TPC cluster, findable > 0.6 cutnumberPhoton = "00200009400000002280920000"; } else if (suffix == "25") { // TPC PID -10,10 cutnumberPhoton = "00200008000000002280920000"; } else if (suffix == "26") { // TPC PID -3,3 cutnumberPhoton = "00200008a00000002280920000"; } else if (suffix == "27") { // 1-D Qt cut, qt < 0.1 cutnumberPhoton = "00200008400000001280920000"; } else if (suffix == "28") { // 2-D Qt cut, qt < 0.05 cutnumberPhoton = "00200008400000003280920000"; } else if (suffix == "29") { // psiPair < 0.2, 1-D cutnumberPhoton = "00200008400000002240920000"; } else if (suffix == "30") { // psiPair < 0.1, 2-D cutnumberPhoton = "00200008400000002250920000"; } else if (suffix == "31") { // cosPA < 0.98 cutnumberPhoton = "00200008400000002280820000"; } else if (suffix == "32") { // cosPA < 0.995 cutnumberPhoton = "00200008400000002280a20000"; } else if (suffix == "33") { // DCA_R < 5 cutnumberPhoton = "00200008400000002280920200"; } else if (suffix == "34") { // DCA_Z < 5 cutnumberPhoton = "00200008400000002280920020"; } //========= Add V0 Reader to ANALYSIS manager if not yet existent ===== TString V0ReaderName = Form("V0ReaderV1_%s_%s", cutnumberEvent.Data(), cutnumberPhoton.Data()); AliConvEventCuts *fEventCuts = NULL; if (!(AliV0ReaderV1 *)mgr->GetTask(V0ReaderName.Data())) { AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data()); if (periodNameV0Reader.CompareTo("") != 0) fV0ReaderV1->SetPeriodName(periodNameV0Reader); fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE); fV0ReaderV1->SetCreateAODs(kFALSE); // AOD Output fV0ReaderV1->SetUseAODConversionPhoton(kTRUE); fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi); if (!mgr) { Error("AddTask_V0ReaderV1", "No analysis manager found."); return NULL; } if (cutnumberEvent != "") { fEventCuts = new AliConvEventCuts(cutnumberEvent.Data(), cutnumberEvent.Data()); fEventCuts->SetPreSelectionCutFlag(kTRUE); fEventCuts->SetV0ReaderName(V0ReaderName); fEventCuts->SetLightOutput(runLightOutput); fEventCuts->SetFillCutHistograms("", fillHistos); if (periodNameV0Reader.CompareTo("") != 0) fEventCuts->SetPeriodEnum(periodNameV0Reader); fV0ReaderV1->SetEventCuts(fEventCuts); } // Set AnalysisCut Number AliConversionPhotonCuts *fCuts = NULL; if (cutnumberPhoton != "") { fCuts = new AliConversionPhotonCuts(cutnumberPhoton.Data(), cutnumberPhoton.Data()); fCuts->SetPreSelectionCutFlag(kTRUE); fCuts->SetIsHeavyIon(false); fCuts->SetV0ReaderName(V0ReaderName); fCuts->SetLightOutput(runLightOutput); fCuts->SetFillCutHistograms("", fillHistos); if (fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())) { fV0ReaderV1->SetConversionCuts(fCuts); } } fV0ReaderV1->Init(); AliLog::SetGlobalLogLevel(AliLog::kFatal); // connect input V0Reader mgr->AddTask(fV0ReaderV1); mgr->ConnectInput(fV0ReaderV1, 0, cinput); } //========= Init subtasks and start analyis ============================ // Event Cuts AliFemtoDreamEventCuts *evtCuts = AliFemtoDreamEventCuts::StandardCutsRun2(); evtCuts->CleanUpMult(false, false, false, true); // Track Cuts AliFemtoDreamTrackCuts *TrackCuts = AliFemtoDreamTrackCuts::PrimProtonCuts(isMC, true, false, false); TrackCuts->SetCheckFilterBit(false); TrackCuts->SetCheckESDFiltering(true); TrackCuts->SetDCAReCalculation(false); TrackCuts->SetCutCharge(1); AliFemtoDreamTrackCuts *AntiTrackCuts = AliFemtoDreamTrackCuts::PrimProtonCuts(isMC, true, false, false); AntiTrackCuts->SetCheckFilterBit(false); AntiTrackCuts->SetCheckESDFiltering(true); AntiTrackCuts->SetDCAReCalculation(false); AntiTrackCuts->SetCutCharge(-1); if (suffix != "0" && suffix != "999") { TrackCuts->SetMinimalBooking(true); AntiTrackCuts->SetMinimalBooking(true); } if (suffix == "1") { TrackCuts->SetPtRange(0.4, 4.05); AntiTrackCuts->SetPtRange(0.4, 4.05); } else if (suffix == "2") { TrackCuts->SetPtRange(0.6, 4.05); AntiTrackCuts->SetPtRange(0.6, 4.05); } else if (suffix == "3") { TrackCuts->SetEtaRange(-0.7, 0.7); AntiTrackCuts->SetEtaRange(-0.7, 0.7); } else if (suffix == "4") { TrackCuts->SetEtaRange(-0.9, 0.9); AntiTrackCuts->SetEtaRange(-0.9, 0.9); } else if (suffix == "5") { TrackCuts->SetPID(AliPID::kProton, 0.75, 2); AntiTrackCuts->SetPID(AliPID::kProton, 0.75, 2); } else if (suffix == "6") { TrackCuts->SetPID(AliPID::kProton, 0.75, 5); AntiTrackCuts->SetPID(AliPID::kProton, 0.75, 5); } else if (suffix == "7") { TrackCuts->SetFilterBit(96); AntiTrackCuts->SetFilterBit(96); } else if (suffix == "8") { TrackCuts->SetNClsTPC(70); AntiTrackCuts->SetNClsTPC(70); } else if (suffix == "9") { TrackCuts->SetNClsTPC(90); AntiTrackCuts->SetNClsTPC(90); } AliSigma0V0Cuts *v0Cuts = AliSigma0V0Cuts::LambdaCuts(); v0Cuts->SetIsMC(isMC); v0Cuts->SetPID(3122); v0Cuts->SetPosPID(AliPID::kProton, 2212); v0Cuts->SetNegPID(AliPID::kPion, -211); AliSigma0V0Cuts *antiv0Cuts = AliSigma0V0Cuts::LambdaCuts(); antiv0Cuts->SetIsMC(isMC); antiv0Cuts->SetPID(-3122); antiv0Cuts->SetPosPID(AliPID::kPion, 211); antiv0Cuts->SetNegPID(AliPID::kProton, -2212); if (suffix != "0") { v0Cuts->SetLightweight(true); antiv0Cuts->SetLightweight(true); } if (suffix == "10") { v0Cuts->SetV0PtMin(0.24); antiv0Cuts->SetV0PtMin(0.24); } else if (suffix == "11") { v0Cuts->SetV0PtMin(0.36); antiv0Cuts->SetV0PtMin(0.36); } else if (suffix == "12") { v0Cuts->SetV0CosPAMin(0.995); antiv0Cuts->SetV0CosPAMin(0.995); } else if (suffix == "13") { v0Cuts->SetV0CosPAMin(0.98); antiv0Cuts->SetV0CosPAMin(0.98); } else if (suffix == "14") { v0Cuts->SetPIDnSigma(3); antiv0Cuts->SetPIDnSigma(3); } else if (suffix == "15") { v0Cuts->SetPIDnSigma(6); antiv0Cuts->SetPIDnSigma(6); } else if (suffix == "16") { v0Cuts->SetArmenterosCut(0., 0.15, 0.2, 1); antiv0Cuts->SetArmenterosCut(0, 0.15, 0.2, 1); } else if (suffix == "17") { v0Cuts->SetTPCclusterMin(80); antiv0Cuts->SetTPCclusterMin(80); } else if (suffix == "18") { v0Cuts->SetTPCclusterMin(60); antiv0Cuts->SetTPCclusterMin(60); } else if (suffix == "19") { v0Cuts->SetEtaMax(0.8); antiv0Cuts->SetEtaMax(0.8); } else if (suffix == "20") { v0Cuts->SetLambdaSelection(1.115683 - 0.008, 1.115683 + 0.008); antiv0Cuts->SetLambdaSelection(1.115683 - 0.008, 1.115683 + 0.008); } if (suffix == "999") { v0Cuts->SetCheckCutsMC(true); antiv0Cuts->SetCheckCutsMC(true); v0Cuts->SetLightweight(false); antiv0Cuts->SetLightweight(false); } AliSigma0PhotonMotherCuts *sigmaCuts = AliSigma0PhotonMotherCuts::DefaultCuts(); sigmaCuts->SetIsMC(isMC); sigmaCuts->SetPDG(3212, 3122, 22); sigmaCuts->SetLambdaCuts(v0Cuts); sigmaCuts->SetV0ReaderName(V0ReaderName.Data()); sigmaCuts->SetIsSpectrum(false); if (suffix != "0" && suffix != "999") { sigmaCuts->SetLightweight(true); } AliSigma0PhotonMotherCuts *antiSigmaCuts = AliSigma0PhotonMotherCuts::DefaultCuts(); antiSigmaCuts->SetIsMC(isMC); antiSigmaCuts->SetPDG(-3212, -3122, 22); antiSigmaCuts->SetLambdaCuts(antiv0Cuts); antiSigmaCuts->SetV0ReaderName(V0ReaderName.Data()); antiSigmaCuts->SetIsSpectrum(false); if (suffix != "0" && suffix != "999") { antiSigmaCuts->SetLightweight(true); } if (trigger == "kINT7") { sigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); } else if (trigger == "kHighMultV0") { sigmaCuts->SetMultiplicityMode(AliVEvent::kHighMultV0); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kHighMultV0); } // Femto Collection std::vector<int> PDGParticles; PDGParticles.push_back(2212); PDGParticles.push_back(2212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); if (suffix == "0") { PDGParticles.push_back(3122); PDGParticles.push_back(22); PDGParticles.push_back(3122); PDGParticles.push_back(22); } std::vector<float> ZVtxBins; ZVtxBins.push_back(-10); ZVtxBins.push_back(-8); ZVtxBins.push_back(-6); ZVtxBins.push_back(-4); ZVtxBins.push_back(-2); ZVtxBins.push_back(0); ZVtxBins.push_back(2); ZVtxBins.push_back(4); ZVtxBins.push_back(6); ZVtxBins.push_back(8); ZVtxBins.push_back(10); std::vector<int> NBins; std::vector<float> kMin; std::vector<float> kMax; std::vector<int> pairQA; std::vector<bool> closeRejection; const int nPairs = (suffix == "0") ? 78 : 36; for (int i = 0; i < nPairs; ++i) { pairQA.push_back(0); closeRejection.push_back(false); if (suffix == "0") { NBins.push_back(750); kMin.push_back(0.); kMax.push_back(3.); } else { NBins.push_back(250); kMin.push_back(0.); kMax.push_back(1.); } } // do extended QA for the pairs in default mode if (suffix == "0") { pairQA[0] = 11; // pp pairQA[2] = 14; // pSigma pairQA[12] = 11; // barp barp pairQA[14] = 14; // barp bSigma pairQA[23] = 44; // Sigma Sigma pairQA[33] = 44; // barSigma barSigma closeRejection[0] = true; // pp closeRejection[12] = true; // barp barp } else { closeRejection[0] = true; // pp closeRejection[8] = true; // barp barp } AliFemtoDreamCollConfig *config = new AliFemtoDreamCollConfig("Femto", "Femto"); std::vector<int> MultBins; if (trigger == "kHighMultV0") { std::vector<int> MultBins; MultBins.push_back(0); MultBins.push_back(4); MultBins.push_back(8); MultBins.push_back(12); MultBins.push_back(16); MultBins.push_back(20); MultBins.push_back(24); MultBins.push_back(28); MultBins.push_back(32); MultBins.push_back(36); MultBins.push_back(40); MultBins.push_back(44); MultBins.push_back(48); MultBins.push_back(52); MultBins.push_back(56); MultBins.push_back(60); MultBins.push_back(64); MultBins.push_back(68); MultBins.push_back(72); MultBins.push_back(76); MultBins.push_back(80); MultBins.push_back(84); MultBins.push_back(88); MultBins.push_back(92); MultBins.push_back(96); MultBins.push_back(100); config->SetMultBins(MultBins); } else { std::vector<int> MultBins; MultBins.push_back(0); MultBins.push_back(4); MultBins.push_back(8); MultBins.push_back(12); MultBins.push_back(16); MultBins.push_back(20); MultBins.push_back(24); MultBins.push_back(28); MultBins.push_back(32); MultBins.push_back(36); MultBins.push_back(40); MultBins.push_back(60); MultBins.push_back(80); config->SetMultBins(MultBins); } config->SetMultBinning(true); config->SetExtendedQAPairs(pairQA); config->SetZBins(ZVtxBins); if (MomRes) { if (isMC) { config->SetMomentumResolution(true); } else { std::cout << "You are trying to request the Momentum Resolution without " "MC Info; fix it wont work! \n"; } } if (trigger == "kHighMultV0") { config->SetDeltaEtaMax(0.01); config->SetDeltaPhiMax(0.01); config->SetClosePairRejection(closeRejection); } if (suffix == "0") { config->SetPhiEtaBinnign(true); } config->SetdPhidEtaPlots(false); config->SetPDGCodes(PDGParticles); config->SetNBinsHist(NBins); config->SetMinKRel(kMin); config->SetMaxKRel(kMax); config->SetMixingDepth(10); config->SetUseEventMixing(true); config->SetMultiplicityEstimator(AliFemtoDreamEvent::kRef08); if (suffix != "0") { config->SetMinimalBookingME(true); } AliAnalysisTaskSigma0Femto *task = new AliAnalysisTaskSigma0Femto("AnalysisTaskSigma0Femto"); if (trigger == "kINT7") { task->SetTrigger(AliVEvent::kINT7); task->SetMultiplicityMode(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); } else if (trigger == "kHighMultV0") { if (isMC) { task->SetTrigger(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); task->SetMultiplicityMode(AliVEvent::kHighMultV0); } else { task->SetTrigger(AliVEvent::kHighMultV0); task->SelectCollisionCandidates(AliVEvent::kHighMultV0); task->SetMultiplicityMode(AliVEvent::kHighMultV0); } } task->SetEventCuts(evtCuts); task->SetV0ReaderName(V0ReaderName.Data()); task->SetIsMC(isMC); task->SetProtonCuts(TrackCuts); task->SetAntiProtonCuts(AntiTrackCuts); task->SetV0Cuts(v0Cuts); task->SetAntiV0Cuts(antiv0Cuts); task->SetSigmaCuts(sigmaCuts); task->SetAntiSigmaCuts(antiSigmaCuts); task->SetCollectionConfig(config); if (suffix != "0" && suffix != "999") { task->SetLightweight(true); } mgr->AddTask(task); TString containerName = mgr->GetCommonFileName(); containerName += ":Sigma0_Femto_"; if (trigger == "kHighMultV0") containerName += "HighMultV0_"; containerName += suffix; TString name = "histo_"; if (trigger == "kHighMultV0") name += "HighMultV0_"; name += suffix; AliAnalysisDataContainer *cOutputList = mgr->CreateContainer( name, TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); name = "femto_"; if (trigger == "kHighMultV0") name += "HighMultV0_"; name += suffix; AliAnalysisDataContainer *cFemtoOutputList = mgr->CreateContainer( name, TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, cOutputList); mgr->ConnectOutput(task, 2, cFemtoOutputList); return task; } Remove DCA vars of the photons AliAnalysisTaskSE *AddTaskSigma0Femto(bool isMC = false, bool MomRes = false, bool etaPhiPlotsAtTPCRadii = false, TString trigger = "kINT7", const char *cutVariation = "0") { TString suffix; suffix.Form("%s", cutVariation); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskSigma0Run2()", "No analysis manager found."); return 0x0; } // ================== GetInputEventHandler ============================= AliVEventHandler *inputHandler = mgr->GetInputEventHandler(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); //========= Set Cutnumber for V0Reader ================================ TString cutnumberPhoton; cutnumberPhoton = "00200008400000002280920000"; TString cutnumberEvent = "00000000"; TString periodNameV0Reader = ""; Bool_t enableV0findingEffi = kFALSE; Bool_t fillHistos = kTRUE; Bool_t runLightOutput = kFALSE; if (suffix != "0" && suffix != "999") { runLightOutput = kTRUE; fillHistos = kFALSE; } if (suffix == "21") { // eta < 0.8 cutnumberPhoton = "0d200008400000002280920000"; } else if (suffix == "22") { // single pT > 0, gammapT > 0 cutnumberPhoton = "00200078400000002280920000"; } else if (suffix == "23") { // single pT > 0.050, gammapT > 0.150 cutnumberPhoton = "002000a8400000002280920000"; } else if (suffix == "24") { // TPC cluster, findable > 0.6 cutnumberPhoton = "00200009400000002280920000"; } else if (suffix == "25") { // TPC PID -10,10 cutnumberPhoton = "00200008000000002280920000"; } else if (suffix == "26") { // TPC PID -3,3 cutnumberPhoton = "00200008a00000002280920000"; } else if (suffix == "27") { // 1-D Qt cut, qt < 0.1 cutnumberPhoton = "00200008400000001280920000"; } else if (suffix == "28") { // 2-D Qt cut, qt < 0.05 cutnumberPhoton = "00200008400000003280920000"; } else if (suffix == "29") { // psiPair < 0.2, 1-D cutnumberPhoton = "00200008400000002240920000"; } else if (suffix == "30") { // psiPair < 0.1, 2-D cutnumberPhoton = "00200008400000002250920000"; } else if (suffix == "31") { // cosPA < 0.98 cutnumberPhoton = "00200008400000002280820000"; } else if (suffix == "32") { // cosPA < 0.995 cutnumberPhoton = "00200008400000002280a20000"; } //========= Add V0 Reader to ANALYSIS manager if not yet existent ===== TString V0ReaderName = Form("V0ReaderV1_%s_%s", cutnumberEvent.Data(), cutnumberPhoton.Data()); AliConvEventCuts *fEventCuts = NULL; if (!(AliV0ReaderV1 *)mgr->GetTask(V0ReaderName.Data())) { AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data()); if (periodNameV0Reader.CompareTo("") != 0) fV0ReaderV1->SetPeriodName(periodNameV0Reader); fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE); fV0ReaderV1->SetCreateAODs(kFALSE); // AOD Output fV0ReaderV1->SetUseAODConversionPhoton(kTRUE); fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi); if (!mgr) { Error("AddTask_V0ReaderV1", "No analysis manager found."); return NULL; } if (cutnumberEvent != "") { fEventCuts = new AliConvEventCuts(cutnumberEvent.Data(), cutnumberEvent.Data()); fEventCuts->SetPreSelectionCutFlag(kTRUE); fEventCuts->SetV0ReaderName(V0ReaderName); fEventCuts->SetLightOutput(runLightOutput); fEventCuts->SetFillCutHistograms("", fillHistos); if (periodNameV0Reader.CompareTo("") != 0) fEventCuts->SetPeriodEnum(periodNameV0Reader); fV0ReaderV1->SetEventCuts(fEventCuts); } // Set AnalysisCut Number AliConversionPhotonCuts *fCuts = NULL; if (cutnumberPhoton != "") { fCuts = new AliConversionPhotonCuts(cutnumberPhoton.Data(), cutnumberPhoton.Data()); fCuts->SetPreSelectionCutFlag(kTRUE); fCuts->SetIsHeavyIon(false); fCuts->SetV0ReaderName(V0ReaderName); fCuts->SetLightOutput(runLightOutput); fCuts->SetFillCutHistograms("", fillHistos); if (fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())) { fV0ReaderV1->SetConversionCuts(fCuts); } } fV0ReaderV1->Init(); AliLog::SetGlobalLogLevel(AliLog::kFatal); // connect input V0Reader mgr->AddTask(fV0ReaderV1); mgr->ConnectInput(fV0ReaderV1, 0, cinput); } //========= Init subtasks and start analyis ============================ // Event Cuts AliFemtoDreamEventCuts *evtCuts = AliFemtoDreamEventCuts::StandardCutsRun2(); evtCuts->CleanUpMult(false, false, false, true); // Track Cuts AliFemtoDreamTrackCuts *TrackCuts = AliFemtoDreamTrackCuts::PrimProtonCuts(isMC, true, false, false); TrackCuts->SetCheckFilterBit(false); TrackCuts->SetCheckESDFiltering(true); TrackCuts->SetDCAReCalculation(false); TrackCuts->SetCutCharge(1); AliFemtoDreamTrackCuts *AntiTrackCuts = AliFemtoDreamTrackCuts::PrimProtonCuts(isMC, true, false, false); AntiTrackCuts->SetCheckFilterBit(false); AntiTrackCuts->SetCheckESDFiltering(true); AntiTrackCuts->SetDCAReCalculation(false); AntiTrackCuts->SetCutCharge(-1); if (suffix != "0" && suffix != "999") { TrackCuts->SetMinimalBooking(true); AntiTrackCuts->SetMinimalBooking(true); } if (suffix == "1") { TrackCuts->SetPtRange(0.4, 4.05); AntiTrackCuts->SetPtRange(0.4, 4.05); } else if (suffix == "2") { TrackCuts->SetPtRange(0.6, 4.05); AntiTrackCuts->SetPtRange(0.6, 4.05); } else if (suffix == "3") { TrackCuts->SetEtaRange(-0.7, 0.7); AntiTrackCuts->SetEtaRange(-0.7, 0.7); } else if (suffix == "4") { TrackCuts->SetEtaRange(-0.9, 0.9); AntiTrackCuts->SetEtaRange(-0.9, 0.9); } else if (suffix == "5") { TrackCuts->SetPID(AliPID::kProton, 0.75, 2); AntiTrackCuts->SetPID(AliPID::kProton, 0.75, 2); } else if (suffix == "6") { TrackCuts->SetPID(AliPID::kProton, 0.75, 5); AntiTrackCuts->SetPID(AliPID::kProton, 0.75, 5); } else if (suffix == "7") { TrackCuts->SetFilterBit(96); AntiTrackCuts->SetFilterBit(96); } else if (suffix == "8") { TrackCuts->SetNClsTPC(70); AntiTrackCuts->SetNClsTPC(70); } else if (suffix == "9") { TrackCuts->SetNClsTPC(90); AntiTrackCuts->SetNClsTPC(90); } AliSigma0V0Cuts *v0Cuts = AliSigma0V0Cuts::LambdaCuts(); v0Cuts->SetIsMC(isMC); v0Cuts->SetPID(3122); v0Cuts->SetPosPID(AliPID::kProton, 2212); v0Cuts->SetNegPID(AliPID::kPion, -211); AliSigma0V0Cuts *antiv0Cuts = AliSigma0V0Cuts::LambdaCuts(); antiv0Cuts->SetIsMC(isMC); antiv0Cuts->SetPID(-3122); antiv0Cuts->SetPosPID(AliPID::kPion, 211); antiv0Cuts->SetNegPID(AliPID::kProton, -2212); if (suffix != "0") { v0Cuts->SetLightweight(true); antiv0Cuts->SetLightweight(true); } if (suffix == "10") { v0Cuts->SetV0PtMin(0.24); antiv0Cuts->SetV0PtMin(0.24); } else if (suffix == "11") { v0Cuts->SetV0PtMin(0.36); antiv0Cuts->SetV0PtMin(0.36); } else if (suffix == "12") { v0Cuts->SetV0CosPAMin(0.995); antiv0Cuts->SetV0CosPAMin(0.995); } else if (suffix == "13") { v0Cuts->SetV0CosPAMin(0.98); antiv0Cuts->SetV0CosPAMin(0.98); } else if (suffix == "14") { v0Cuts->SetPIDnSigma(3); antiv0Cuts->SetPIDnSigma(3); } else if (suffix == "15") { v0Cuts->SetPIDnSigma(6); antiv0Cuts->SetPIDnSigma(6); } else if (suffix == "16") { v0Cuts->SetArmenterosCut(0., 0.15, 0.2, 1); antiv0Cuts->SetArmenterosCut(0, 0.15, 0.2, 1); } else if (suffix == "17") { v0Cuts->SetTPCclusterMin(80); antiv0Cuts->SetTPCclusterMin(80); } else if (suffix == "18") { v0Cuts->SetTPCclusterMin(60); antiv0Cuts->SetTPCclusterMin(60); } else if (suffix == "19") { v0Cuts->SetEtaMax(0.8); antiv0Cuts->SetEtaMax(0.8); } else if (suffix == "20") { v0Cuts->SetLambdaSelection(1.115683 - 0.008, 1.115683 + 0.008); antiv0Cuts->SetLambdaSelection(1.115683 - 0.008, 1.115683 + 0.008); } if (suffix == "999") { v0Cuts->SetCheckCutsMC(true); antiv0Cuts->SetCheckCutsMC(true); v0Cuts->SetLightweight(false); antiv0Cuts->SetLightweight(false); } AliSigma0PhotonMotherCuts *sigmaCuts = AliSigma0PhotonMotherCuts::DefaultCuts(); sigmaCuts->SetIsMC(isMC); sigmaCuts->SetPDG(3212, 3122, 22); sigmaCuts->SetLambdaCuts(v0Cuts); sigmaCuts->SetV0ReaderName(V0ReaderName.Data()); sigmaCuts->SetIsSpectrum(false); if (suffix != "0" && suffix != "999") { sigmaCuts->SetLightweight(true); } AliSigma0PhotonMotherCuts *antiSigmaCuts = AliSigma0PhotonMotherCuts::DefaultCuts(); antiSigmaCuts->SetIsMC(isMC); antiSigmaCuts->SetPDG(-3212, -3122, 22); antiSigmaCuts->SetLambdaCuts(antiv0Cuts); antiSigmaCuts->SetV0ReaderName(V0ReaderName.Data()); antiSigmaCuts->SetIsSpectrum(false); if (suffix != "0" && suffix != "999") { antiSigmaCuts->SetLightweight(true); } if (trigger == "kINT7") { sigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); } else if (trigger == "kHighMultV0") { sigmaCuts->SetMultiplicityMode(AliVEvent::kHighMultV0); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kHighMultV0); } // Femto Collection std::vector<int> PDGParticles; PDGParticles.push_back(2212); PDGParticles.push_back(2212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); PDGParticles.push_back(3212); if (suffix == "0") { PDGParticles.push_back(3122); PDGParticles.push_back(22); PDGParticles.push_back(3122); PDGParticles.push_back(22); } std::vector<float> ZVtxBins; ZVtxBins.push_back(-10); ZVtxBins.push_back(-8); ZVtxBins.push_back(-6); ZVtxBins.push_back(-4); ZVtxBins.push_back(-2); ZVtxBins.push_back(0); ZVtxBins.push_back(2); ZVtxBins.push_back(4); ZVtxBins.push_back(6); ZVtxBins.push_back(8); ZVtxBins.push_back(10); std::vector<int> NBins; std::vector<float> kMin; std::vector<float> kMax; std::vector<int> pairQA; std::vector<bool> closeRejection; const int nPairs = (suffix == "0") ? 78 : 36; for (int i = 0; i < nPairs; ++i) { pairQA.push_back(0); closeRejection.push_back(false); if (suffix == "0") { NBins.push_back(750); kMin.push_back(0.); kMax.push_back(3.); } else { NBins.push_back(250); kMin.push_back(0.); kMax.push_back(1.); } } // do extended QA for the pairs in default mode if (suffix == "0") { pairQA[0] = 11; // pp pairQA[2] = 14; // pSigma pairQA[12] = 11; // barp barp pairQA[14] = 14; // barp bSigma pairQA[23] = 44; // Sigma Sigma pairQA[33] = 44; // barSigma barSigma closeRejection[0] = true; // pp closeRejection[12] = true; // barp barp } else { closeRejection[0] = true; // pp closeRejection[8] = true; // barp barp } AliFemtoDreamCollConfig *config = new AliFemtoDreamCollConfig("Femto", "Femto"); std::vector<int> MultBins; if (trigger == "kHighMultV0") { std::vector<int> MultBins; MultBins.push_back(0); MultBins.push_back(4); MultBins.push_back(8); MultBins.push_back(12); MultBins.push_back(16); MultBins.push_back(20); MultBins.push_back(24); MultBins.push_back(28); MultBins.push_back(32); MultBins.push_back(36); MultBins.push_back(40); MultBins.push_back(44); MultBins.push_back(48); MultBins.push_back(52); MultBins.push_back(56); MultBins.push_back(60); MultBins.push_back(64); MultBins.push_back(68); MultBins.push_back(72); MultBins.push_back(76); MultBins.push_back(80); MultBins.push_back(84); MultBins.push_back(88); MultBins.push_back(92); MultBins.push_back(96); MultBins.push_back(100); config->SetMultBins(MultBins); } else { std::vector<int> MultBins; MultBins.push_back(0); MultBins.push_back(4); MultBins.push_back(8); MultBins.push_back(12); MultBins.push_back(16); MultBins.push_back(20); MultBins.push_back(24); MultBins.push_back(28); MultBins.push_back(32); MultBins.push_back(36); MultBins.push_back(40); MultBins.push_back(60); MultBins.push_back(80); config->SetMultBins(MultBins); } config->SetMultBinning(true); config->SetExtendedQAPairs(pairQA); config->SetZBins(ZVtxBins); if (MomRes) { if (isMC) { config->SetMomentumResolution(true); } else { std::cout << "You are trying to request the Momentum Resolution without " "MC Info; fix it wont work! \n"; } } if (trigger == "kHighMultV0") { config->SetDeltaEtaMax(0.01); config->SetDeltaPhiMax(0.01); config->SetClosePairRejection(closeRejection); } if (suffix == "0") { config->SetPhiEtaBinnign(true); } config->SetdPhidEtaPlots(false); config->SetPDGCodes(PDGParticles); config->SetNBinsHist(NBins); config->SetMinKRel(kMin); config->SetMaxKRel(kMax); config->SetMixingDepth(10); config->SetUseEventMixing(true); config->SetMultiplicityEstimator(AliFemtoDreamEvent::kRef08); if (suffix != "0") { config->SetMinimalBookingME(true); } AliAnalysisTaskSigma0Femto *task = new AliAnalysisTaskSigma0Femto("AnalysisTaskSigma0Femto"); if (trigger == "kINT7") { task->SetTrigger(AliVEvent::kINT7); task->SetMultiplicityMode(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); } else if (trigger == "kHighMultV0") { if (isMC) { task->SetTrigger(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); task->SetMultiplicityMode(AliVEvent::kHighMultV0); } else { task->SetTrigger(AliVEvent::kHighMultV0); task->SelectCollisionCandidates(AliVEvent::kHighMultV0); task->SetMultiplicityMode(AliVEvent::kHighMultV0); } } task->SetEventCuts(evtCuts); task->SetV0ReaderName(V0ReaderName.Data()); task->SetIsMC(isMC); task->SetProtonCuts(TrackCuts); task->SetAntiProtonCuts(AntiTrackCuts); task->SetV0Cuts(v0Cuts); task->SetAntiV0Cuts(antiv0Cuts); task->SetSigmaCuts(sigmaCuts); task->SetAntiSigmaCuts(antiSigmaCuts); task->SetCollectionConfig(config); if (suffix != "0" && suffix != "999") { task->SetLightweight(true); } mgr->AddTask(task); TString containerName = mgr->GetCommonFileName(); containerName += ":Sigma0_Femto_"; if (trigger == "kHighMultV0") containerName += "HighMultV0_"; containerName += suffix; TString name = "histo_"; if (trigger == "kHighMultV0") name += "HighMultV0_"; name += suffix; AliAnalysisDataContainer *cOutputList = mgr->CreateContainer( name, TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); name = "femto_"; if (trigger == "kHighMultV0") name += "HighMultV0_"; name += suffix; AliAnalysisDataContainer *cFemtoOutputList = mgr->CreateContainer( name, TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, cOutputList); mgr->ConnectOutput(task, 2, cFemtoOutputList); return task; }
Fixing default argument for Q/pt-shift switch also in jet task
AliAnalysisTaskSEImproveITS *AddTaskImproveITS(Bool_t isRunInVertexing=kFALSE, // set to kTRUE to run during AODvertexingHF creation const char *resfileCurURI="$ALICE_ROOT/PWGHF/vertexingHF/macros/ITSgraphs_Current.root", const char *resfileUpgURI="$ALICE_ROOT/PWGHF/vertexingHF/macros/ITSgraphs_NewAll-X0.3-Res4um.root", Int_t ndebug=0) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddAliAnalysisTaskSEImproveITS", "No analysis manager to connect to."); return 0; } AliAnalysisTaskSEImproveITS *task =new AliAnalysisTaskSEImproveITS("ITSImprover", resfileCurURI, resfileUpgURI, isRunInVertexing, ndebug); mgr->AddTask(task); TString outputFileName=AliAnalysisManager::GetCommonFileName(); outputFileName+=":ITSImprover"; AliAnalysisDataContainer *coutput =mgr->CreateContainer("debug", TNtuple::Class(), AliAnalysisManager::kOutputContainer, outputFileName); mgr->ConnectInput (task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,coutput); return task; } changed path to resolution files AliAnalysisTaskSEImproveITS *AddTaskImproveITS(Bool_t isRunInVertexing=kFALSE, // set to kTRUE to run during AODvertexingHF creation const char *resfileCurURI="$ALICE_ROOT/PWGHF/vertexingHF/upgrade/ITSgraphs_Current.root", const char *resfileUpgURI="$ALICE_ROOT/PWGHF/vertexingHF/upgrade/ITSgraphs_NewAll-X0.3-Res4um.root", Int_t ndebug=0) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddAliAnalysisTaskSEImproveITS", "No analysis manager to connect to."); return 0; } AliAnalysisTaskSEImproveITS *task =new AliAnalysisTaskSEImproveITS("ITSImprover", resfileCurURI, resfileUpgURI, isRunInVertexing, ndebug); mgr->AddTask(task); TString outputFileName=AliAnalysisManager::GetCommonFileName(); outputFileName+=":ITSImprover"; AliAnalysisDataContainer *coutput =mgr->CreateContainer("debug", TNtuple::Class(), AliAnalysisManager::kOutputContainer, outputFileName); mgr->ConnectInput (task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,coutput); return task; }
AliEmcalJetTask* AddTaskEmcalJet( const char *nTracks = "usedefault", const char *nClusters = "usedefault", const AliJetContainer::EJetAlgo_t jetAlgo = AliJetContainer::antikt_algorithm, const Double_t radius = 0.4, const AliJetContainer::EJetType_t jetType = AliJetContainer::kFullJet, const Double_t minTrPt = 0.15, const Double_t minClPt = 0.30, const Double_t ghostArea = 0.005, const AliJetContainer::ERecoScheme_t reco = AliJetContainer::pt_scheme, const char *tag = "Jet", const Double_t minJetPt = 0., const Bool_t lockTask = kTRUE, const Bool_t bFillGhosts = kFALSE ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEmcalJet", "No analysis manager to connect to."); return 0; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== AliVEventHandler* handler = mgr->GetInputEventHandler(); if (!handler) { ::Error("AddTaskEmcalJet", "This task requires an input event handler"); return 0; } enum EDataType_t { kUnknown, kESD, kAOD, kMCgen }; TString trackName(nTracks); TString clusName(nClusters); EDataType_t dataType = kUnknown; if (handler->InheritsFrom("AliESDInputHandler")) { dataType = kESD; } else if (handler->InheritsFrom("AliAODInputHandler")) { dataType = kAOD; } else if (handler->InheritsFrom("AliMCGenHandler")) { dataType = kMCgen; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- if (trackName == "usedefault") { if (dataType == kESD) { trackName = "Tracks"; } else if (dataType == kAOD) { trackName = "tracks"; } else if (dataType == kMCgen) { trackName = "mcparticles"; } } if (clusName == "usedefault") { if (dataType == kESD) { clusName = "CaloClusters"; } else if (dataType == kAOD) { clusName = "caloClusters"; } else { clusName = ""; } } AliParticleContainer* partCont = 0; if (trackName == "mcparticles") { AliMCParticleContainer* mcpartCont = new AliMCParticleContainer(trackName); partCont = mcpartCont; } else if (trackName == "tracks" || trackName == "Tracks") { AliTrackContainer* trackCont = new AliTrackContainer(trackName); partCont = trackCont; } else if (!trackName.IsNull()) { partCont = new AliParticleContainer(trackName); } if (partCont) partCont->SetParticlePtCut(minTrPt); AliClusterContainer* clusCont = 0; if (!clusName.IsNull()) { clusCont = new AliClusterContainer(clusName); clusCont->SetClusECut(0.); clusCont->SetClusPtCut(0.); clusCont->SetClusHadCorrEnergyCut(minClPt); clusCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr); } switch (jetType) { case AliJetContainer::kChargedJet: if (partCont) partCont->SetCharge(AliParticleContainer::kCharged); break; case AliJetContainer::kNeutralJet: if (partCont) partCont->SetCharge(AliParticleContainer::kNeutral); break; default: break; } TString name = AliJetContainer::GenerateJetName(jetType, jetAlgo, reco, radius, partCont, clusCont, tag); Printf("Jet task name: %s", name.Data()); AliEmcalJetTask* mgrTask = static_cast<AliEmcalJetTask *>(mgr->GetTask(name.Data())); if (mgrTask) return mgrTask; AliEmcalJetTask* jetTask = new AliEmcalJetTask(name); jetTask->SetJetType(jetType); jetTask->SetJetAlgo(jetAlgo); jetTask->SetRecombScheme(reco); jetTask->SetRadius(radius); if (partCont) jetTask->AdoptParticleContainer(partCont); if (clusCont) jetTask->AdoptClusterContainer(clusCont); jetTask->SetJetsName(tag); jetTask->SetMinJetPt(minJetPt); jetTask->SetGhostArea(ghostArea); if (bFillGhosts) jetTask->SetFillGhost(); if (lockTask) jetTask->SetLocked(); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(jetTask); // Create containers for input/output AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer(); mgr->ConnectInput(jetTask, 0, cinput); TObjArray* cnt = mgr->GetContainers(); return jetTask; } equire only Contains instead of == for matching particle containers Needed in order to identify non-standard particle containers (mcparticles would overwrite the AOD std branch) AliEmcalJetTask* AddTaskEmcalJet( const char *nTracks = "usedefault", const char *nClusters = "usedefault", const AliJetContainer::EJetAlgo_t jetAlgo = AliJetContainer::antikt_algorithm, const Double_t radius = 0.4, const AliJetContainer::EJetType_t jetType = AliJetContainer::kFullJet, const Double_t minTrPt = 0.15, const Double_t minClPt = 0.30, const Double_t ghostArea = 0.005, const AliJetContainer::ERecoScheme_t reco = AliJetContainer::pt_scheme, const char *tag = "Jet", const Double_t minJetPt = 0., const Bool_t lockTask = kTRUE, const Bool_t bFillGhosts = kFALSE ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEmcalJet", "No analysis manager to connect to."); return 0; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== AliVEventHandler* handler = mgr->GetInputEventHandler(); if (!handler) { ::Error("AddTaskEmcalJet", "This task requires an input event handler"); return 0; } enum EDataType_t { kUnknown, kESD, kAOD, kMCgen }; TString trackName(nTracks); TString clusName(nClusters); EDataType_t dataType = kUnknown; if (handler->InheritsFrom("AliESDInputHandler")) { dataType = kESD; } else if (handler->InheritsFrom("AliAODInputHandler")) { dataType = kAOD; } else if (handler->InheritsFrom("AliMCGenHandler")) { dataType = kMCgen; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- if (trackName == "usedefault") { if (dataType == kESD) { trackName = "Tracks"; } else if (dataType == kAOD) { trackName = "tracks"; } else if (dataType == kMCgen) { trackName = "mcparticles"; } } if (clusName == "usedefault") { if (dataType == kESD) { clusName = "CaloClusters"; } else if (dataType == kAOD) { clusName = "caloClusters"; } else { clusName = ""; } } AliParticleContainer* partCont = 0; if (trackName.Contains("mcparticles")) { // must be contains in order to allow for non-standard particle containers AliMCParticleContainer* mcpartCont = new AliMCParticleContainer(trackName); partCont = mcpartCont; } else if (trackName == "tracks" || trackName == "Tracks") { AliTrackContainer* trackCont = new AliTrackContainer(trackName); partCont = trackCont; } else if (!trackName.IsNull()) { partCont = new AliParticleContainer(trackName); } if (partCont) partCont->SetParticlePtCut(minTrPt); AliClusterContainer* clusCont = 0; if (!clusName.IsNull()) { clusCont = new AliClusterContainer(clusName); clusCont->SetClusECut(0.); clusCont->SetClusPtCut(0.); clusCont->SetClusHadCorrEnergyCut(minClPt); clusCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr); } switch (jetType) { case AliJetContainer::kChargedJet: if (partCont) partCont->SetCharge(AliParticleContainer::kCharged); break; case AliJetContainer::kNeutralJet: if (partCont) partCont->SetCharge(AliParticleContainer::kNeutral); break; default: break; } TString name = AliJetContainer::GenerateJetName(jetType, jetAlgo, reco, radius, partCont, clusCont, tag); Printf("Jet task name: %s", name.Data()); AliEmcalJetTask* mgrTask = static_cast<AliEmcalJetTask *>(mgr->GetTask(name.Data())); if (mgrTask) return mgrTask; AliEmcalJetTask* jetTask = new AliEmcalJetTask(name); jetTask->SetJetType(jetType); jetTask->SetJetAlgo(jetAlgo); jetTask->SetRecombScheme(reco); jetTask->SetRadius(radius); if (partCont) jetTask->AdoptParticleContainer(partCont); if (clusCont) jetTask->AdoptClusterContainer(clusCont); jetTask->SetJetsName(tag); jetTask->SetMinJetPt(minJetPt); jetTask->SetGhostArea(ghostArea); if (bFillGhosts) jetTask->SetFillGhost(); if (lockTask) jetTask->SetLocked(); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(jetTask); // Create containers for input/output AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer(); mgr->ConnectInput(jetTask, 0, cinput); TObjArray* cnt = mgr->GetContainers(); return jetTask; }
#include "AliAnalysisTaskSE.h" #include "AliAnalysisManager.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliESDEvent.h" #include "AliHeader.h" #include "AliMultiplicity.h" #include <TParticle.h> #include <TDatabasePDG.h> #include <TH1F.h> #include <TH2F.h> #include <TH3F.h> #include <TChain.h> #include "AliGenerator.h" #include "AliGenCocktailEventHeader.h" #include "AliGenHijingEventHeader.h" #include "AliAnalysisTaskCheckGenKine.h" /************************************************************************** * Copyright(c) 1998-2012, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //************************************************************************* // Implementation of class AliAnalysisTaskCheckGenKine // AliAnalysisTask to check MC production at ESD+Kine level // // // Authors: F. Prino, prino@to.infn.it // //************************************************************************* /// \cond CLASSIMP ClassImp(AliAnalysisTaskCheckGenKine); /// \endcond //______________________________________________________________________________ AliAnalysisTaskCheckGenKine::AliAnalysisTaskCheckGenKine() : AliAnalysisTaskSE("CheckGenKine"), fOutput(0), fHistoNEvents(0), fHistoGenMult(0), fHistoVtxContrib(0), fHistoSPD3DVtxX(0), fHistoSPD3DVtxY(0), fHistoSPD3DVtxZ(0), fHistoSPDZVtxZ(0), fHistoTrkVtxX(0), fHistoTrkVtxY(0), fHistoTrkVtxZ(0), fHistoSPD3DVtxResidX(0), fHistoSPD3DVtxResidY(0), fHistoSPD3DVtxResidZ(0), fHistoSPDZVtxResidZ(0), fHistoTrkVtxResidX(0), fHistoTrkVtxResidY(0), fHistoTrkVtxResidZ(0), fHistoTracklets(0), fHistoSelTracks(0), fHistoGenMultVsb(0), fHistoTrackletsVsb(0), fHistoSelTracksVsb(0), fSpeciesAbundance(0), fIsAA(kFALSE), fNumOfSpeciesToCheck(0) { // fNumOfSpeciesToCheck=0; fPdgCodes[fNumOfSpeciesToCheck++]=11; fPdgCodes[fNumOfSpeciesToCheck++]=-11; fPdgCodes[fNumOfSpeciesToCheck++]=211; fPdgCodes[fNumOfSpeciesToCheck++]=-211; fPdgCodes[fNumOfSpeciesToCheck++]=111; fPdgCodes[fNumOfSpeciesToCheck++]=321; fPdgCodes[fNumOfSpeciesToCheck++]=-321; fPdgCodes[fNumOfSpeciesToCheck++]=310; fPdgCodes[fNumOfSpeciesToCheck++]=130; fPdgCodes[fNumOfSpeciesToCheck++]=2212; fPdgCodes[fNumOfSpeciesToCheck++]=-2212; fPdgCodes[fNumOfSpeciesToCheck++]=3122; fPdgCodes[fNumOfSpeciesToCheck++]=-3122; fPdgCodes[fNumOfSpeciesToCheck++]=3312; fPdgCodes[fNumOfSpeciesToCheck++]=-3312; fPdgCodes[fNumOfSpeciesToCheck++]=3334; fPdgCodes[fNumOfSpeciesToCheck++]=-3334; fPdgCodes[fNumOfSpeciesToCheck++]=421; fPdgCodes[fNumOfSpeciesToCheck++]=-421; fPdgCodes[fNumOfSpeciesToCheck++]=511; fPdgCodes[fNumOfSpeciesToCheck++]=-511; fPdgCodes[fNumOfSpeciesToCheck++]=1000010020; fPdgCodes[fNumOfSpeciesToCheck++]=-1000010020; for(Int_t j=0; j<kMaxNumOfSpeciesToCheck; j++){ fEtaPt[j]=0x0; fPrimSec[j]=0x0; fNumOfDau[j]=0x0; fDecLen[j]=0x0; fMassDiff[j]=0x0; fMomDiff[j]=0x0; fPrimSecb[j]=0x0; } DefineInput(0, TChain::Class()); DefineOutput(1, TList::Class()); } //___________________________________________________________________________ AliAnalysisTaskCheckGenKine::~AliAnalysisTaskCheckGenKine(){ // if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return; if (fOutput) { delete fOutput; fOutput = 0; } } //___________________________________________________________________________ void AliAnalysisTaskCheckGenKine::AddParticleToCheck(Int_t pdg){ // add particle PDG code in the list of species to be checked for(Int_t kp=0; kp<fNumOfSpeciesToCheck; kp++){ if(fPdgCodes[kp]==pdg){ printf("Particle %d already in list of species to be checked\n",pdg); return; } } if(fNumOfSpeciesToCheck<kMaxNumOfSpeciesToCheck) fPdgCodes[fNumOfSpeciesToCheck++]=pdg; else printf("Maximum number of particles species (%d) already reached, won't add %d\n",kMaxNumOfSpeciesToCheck,pdg); return; } //___________________________________________________________________________ void AliAnalysisTaskCheckGenKine::PrintSpeciesToCheck(){ // print the list of particle species that will be checked printf("--- Number of particle species that will be checked = %d\n",fNumOfSpeciesToCheck); for(Int_t kp=0; kp<fNumOfSpeciesToCheck; kp++) printf(" %d) PDGcode=%d\n",kp,fPdgCodes[kp]); return; } //___________________________________________________________________________ void AliAnalysisTaskCheckGenKine::UserCreateOutputObjects() { /// create output histos fOutput = new TList(); fOutput->SetOwner(); fOutput->SetName("OutputHistos"); Double_t minMult=-0.5; Double_t maxMult=99.5; if(fIsAA){ maxMult=5000.; minMult=0.; } fHistoNEvents = new TH1F("hNEvents", "Number of processed events",4,-0.5,3.5); fHistoNEvents->SetMinimum(0); fHistoNEvents->GetXaxis()->SetBinLabel(1,"Analyzed"); fHistoNEvents->GetXaxis()->SetBinLabel(2,"SPD vertex 3D"); fHistoNEvents->GetXaxis()->SetBinLabel(3,"SPD vertex Z"); fHistoNEvents->GetXaxis()->SetBinLabel(4,"Track vertex"); fOutput->Add(fHistoNEvents); fHistoGenMult = new TH1F("hGenMult"," ; Nch (|#eta|<0.9)",100,minMult,maxMult); fOutput->Add(fHistoGenMult); // vertex histos fHistoVtxContrib = new TH3F("kVtxContrib"," ; Nch (|#eta|<0.9) ; SPDVert contrib. ; TrackVert contrib.",100,-0.5,99.5,102,-2.5,99.5,102,-2.5,99.5); fHistoSPD3DVtxX = new TH1F("hSPD3DVtxX"," ; SPD 3Dvertex X (cm)",200,-1.,1.); fHistoSPD3DVtxY = new TH1F("hSPD3DVtxY"," ; SPD 3Dvertex Y (cm)",200,-1.,1.); fHistoSPD3DVtxZ = new TH1F("hSPD3DVtxZ"," ; SPD 3Dvertex Z (cm)",200,-20.,20.); fHistoSPDZVtxZ = new TH1F("hSPDZVtxZ"," ; SPD Zvertex Z (cm)",200,-20.,20.); fHistoTrkVtxX = new TH1F("hTrkVtxX"," ; Track vertex X (cm)",200,-1.,1.); fHistoTrkVtxY = new TH1F("hTrkVtxY"," ; Track vertex Y (cm)",200,-1.,1.); fHistoTrkVtxZ = new TH1F("hTrkVtxZ"," ; Track vertex Z (cm)",200,-20.,20.); fHistoSPD3DVtxResidX = new TH3F("hSPD3DVtxResidX"," ; SPDVert contrib. ; z_{vertex} (cm) ; x_{reco}-x_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoSPD3DVtxResidY = new TH3F("hSPD3DVtxResidY"," ; SPDVert contrib. ; z_{vertex} (cm) ; y_{reco}-y_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoSPD3DVtxResidZ = new TH3F("hSPD3DVtxResidZ"," ; SPDVert contrib. ; z_{vertex} (cm) ; z_{reco}-z_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoSPDZVtxResidZ = new TH3F("hSPDZVtxResidZ"," ; SPDVert contrib. ; z_{vertex} (cm) ; z_{reco}-z_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoTrkVtxResidX = new TH3F("hTrkVtxResidX"," ; SPDVert contrib. ; z_{vertex} (cm) ; x_{reco}-x_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoTrkVtxResidY = new TH3F("hTrkVtxResidY"," ; SPDVert contrib. ; z_{vertex} (cm) ; y_{reco}-y_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoTrkVtxResidZ = new TH3F("hTrkVtxResidZ"," ; SPDVert contrib. ; z_{vertex} (cm) ; z_{reco}-z_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fOutput->Add(fHistoVtxContrib); fOutput->Add(fHistoSPD3DVtxX); fOutput->Add(fHistoSPD3DVtxY); fOutput->Add(fHistoSPD3DVtxZ); fOutput->Add(fHistoSPDZVtxZ); fOutput->Add(fHistoTrkVtxX); fOutput->Add(fHistoTrkVtxY); fOutput->Add(fHistoTrkVtxZ); fOutput->Add(fHistoSPD3DVtxResidX); fOutput->Add(fHistoSPD3DVtxResidY); fOutput->Add(fHistoSPD3DVtxResidZ); fOutput->Add(fHistoSPDZVtxResidZ); fOutput->Add(fHistoTrkVtxResidX); fOutput->Add(fHistoTrkVtxResidY); fOutput->Add(fHistoTrkVtxResidZ); // multiplicity histos fHistoTracklets = new TH2F("hTracklets"," ; N_{gen} ; N_{tracklets}",100,minMult,maxMult,100,minMult,maxMult); fHistoSelTracks = new TH2F("hSelTracks"," ; N_{gen} ; N_{TPC+ITS tracks}",100,minMult,maxMult,100,minMult,maxMult); fOutput->Add(fHistoTracklets); fOutput->Add(fHistoSelTracks); if(fIsAA){ fHistoGenMultVsb = new TH2F("hGenMultVsb"," ; impact parameter (fm) ; Nch (|#eta|<0.9)",150,0.,15.,100,minMult,maxMult); fHistoTrackletsVsb = new TH2F("hTrackletsVsb"," ; impact parameter (fm) ; N_{tracklets}",150,0.,15.,100,minMult,maxMult); fHistoSelTracksVsb = new TH2F("hSelTracksVsb"," ; impact parameter (fm) ; N_{TPC+ITS tracks}",150,0.,15.,100,minMult,maxMult); fOutput->Add(fHistoGenMultVsb); fOutput->Add(fHistoTrackletsVsb); fOutput->Add(fHistoSelTracksVsb); } // per-particle histos fSpeciesAbundance = new TH2F("hSpeciesAbundance","",fNumOfSpeciesToCheck,-0.5,fNumOfSpeciesToCheck-0.5,2,-0.5,1.5); fSpeciesAbundance->GetYaxis()->SetBinLabel(1,"From generator"); fSpeciesAbundance->GetYaxis()->SetBinLabel(2,"From transport"); fOutput->Add(fSpeciesAbundance); for(Int_t j=0; j<fNumOfSpeciesToCheck; j++){ TString pname=TDatabasePDG::Instance()->GetParticle(fPdgCodes[j])->GetName(); fSpeciesAbundance->GetXaxis()->SetBinLabel(j+1,pname.Data()); fEtaPt[j] = new TH2F(TString::Format("hEtaPt%s",pname.Data())," ; #eta ; p_{T} (GeV/c)",20,-10,10,100,0.,20.); fPrimSec[j] = new TH3F(TString::Format("hPrimSec%s",pname.Data())," ; ; p_{T} (GeV/c) ; dist from vert (cm)",4,-0.5,3.5,100,0.,20.,100,0.,100.); fPrimSec[j]->GetXaxis()->SetBinLabel(1,"Primary"); fPrimSec[j]->GetXaxis()->SetBinLabel(2,"Secondary from weak"); fPrimSec[j]->GetXaxis()->SetBinLabel(3,"Secondary from material"); fPrimSec[j]->GetXaxis()->SetBinLabel(4,"Other"); fNumOfDau[j] = new TH2F(TString::Format("hNumOfDau%s",pname.Data())," ; Number of daughters",11,-0.5,10.5,6,-0.5,5.5); fNumOfDau[j]->GetYaxis()->SetBinLabel(1,"From generator, decay generator"); fNumOfDau[j]->GetYaxis()->SetBinLabel(2,"From generator, decay transport"); fNumOfDau[j]->GetYaxis()->SetBinLabel(3,"From generator, interaction transport"); fNumOfDau[j]->GetYaxis()->SetBinLabel(4,"From transport, decay transport"); fNumOfDau[j]->GetYaxis()->SetBinLabel(5,"From transport, interaction transport"); fNumOfDau[j]->GetYaxis()->SetBinLabel(6,"Ohter"); fDecLen[j] = new TH2F(TString::Format("hDecLen%s",pname.Data())," ; p (GeV/c) ; decay length (cm)",100,0.,20.,200,0.,20.); fMassDiff[j] = new TH2F(TString::Format("hMassDiff%s",pname.Data())," ; (M_{mother} - M_{daughters})/ M_{mother}",101,-0.0505,0.0505,3,-0.5,2.5); fMomDiff[j] = new TH2F(TString::Format("hMomDiff%s",pname.Data())," ; (p_{mother} - p_{daughters})/ p_{mother}",101,-0.0505,0.0505,3,-0.5,2.5); fMassDiff[j]->GetYaxis()->SetBinLabel(1,"Decay generator"); fMassDiff[j]->GetYaxis()->SetBinLabel(2,"Decay transport"); fMassDiff[j]->GetYaxis()->SetBinLabel(3,"Interaction transport"); fMomDiff[j]->GetYaxis()->SetBinLabel(1,"Decay generator"); fMomDiff[j]->GetYaxis()->SetBinLabel(2,"Decay transport"); fMomDiff[j]->GetYaxis()->SetBinLabel(3,"Interaction transport"); fOutput->Add(fEtaPt[j]); fOutput->Add(fPrimSec[j]); fOutput->Add(fNumOfDau[j]); fOutput->Add(fDecLen[j]); fOutput->Add(fMassDiff[j]); fOutput->Add(fMomDiff[j]); if(fIsAA){ fPrimSecb[j] = new TH3F(TString::Format("hPrimSecb%s",pname.Data())," ; ; p_{T} (GeV/c) ; impact parameter (fm)",4,-0.5,3.5,100,0.,20.,150,0.,15.); fPrimSecb[j]->GetXaxis()->SetBinLabel(1,"Primary"); fPrimSecb[j]->GetXaxis()->SetBinLabel(2,"Secondary from weak"); fPrimSecb[j]->GetXaxis()->SetBinLabel(3,"Secondary from material"); fPrimSecb[j]->GetXaxis()->SetBinLabel(4,"Other"); fOutput->Add(fPrimSecb[j]); } } PostData(1,fOutput); } //______________________________________________________________________________ void AliAnalysisTaskCheckGenKine::UserExec(Option_t *) { // AliESDEvent *esd = (AliESDEvent*) (InputEvent()); if(!esd) { printf("AliAnalysisTaskCheckGenKine::Exec(): bad ESD\n"); return; } AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); if (!eventHandler) { printf("AliAnalysisTaskCheckGenKine::Exec(): could not retrieve MC event handler"); return; } AliMCEvent* mcEvent = eventHandler->MCEvent(); if (!mcEvent) { Printf("AliAnalysisTaskCheckGenKine::Exec(): could not retrieve MC event"); return; } const AliVVertex* mcVert=mcEvent->GetPrimaryVertex(); if(!mcVert){ Printf("AliAnalysisTaskCheckGenKine::Exec(): generated vertex not available"); return; } Double_t imppar=-999.; TString genname=mcEvent->GenEventHeader()->ClassName(); if(genname.Contains("CocktailEventHeader")){ AliGenCocktailEventHeader *cockhead=(AliGenCocktailEventHeader*)mcEvent->GenEventHeader(); TList* lgen=cockhead->GetHeaders(); for(Int_t ig=0; ig<lgen->GetEntries(); ig++){ AliGenerator* gen=(AliGenerator*)lgen->At(ig); TString title=gen->GetName(); if(title.Contains("hijing") || title.Contains("Hijing")){ AliGenHijingEventHeader* hijh=(AliGenHijingEventHeader*)lgen->At(ig); imppar=hijh->ImpactParameter(); } } }else if(genname.Contains("hijing") || genname.Contains("Hijing")){ AliGenHijingEventHeader* hijh=(AliGenHijingEventHeader*)mcEvent->GenEventHeader(); imppar=hijh->ImpactParameter(); } fHistoNEvents->Fill(0); //vertices const AliESDVertex *spdv=esd->GetPrimaryVertexSPD(); const AliESDVertex *trkv=esd->GetPrimaryVertexTracks(); Int_t nContribSPD=-3; if(spdv) nContribSPD=spdv->GetNContributors(); Int_t nContribTRK=-1; if(trkv) nContribTRK=trkv->GetNContributors(); // generated multiplicities Int_t nParticles=mcEvent->GetNumberOfTracks(); Int_t nChEta09 = 0.; Int_t nPhysPrimEta09=0; Int_t nPiKPEta09=0; for (Int_t i=0;i<nParticles;i++){ TParticle* part = (TParticle*)mcEvent->Particle(i); TParticlePDG* ppdg = part->GetPDG(); Int_t absPdg=TMath::Abs(part->GetPdgCode()); Double_t eta=part->Eta(); if(TMath::Abs(eta)<0.9){ if(mcEvent->IsPhysicalPrimary(i)) nPhysPrimEta09++; if(absPdg==211 || absPdg==321 || absPdg==2212) nPiKPEta09++; if(ppdg && TMath::Abs(ppdg->Charge())>0.) nChEta09++; } } fHistoGenMult->Fill(nChEta09); fHistoVtxContrib->Fill(nPiKPEta09,nContribSPD,nContribTRK); // primary vertex plots if(nContribSPD>=1){ Double_t dx=spdv->GetX()-mcVert->GetX(); Double_t dy=spdv->GetY()-mcVert->GetY(); Double_t dz=spdv->GetZ()-mcVert->GetZ(); if(spdv->IsFromVertexer3D()){ fHistoNEvents->Fill(1); fHistoSPD3DVtxX->Fill(spdv->GetX()); fHistoSPD3DVtxY->Fill(spdv->GetY()); fHistoSPD3DVtxZ->Fill(spdv->GetZ()); fHistoSPD3DVtxResidX->Fill(nContribSPD,mcVert->GetZ(),dx); fHistoSPD3DVtxResidY->Fill(nContribSPD,mcVert->GetZ(),dy); fHistoSPD3DVtxResidZ->Fill(nContribSPD,mcVert->GetZ(),dz); }else if(spdv->IsFromVertexerZ()){ fHistoNEvents->Fill(2); fHistoSPDZVtxZ->Fill(spdv->GetZ()); fHistoSPDZVtxResidZ->Fill(nContribSPD,mcVert->GetZ(),dz); } } if(nContribTRK>=1){ Double_t dx=trkv->GetX()-mcVert->GetX(); Double_t dy=trkv->GetY()-mcVert->GetY(); Double_t dz=trkv->GetZ()-mcVert->GetZ(); fHistoNEvents->Fill(3); fHistoTrkVtxX->Fill(trkv->GetX()); fHistoTrkVtxY->Fill(trkv->GetY()); fHistoTrkVtxZ->Fill(trkv->GetZ()); fHistoTrkVtxResidX->Fill(nContribTRK,mcVert->GetZ(),dx); fHistoTrkVtxResidY->Fill(nContribTRK,mcVert->GetZ(),dy); fHistoTrkVtxResidZ->Fill(nContribTRK,mcVert->GetZ(),dz); } const AliMultiplicity* mult=esd->GetMultiplicity(); Int_t nTracklets=mult->GetNumberOfTracklets(); Int_t nTrackletsEta09=0; for(Int_t it=0; it<nTracklets; it++){ Double_t eta=TMath::Abs(mult->GetEta(it)); if(eta<0.9) nTrackletsEta09++; } fHistoTracklets->Fill(nPiKPEta09,nTrackletsEta09); Int_t nTracks=esd->GetNumberOfTracks(); Int_t nSelTracks=0; for(Int_t it=0; it<nTracks; it++){ AliESDtrack* tr=esd->GetTrack(it); UInt_t status=tr->GetStatus(); if(!(status&AliESDtrack::kITSrefit)) continue; if(!(status&AliESDtrack::kTPCin)) continue; nSelTracks++; } fHistoSelTracks->Fill(nPiKPEta09,nSelTracks); if(fIsAA){ fHistoGenMultVsb->Fill(imppar,nPiKPEta09); fHistoTrackletsVsb->Fill(imppar,nTrackletsEta09); fHistoSelTracksVsb->Fill(imppar,nSelTracks); } for (Int_t i=0;i<nParticles;i++){ AliMCParticle* mcPart=(AliMCParticle*)mcEvent->GetTrack(i); TParticle* part = (TParticle*)mcEvent->Particle(i); if(!mcPart || !part) continue; Int_t pdg=part->GetPdgCode(); Int_t spId=GetSpeciesIndex(pdg); if(spId<0) continue; Double_t pt=part->Pt(); Double_t mom=part->P(); Double_t mass=part->GetMass(); Double_t eta=part->Eta(); Int_t fromGener=1; if(i<mcEvent->GetNumberOfPrimaries()) fromGener=0; fSpeciesAbundance->Fill(spId,fromGener); if(fromGener==0) fEtaPt[spId]->Fill(eta,pt); if(TMath::Abs(eta)>0.8) continue; Double_t distx=part->Vx()-mcVert->GetX(); Double_t disty=part->Vy()-mcVert->GetY(); Double_t distz=part->Vz()-mcVert->GetZ(); Double_t distToVert=TMath::Sqrt(distx*distx+disty*disty+distz*distz); Int_t primSec=3; if(mcEvent->IsPhysicalPrimary(i)) primSec=0; else{ if(mcEvent->IsSecondaryFromWeakDecay(i)) primSec=1; else if(mcEvent->IsSecondaryFromMaterial(i)) primSec=2; } fPrimSec[spId]->Fill(primSec,pt,distToVert); if(fIsAA) fPrimSecb[spId]->Fill(primSec,pt,imppar); Int_t nDau=mcPart->GetNDaughters(); Int_t iDau=mcPart->GetDaughterFirst(); if(iDau>=0){ TParticle* firstDau = (TParticle*)mcEvent->Particle(iDau); Int_t yVal=5; Int_t dauOrig=-1; if(iDau<mcEvent->GetNumberOfPrimaries()){ // produced by generator, decayed by generator dauOrig=0; } Int_t process=firstDau->GetUniqueID(); if(process==4) dauOrig=1; //decay else if(process>=13) dauOrig=2; //hadronic interaction if(dauOrig>=0){ if(fromGener==0) yVal=dauOrig; else if(fromGener==1 && dauOrig>=1) yVal=dauOrig+2; } fNumOfDau[spId]->Fill(nDau,yVal); Double_t dxDau=firstDau->Vx()-part->Vx(); Double_t dyDau=firstDau->Vy()-part->Vy(); Double_t dzDau=firstDau->Vz()-part->Vz(); Double_t decLen=TMath::Sqrt(dxDau*dxDau+dyDau*dyDau+dzDau*dzDau); Double_t sumPxDau=0.; Double_t sumPyDau=0.; Double_t sumPzDau=0.; Double_t sumEDau=0.; for(Int_t j=0; j<nDau; j++){ TParticle* partDau = (TParticle*)mcEvent->Particle(iDau+j); if(partDau){ sumPxDau+=partDau->Px(); sumPyDau+=partDau->Py(); sumPzDau+=partDau->Pz(); sumEDau+=partDau->Energy(); } } Double_t pSquareDau=sumPxDau*sumPxDau+sumPyDau*sumPyDau+sumPzDau*sumPzDau; Double_t pDau=TMath::Sqrt(pSquareDau); Double_t pDiff=(mom-pDau)/mom; fMomDiff[spId]->Fill(pDiff,dauOrig); Double_t invMass2=sumEDau*sumEDau-pSquareDau; if(invMass2>=0){ Double_t invMass=TMath::Sqrt(sumEDau*sumEDau-pSquareDau); Double_t mDiff=(mass-invMass)/mass; fMassDiff[spId]->Fill(mDiff,dauOrig); } if(primSec==0) fDecLen[spId]->Fill(mom,decLen); } } PostData(1,fOutput); } //______________________________________________________________________________ void AliAnalysisTaskCheckGenKine::Terminate(Option_t */*option*/) { /// Terminate analysis fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { printf("ERROR: fOutput not available\n"); return; } return; } Improved counters of generated particles #include "AliAnalysisTaskSE.h" #include "AliAnalysisManager.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliESDEvent.h" #include "AliHeader.h" #include "AliMultiplicity.h" #include <TParticle.h> #include <TDatabasePDG.h> #include <TH1F.h> #include <TH2F.h> #include <TH3F.h> #include <TChain.h> #include "AliGenerator.h" #include "AliGenCocktailEventHeader.h" #include "AliGenHijingEventHeader.h" #include "AliAnalysisTaskCheckGenKine.h" /************************************************************************** * Copyright(c) 1998-2012, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //************************************************************************* // Implementation of class AliAnalysisTaskCheckGenKine // AliAnalysisTask to check MC production at ESD+Kine level // // // Authors: F. Prino, prino@to.infn.it // //************************************************************************* /// \cond CLASSIMP ClassImp(AliAnalysisTaskCheckGenKine); /// \endcond //______________________________________________________________________________ AliAnalysisTaskCheckGenKine::AliAnalysisTaskCheckGenKine() : AliAnalysisTaskSE("CheckGenKine"), fOutput(0), fHistoNEvents(0), fHistoGenMult(0), fHistoVtxContrib(0), fHistoSPD3DVtxX(0), fHistoSPD3DVtxY(0), fHistoSPD3DVtxZ(0), fHistoSPDZVtxZ(0), fHistoTrkVtxX(0), fHistoTrkVtxY(0), fHistoTrkVtxZ(0), fHistoSPD3DVtxResidX(0), fHistoSPD3DVtxResidY(0), fHistoSPD3DVtxResidZ(0), fHistoSPDZVtxResidZ(0), fHistoTrkVtxResidX(0), fHistoTrkVtxResidY(0), fHistoTrkVtxResidZ(0), fHistoTracklets(0), fHistoSelTracks(0), fHistoGenMultVsb(0), fHistoTrackletsVsb(0), fHistoSelTracksVsb(0), fSpeciesAbundance(0), fIsAA(kFALSE), fNumOfSpeciesToCheck(0) { // fNumOfSpeciesToCheck=0; fPdgCodes[fNumOfSpeciesToCheck++]=11; fPdgCodes[fNumOfSpeciesToCheck++]=-11; fPdgCodes[fNumOfSpeciesToCheck++]=211; fPdgCodes[fNumOfSpeciesToCheck++]=-211; fPdgCodes[fNumOfSpeciesToCheck++]=111; fPdgCodes[fNumOfSpeciesToCheck++]=321; fPdgCodes[fNumOfSpeciesToCheck++]=-321; fPdgCodes[fNumOfSpeciesToCheck++]=310; fPdgCodes[fNumOfSpeciesToCheck++]=130; fPdgCodes[fNumOfSpeciesToCheck++]=2212; fPdgCodes[fNumOfSpeciesToCheck++]=-2212; fPdgCodes[fNumOfSpeciesToCheck++]=3122; fPdgCodes[fNumOfSpeciesToCheck++]=-3122; fPdgCodes[fNumOfSpeciesToCheck++]=3312; fPdgCodes[fNumOfSpeciesToCheck++]=-3312; fPdgCodes[fNumOfSpeciesToCheck++]=3334; fPdgCodes[fNumOfSpeciesToCheck++]=-3334; fPdgCodes[fNumOfSpeciesToCheck++]=421; fPdgCodes[fNumOfSpeciesToCheck++]=-421; fPdgCodes[fNumOfSpeciesToCheck++]=511; fPdgCodes[fNumOfSpeciesToCheck++]=-511; fPdgCodes[fNumOfSpeciesToCheck++]=1000010020; fPdgCodes[fNumOfSpeciesToCheck++]=-1000010020; for(Int_t j=0; j<kMaxNumOfSpeciesToCheck; j++){ fEtaPt[j]=0x0; fPrimSec[j]=0x0; fNumOfDau[j]=0x0; fDecLen[j]=0x0; fMassDiff[j]=0x0; fMomDiff[j]=0x0; fPrimSecb[j]=0x0; } DefineInput(0, TChain::Class()); DefineOutput(1, TList::Class()); } //___________________________________________________________________________ AliAnalysisTaskCheckGenKine::~AliAnalysisTaskCheckGenKine(){ // if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return; if (fOutput) { delete fOutput; fOutput = 0; } } //___________________________________________________________________________ void AliAnalysisTaskCheckGenKine::AddParticleToCheck(Int_t pdg){ // add particle PDG code in the list of species to be checked for(Int_t kp=0; kp<fNumOfSpeciesToCheck; kp++){ if(fPdgCodes[kp]==pdg){ printf("Particle %d already in list of species to be checked\n",pdg); return; } } if(fNumOfSpeciesToCheck<kMaxNumOfSpeciesToCheck) fPdgCodes[fNumOfSpeciesToCheck++]=pdg; else printf("Maximum number of particles species (%d) already reached, won't add %d\n",kMaxNumOfSpeciesToCheck,pdg); return; } //___________________________________________________________________________ void AliAnalysisTaskCheckGenKine::PrintSpeciesToCheck(){ // print the list of particle species that will be checked printf("--- Number of particle species that will be checked = %d\n",fNumOfSpeciesToCheck); for(Int_t kp=0; kp<fNumOfSpeciesToCheck; kp++) printf(" %d) PDGcode=%d\n",kp,fPdgCodes[kp]); return; } //___________________________________________________________________________ void AliAnalysisTaskCheckGenKine::UserCreateOutputObjects() { /// create output histos fOutput = new TList(); fOutput->SetOwner(); fOutput->SetName("OutputHistos"); Double_t minMult=-0.5; Double_t maxMult=99.5; if(fIsAA){ maxMult=5000.; minMult=0.; } fHistoNEvents = new TH1F("hNEvents", "Number of processed events",4,-0.5,3.5); fHistoNEvents->SetMinimum(0); fHistoNEvents->GetXaxis()->SetBinLabel(1,"Analyzed"); fHistoNEvents->GetXaxis()->SetBinLabel(2,"SPD vertex 3D"); fHistoNEvents->GetXaxis()->SetBinLabel(3,"SPD vertex Z"); fHistoNEvents->GetXaxis()->SetBinLabel(4,"Track vertex"); fOutput->Add(fHistoNEvents); fHistoGenMult = new TH1F("hGenMult"," ; N_{gen} (charged, |#eta|<0.9)",100,minMult,5.*maxMult); fOutput->Add(fHistoGenMult); // vertex histos fHistoVtxContrib = new TH3F("kVtxContrib"," ; Nch (pi,K,p |#eta|<0.9) ; SPDVert contrib. ; TrackVert contrib.",100,-0.5,99.5,102,-2.5,99.5,102,-2.5,99.5); fHistoSPD3DVtxX = new TH1F("hSPD3DVtxX"," ; SPD 3Dvertex X (cm)",200,-1.,1.); fHistoSPD3DVtxY = new TH1F("hSPD3DVtxY"," ; SPD 3Dvertex Y (cm)",200,-1.,1.); fHistoSPD3DVtxZ = new TH1F("hSPD3DVtxZ"," ; SPD 3Dvertex Z (cm)",200,-20.,20.); fHistoSPDZVtxZ = new TH1F("hSPDZVtxZ"," ; SPD Zvertex Z (cm)",200,-20.,20.); fHistoTrkVtxX = new TH1F("hTrkVtxX"," ; Track vertex X (cm)",200,-1.,1.); fHistoTrkVtxY = new TH1F("hTrkVtxY"," ; Track vertex Y (cm)",200,-1.,1.); fHistoTrkVtxZ = new TH1F("hTrkVtxZ"," ; Track vertex Z (cm)",200,-20.,20.); fHistoSPD3DVtxResidX = new TH3F("hSPD3DVtxResidX"," ; SPDVert contrib. ; z_{vertex} (cm) ; x_{reco}-x_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoSPD3DVtxResidY = new TH3F("hSPD3DVtxResidY"," ; SPDVert contrib. ; z_{vertex} (cm) ; y_{reco}-y_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoSPD3DVtxResidZ = new TH3F("hSPD3DVtxResidZ"," ; SPDVert contrib. ; z_{vertex} (cm) ; z_{reco}-z_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoSPDZVtxResidZ = new TH3F("hSPDZVtxResidZ"," ; SPDVert contrib. ; z_{vertex} (cm) ; z_{reco}-z_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoTrkVtxResidX = new TH3F("hTrkVtxResidX"," ; SPDVert contrib. ; z_{vertex} (cm) ; x_{reco}-x_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoTrkVtxResidY = new TH3F("hTrkVtxResidY"," ; SPDVert contrib. ; z_{vertex} (cm) ; y_{reco}-y_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fHistoTrkVtxResidZ = new TH3F("hTrkVtxResidZ"," ; SPDVert contrib. ; z_{vertex} (cm) ; z_{reco}-z_{gen} (cm)",100,minMult,maxMult,40,-20.,20.,100,-0.1,0.1); fOutput->Add(fHistoVtxContrib); fOutput->Add(fHistoSPD3DVtxX); fOutput->Add(fHistoSPD3DVtxY); fOutput->Add(fHistoSPD3DVtxZ); fOutput->Add(fHistoSPDZVtxZ); fOutput->Add(fHistoTrkVtxX); fOutput->Add(fHistoTrkVtxY); fOutput->Add(fHistoTrkVtxZ); fOutput->Add(fHistoSPD3DVtxResidX); fOutput->Add(fHistoSPD3DVtxResidY); fOutput->Add(fHistoSPD3DVtxResidZ); fOutput->Add(fHistoSPDZVtxResidZ); fOutput->Add(fHistoTrkVtxResidX); fOutput->Add(fHistoTrkVtxResidY); fOutput->Add(fHistoTrkVtxResidZ); // multiplicity histos fHistoTracklets = new TH2F("hTracklets"," ; N_{gen} (phys prim, |#eta|<0.9) ; N_{tracklets}",100,minMult,maxMult,100,minMult,maxMult); fHistoSelTracks = new TH2F("hSelTracks"," ; N_{gen} (phys prim, |#eta|<0.9) ; N_{TPC+ITS tracks}",100,minMult,maxMult,100,minMult,maxMult); fOutput->Add(fHistoTracklets); fOutput->Add(fHistoSelTracks); if(fIsAA){ fHistoGenMultVsb = new TH2F("hGenMultVsb"," ; impact parameter (fm) ; N_{gen} (phys prim, |#eta|<0.9)",150,0.,15.,100,minMult,maxMult); fHistoTrackletsVsb = new TH2F("hTrackletsVsb"," ; impact parameter (fm) ; N_{tracklets}",150,0.,15.,100,minMult,maxMult); fHistoSelTracksVsb = new TH2F("hSelTracksVsb"," ; impact parameter (fm) ; N_{TPC+ITS tracks}",150,0.,15.,100,minMult,maxMult); fOutput->Add(fHistoGenMultVsb); fOutput->Add(fHistoTrackletsVsb); fOutput->Add(fHistoSelTracksVsb); } // per-particle histos fSpeciesAbundance = new TH2F("hSpeciesAbundance","",fNumOfSpeciesToCheck,-0.5,fNumOfSpeciesToCheck-0.5,2,-0.5,1.5); fSpeciesAbundance->GetYaxis()->SetBinLabel(1,"From generator"); fSpeciesAbundance->GetYaxis()->SetBinLabel(2,"From transport"); fOutput->Add(fSpeciesAbundance); for(Int_t j=0; j<fNumOfSpeciesToCheck; j++){ TString pname=TDatabasePDG::Instance()->GetParticle(fPdgCodes[j])->GetName(); fSpeciesAbundance->GetXaxis()->SetBinLabel(j+1,pname.Data()); fEtaPt[j] = new TH2F(TString::Format("hEtaPt%s",pname.Data())," ; #eta ; p_{T} (GeV/c)",20,-10,10,100,0.,20.); fPrimSec[j] = new TH3F(TString::Format("hPrimSec%s",pname.Data())," ; ; p_{T} (GeV/c) ; dist from vert (cm)",4,-0.5,3.5,100,0.,20.,100,0.,100.); fPrimSec[j]->GetXaxis()->SetBinLabel(1,"Primary"); fPrimSec[j]->GetXaxis()->SetBinLabel(2,"Secondary from weak"); fPrimSec[j]->GetXaxis()->SetBinLabel(3,"Secondary from material"); fPrimSec[j]->GetXaxis()->SetBinLabel(4,"Other"); fNumOfDau[j] = new TH2F(TString::Format("hNumOfDau%s",pname.Data())," ; Number of daughters",11,-0.5,10.5,6,-0.5,5.5); fNumOfDau[j]->GetYaxis()->SetBinLabel(1,"From generator, decay generator"); fNumOfDau[j]->GetYaxis()->SetBinLabel(2,"From generator, decay transport"); fNumOfDau[j]->GetYaxis()->SetBinLabel(3,"From generator, interaction transport"); fNumOfDau[j]->GetYaxis()->SetBinLabel(4,"From transport, decay transport"); fNumOfDau[j]->GetYaxis()->SetBinLabel(5,"From transport, interaction transport"); fNumOfDau[j]->GetYaxis()->SetBinLabel(6,"Ohter"); fDecLen[j] = new TH2F(TString::Format("hDecLen%s",pname.Data())," ; p (GeV/c) ; decay length (cm)",100,0.,20.,200,0.,20.); fMassDiff[j] = new TH2F(TString::Format("hMassDiff%s",pname.Data())," ; (M_{mother} - M_{daughters})/ M_{mother}",101,-0.0505,0.0505,3,-0.5,2.5); fMomDiff[j] = new TH2F(TString::Format("hMomDiff%s",pname.Data())," ; (p_{mother} - p_{daughters})/ p_{mother}",101,-0.0505,0.0505,3,-0.5,2.5); fMassDiff[j]->GetYaxis()->SetBinLabel(1,"Decay generator"); fMassDiff[j]->GetYaxis()->SetBinLabel(2,"Decay transport"); fMassDiff[j]->GetYaxis()->SetBinLabel(3,"Interaction transport"); fMomDiff[j]->GetYaxis()->SetBinLabel(1,"Decay generator"); fMomDiff[j]->GetYaxis()->SetBinLabel(2,"Decay transport"); fMomDiff[j]->GetYaxis()->SetBinLabel(3,"Interaction transport"); fOutput->Add(fEtaPt[j]); fOutput->Add(fPrimSec[j]); fOutput->Add(fNumOfDau[j]); fOutput->Add(fDecLen[j]); fOutput->Add(fMassDiff[j]); fOutput->Add(fMomDiff[j]); if(fIsAA){ fPrimSecb[j] = new TH3F(TString::Format("hPrimSecb%s",pname.Data())," ; ; p_{T} (GeV/c) ; impact parameter (fm)",4,-0.5,3.5,100,0.,20.,150,0.,15.); fPrimSecb[j]->GetXaxis()->SetBinLabel(1,"Primary"); fPrimSecb[j]->GetXaxis()->SetBinLabel(2,"Secondary from weak"); fPrimSecb[j]->GetXaxis()->SetBinLabel(3,"Secondary from material"); fPrimSecb[j]->GetXaxis()->SetBinLabel(4,"Other"); fOutput->Add(fPrimSecb[j]); } } PostData(1,fOutput); } //______________________________________________________________________________ void AliAnalysisTaskCheckGenKine::UserExec(Option_t *) { // AliESDEvent *esd = (AliESDEvent*) (InputEvent()); if(!esd) { printf("AliAnalysisTaskCheckGenKine::Exec(): bad ESD\n"); return; } AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); if (!eventHandler) { printf("AliAnalysisTaskCheckGenKine::Exec(): could not retrieve MC event handler"); return; } AliMCEvent* mcEvent = eventHandler->MCEvent(); if (!mcEvent) { Printf("AliAnalysisTaskCheckGenKine::Exec(): could not retrieve MC event"); return; } const AliVVertex* mcVert=mcEvent->GetPrimaryVertex(); if(!mcVert){ Printf("AliAnalysisTaskCheckGenKine::Exec(): generated vertex not available"); return; } Double_t imppar=-999.; TString genname=mcEvent->GenEventHeader()->ClassName(); if(genname.Contains("CocktailEventHeader")){ AliGenCocktailEventHeader *cockhead=(AliGenCocktailEventHeader*)mcEvent->GenEventHeader(); TList* lgen=cockhead->GetHeaders(); for(Int_t ig=0; ig<lgen->GetEntries(); ig++){ AliGenerator* gen=(AliGenerator*)lgen->At(ig); TString title=gen->GetName(); if(title.Contains("hijing") || title.Contains("Hijing")){ AliGenHijingEventHeader* hijh=(AliGenHijingEventHeader*)lgen->At(ig); imppar=hijh->ImpactParameter(); } } }else if(genname.Contains("hijing") || genname.Contains("Hijing")){ AliGenHijingEventHeader* hijh=(AliGenHijingEventHeader*)mcEvent->GenEventHeader(); imppar=hijh->ImpactParameter(); } fHistoNEvents->Fill(0); //vertices const AliESDVertex *spdv=esd->GetPrimaryVertexSPD(); const AliESDVertex *trkv=esd->GetPrimaryVertexTracks(); Int_t nContribSPD=-3; if(spdv) nContribSPD=spdv->GetNContributors(); Int_t nContribTRK=-1; if(trkv) nContribTRK=trkv->GetNContributors(); // generated multiplicities Int_t nParticles=mcEvent->GetNumberOfTracks(); Int_t nChEta09 = 0.; Int_t nPhysPrimEta09=0; Int_t nChPhysPrimEta09=0; Int_t nPiKPEta09=0; for (Int_t i=0;i<nParticles;i++){ TParticle* part = (TParticle*)mcEvent->Particle(i); TParticlePDG* ppdg = part->GetPDG(); Int_t absPdg=TMath::Abs(part->GetPdgCode()); Double_t eta=part->Eta(); if(TMath::Abs(eta)<0.9){ if(mcEvent->IsPhysicalPrimary(i)){ nPhysPrimEta09++; if(ppdg && TMath::Abs(ppdg->Charge())>0.) nChPhysPrimEta09++; } if(absPdg==211 || absPdg==321 || absPdg==2212) nPiKPEta09++; if(ppdg && TMath::Abs(ppdg->Charge())>0.) nChEta09++; } } fHistoGenMult->Fill(nChEta09); fHistoVtxContrib->Fill(nPiKPEta09,nContribSPD,nContribTRK); // primary vertex plots if(nContribSPD>=1){ Double_t dx=spdv->GetX()-mcVert->GetX(); Double_t dy=spdv->GetY()-mcVert->GetY(); Double_t dz=spdv->GetZ()-mcVert->GetZ(); if(spdv->IsFromVertexer3D()){ fHistoNEvents->Fill(1); fHistoSPD3DVtxX->Fill(spdv->GetX()); fHistoSPD3DVtxY->Fill(spdv->GetY()); fHistoSPD3DVtxZ->Fill(spdv->GetZ()); fHistoSPD3DVtxResidX->Fill(nContribSPD,mcVert->GetZ(),dx); fHistoSPD3DVtxResidY->Fill(nContribSPD,mcVert->GetZ(),dy); fHistoSPD3DVtxResidZ->Fill(nContribSPD,mcVert->GetZ(),dz); }else if(spdv->IsFromVertexerZ()){ fHistoNEvents->Fill(2); fHistoSPDZVtxZ->Fill(spdv->GetZ()); fHistoSPDZVtxResidZ->Fill(nContribSPD,mcVert->GetZ(),dz); } } if(nContribTRK>=1){ Double_t dx=trkv->GetX()-mcVert->GetX(); Double_t dy=trkv->GetY()-mcVert->GetY(); Double_t dz=trkv->GetZ()-mcVert->GetZ(); fHistoNEvents->Fill(3); fHistoTrkVtxX->Fill(trkv->GetX()); fHistoTrkVtxY->Fill(trkv->GetY()); fHistoTrkVtxZ->Fill(trkv->GetZ()); fHistoTrkVtxResidX->Fill(nContribTRK,mcVert->GetZ(),dx); fHistoTrkVtxResidY->Fill(nContribTRK,mcVert->GetZ(),dy); fHistoTrkVtxResidZ->Fill(nContribTRK,mcVert->GetZ(),dz); } const AliMultiplicity* mult=esd->GetMultiplicity(); Int_t nTracklets=mult->GetNumberOfTracklets(); Int_t nTrackletsEta09=0; for(Int_t it=0; it<nTracklets; it++){ Double_t eta=TMath::Abs(mult->GetEta(it)); if(eta<0.9) nTrackletsEta09++; } fHistoTracklets->Fill(nChPhysPrimEta09,nTrackletsEta09); Int_t nTracks=esd->GetNumberOfTracks(); Int_t nSelTracks=0; for(Int_t it=0; it<nTracks; it++){ AliESDtrack* tr=esd->GetTrack(it); UInt_t status=tr->GetStatus(); if(!(status&AliESDtrack::kITSrefit)) continue; if(!(status&AliESDtrack::kTPCin)) continue; nSelTracks++; } fHistoSelTracks->Fill(nChPhysPrimEta09,nSelTracks); if(fIsAA){ fHistoGenMultVsb->Fill(imppar,nChPhysPrimEta09); fHistoTrackletsVsb->Fill(imppar,nTrackletsEta09); fHistoSelTracksVsb->Fill(imppar,nSelTracks); } for (Int_t i=0;i<nParticles;i++){ AliMCParticle* mcPart=(AliMCParticle*)mcEvent->GetTrack(i); TParticle* part = (TParticle*)mcEvent->Particle(i); if(!mcPart || !part) continue; Int_t pdg=part->GetPdgCode(); Int_t spId=GetSpeciesIndex(pdg); if(spId<0) continue; Double_t pt=part->Pt(); Double_t mom=part->P(); Double_t mass=part->GetMass(); Double_t eta=part->Eta(); Int_t fromGener=1; if(i<mcEvent->GetNumberOfPrimaries()) fromGener=0; fSpeciesAbundance->Fill(spId,fromGener); if(fromGener==0) fEtaPt[spId]->Fill(eta,pt); if(TMath::Abs(eta)>0.8) continue; Double_t distx=part->Vx()-mcVert->GetX(); Double_t disty=part->Vy()-mcVert->GetY(); Double_t distz=part->Vz()-mcVert->GetZ(); Double_t distToVert=TMath::Sqrt(distx*distx+disty*disty+distz*distz); Int_t primSec=3; if(mcEvent->IsPhysicalPrimary(i)) primSec=0; else{ if(mcEvent->IsSecondaryFromWeakDecay(i)) primSec=1; else if(mcEvent->IsSecondaryFromMaterial(i)) primSec=2; } fPrimSec[spId]->Fill(primSec,pt,distToVert); if(fIsAA) fPrimSecb[spId]->Fill(primSec,pt,imppar); Int_t nDau=mcPart->GetNDaughters(); Int_t iDau=mcPart->GetDaughterFirst(); if(iDau>=0){ TParticle* firstDau = (TParticle*)mcEvent->Particle(iDau); Int_t yVal=5; Int_t dauOrig=-1; if(iDau<mcEvent->GetNumberOfPrimaries()){ // produced by generator, decayed by generator dauOrig=0; } Int_t process=firstDau->GetUniqueID(); if(process==4) dauOrig=1; //decay else if(process>=13) dauOrig=2; //hadronic interaction if(dauOrig>=0){ if(fromGener==0) yVal=dauOrig; else if(fromGener==1 && dauOrig>=1) yVal=dauOrig+2; } fNumOfDau[spId]->Fill(nDau,yVal); Double_t dxDau=firstDau->Vx()-part->Vx(); Double_t dyDau=firstDau->Vy()-part->Vy(); Double_t dzDau=firstDau->Vz()-part->Vz(); Double_t decLen=TMath::Sqrt(dxDau*dxDau+dyDau*dyDau+dzDau*dzDau); Double_t sumPxDau=0.; Double_t sumPyDau=0.; Double_t sumPzDau=0.; Double_t sumEDau=0.; for(Int_t j=0; j<nDau; j++){ TParticle* partDau = (TParticle*)mcEvent->Particle(iDau+j); if(partDau){ sumPxDau+=partDau->Px(); sumPyDau+=partDau->Py(); sumPzDau+=partDau->Pz(); sumEDau+=partDau->Energy(); } } Double_t pSquareDau=sumPxDau*sumPxDau+sumPyDau*sumPyDau+sumPzDau*sumPzDau; Double_t pDau=TMath::Sqrt(pSquareDau); Double_t pDiff=(mom-pDau)/mom; fMomDiff[spId]->Fill(pDiff,dauOrig); Double_t invMass2=sumEDau*sumEDau-pSquareDau; if(invMass2>=0){ Double_t invMass=TMath::Sqrt(sumEDau*sumEDau-pSquareDau); Double_t mDiff=(mass-invMass)/mass; fMassDiff[spId]->Fill(mDiff,dauOrig); } if(primSec==0) fDecLen[spId]->Fill(mom,decLen); } } PostData(1,fOutput); } //______________________________________________________________________________ void AliAnalysisTaskCheckGenKine::Terminate(Option_t */*option*/) { /// Terminate analysis fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { printf("ERROR: fOutput not available\n"); return; } return; }
#include "CameraBase.h" #include "sys/SysControl.h" #include "HMDWrapper.h" using namespace MathLib; #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO #define CAMERA_BASE_CLAMP 89.9f CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR) { m_nFlush = 0; m_vPosition = Vec3_zero; m_fPhiAngle = 0.0f; m_fThetaAngle = 0.0f; m_pLastPlayer = NULL; m_nEnabelMouse = 1; SetRadius(1.0f); SetMinThetaAngle(-90.0f); SetMaxThetaAngle(90.0f); SetTurning(90.0f); SetViewDirection(vec3(0.0f,1.0f,0.0f)); SetEnabled(0); SetHMDEnabled(1); } CCameraBase::~CCameraBase() { Leave(); } void CCameraBase::SetEnabled(int nEnable) { if(nEnable) { m_pLastPlayer = g_Engine.pGame->GetPlayer(); CPlayer::SetEnabled(nEnable); g_Engine.pGame->SetPlayer(this); } else { if (m_pLastPlayer) { g_Engine.pGame->SetPlayer(m_pLastPlayer); CPlayer::SetEnabled(nEnable); } } } int CCameraBase::IsEnabled() const { return CPlayer::IsEnabled(); } void CCameraBase::SetHMDEnabled(int nEnable) { m_nHMDEnable = nEnable; } int CCameraBase::IsHMDEnabled() const { return m_nHMDEnable; } void CCameraBase::SetRadius(float r) { m_fRadius = r; } float CCameraBase::GetRadius() const { return m_fRadius; } /******************************************************************************\ * * Parameters * \******************************************************************************/ /* */ Signed-off-by: mrlitong <litongtongxue@gmail.com> #include "CameraBase.h" #include "sys/SysControl.h" #include "HMDWrapper.h" #include "Engine.h" #include "Game.h" using namespace MathLib; #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO #define CAMERA_BASE_CLAMP 89.9f CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR) { m_nFlush = 0; m_vPosition = Vec3_zero; m_fPhiAngle = 0.0f; m_fThetaAngle = 0.0f; m_pLastPlayer = NULL; m_nEnabelMouse = 1; SetRadius(1.0f); SetMinThetaAngle(-90.0f); SetMaxThetaAngle(90.0f); SetTurning(90.0f); SetViewDirection(vec3(0.0f,1.0f,0.0f)); SetEnabled(0); SetHMDEnabled(1); } CCameraBase::~CCameraBase() { Leave(); } void CCameraBase::SetEnabled(int nEnable) { if(nEnable) { m_pLastPlayer = g_Engine.pGame->GetPlayer(); CPlayer::SetEnabled(nEnable); g_Engine.pGame->SetPlayer(this); } else { if (m_pLastPlayer) { g_Engine.pGame->SetPlayer(m_pLastPlayer); CPlayer::SetEnabled(nEnable); } } } int CCameraBase::IsEnabled() const { return CPlayer::IsEnabled(); } void CCameraBase::SetHMDEnabled(int nEnable) { m_nHMDEnable = nEnable; } int CCameraBase::IsHMDEnabled() const { return m_nHMDEnable; } void CCameraBase::SetRadius(float r) { m_fRadius = r; } float CCameraBase::GetRadius() const { return m_fRadius; } /******************************************************************************\ * * Parameters * \******************************************************************************/ /* */
// ------------------------------------------------------------------- // // hot_backup_test.cc // // Copyright (c) 2016 Basho Technologies, Inc. All Rights Reserved. // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // ------------------------------------------------------------------- #include <fcntl.h> #include <libgen.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "util/testharness.h" #include "util/testutil.h" #include "db/dbformat.h" #include "db/db_impl.h" #include "util/hot_backup.h" /** * Execution routine */ int main(int argc, char** argv) { int ret_val; ret_val=leveldb::test::RunAllTests(); return(ret_val); } // main namespace leveldb { /** * Wrapper class for tests. Holds working variables * and helper functions. */ class HotBackupTester : public HotBackup { public: std::string m_DBName; std::string m_Trigger; HotBackupTester() { m_DBName = test::TmpDir() + "/hot_backup"; m_Trigger = test::TmpDir() + "/trigger"; }; ~HotBackupTester() { }; virtual const char * GetTriggerPath() {return(m_Trigger.c_str());}; }; // class HotBackupTester /** * Initial code used the existance of /etc/riak/hot_backup file * as flag to start a backup. */ TEST(HotBackupTester, FileTriggerTest) { char * dup_path, *path; int ret_val; bool ret_flag; uint64_t perf_before, perf_after; perf_before=gPerfCounters->Value(ePerfSyslogWrite); // cleanup anything existing, likely fails /// hmm, should there be a way to move this trigger /// to a "safe" area like /tmp? unlink(GetTriggerPath()); // does parent path exist? // bypass test if it does not ... Travis CI and // other users might not be able to access /etc/riak dup_path=strdup(GetTriggerPath()); path=dirname(dup_path); ret_val=access(path, R_OK | W_OK); ASSERT_TRUE(-1!=ret_val); // is a trigger seen (hope not) ret_flag=HotBackup::IsTriggerSet(); ASSERT_TRUE(!ret_flag); // make a trigger ret_val=open(GetTriggerPath(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ASSERT_TRUE(-1!=ret_val); close(ret_val); // test the trigger ret_flag=HotBackup::IsTriggerSet(); ASSERT_TRUE(ret_flag); // pretend to be back process /// schedule twice HotBackup::HotBackupScheduled(); HotBackup::HotBackupScheduled(); // trigger still there? ret_flag=HotBackup::IsTriggerSet(); ASSERT_TRUE(ret_flag); // release one, trigger goes away HotBackup::HotBackupFinished(); ret_flag=HotBackup::IsTriggerSet(); ASSERT_TRUE(!ret_flag); // did our simulation create a syslog entry? // (bonus if you manually check /var/log/syslog for actual entries) perf_after=gPerfCounters->Value(ePerfSyslogWrite) - perf_before; ASSERT_TRUE( 1==perf_after ); // clean up second count. HotBackup::HotBackupFinished(); free(dup_path); dup_path=NULL; } // FileTriggerTest } // namespace leveldb add DirectoryRotationTest // ------------------------------------------------------------------- // // hot_backup_test.cc // // Copyright (c) 2016 Basho Technologies, Inc. All Rights Reserved. // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // ------------------------------------------------------------------- #include <fcntl.h> #include <libgen.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "leveldb/db.h" #include "util/testharness.h" #include "util/testutil.h" #include "db/dbformat.h" #include "db/db_impl.h" #include "db/filename.h" #include "util/hot_backup.h" /** * Execution routine */ int main(int argc, char** argv) { int ret_val; ret_val=leveldb::test::RunAllTests(); return(ret_val); } // main namespace leveldb { /** * Wrapper class for tests. Holds working variables * and helper functions. */ class HotBackupTester : public HotBackup { public: std::string m_DBName; std::string m_Trigger; HotBackupTester() { m_DBName = test::TmpDir() + "/hot_backup"; m_Trigger = test::TmpDir() + "/trigger"; }; ~HotBackupTester() { }; virtual const char * GetTriggerPath() {return(m_Trigger.c_str());}; void ClearAllBackups( Options & InOptions) { int loop; Options options; // clear old if exists for (loop=0; loop<=config::kNumBackups; ++loop) { options=InOptions; SetBackupPaths(options, loop); DestroyDB("", options); } // if options.tiered_slow_level=4; options.tiered_fast_prefix=m_DBName + "/fast"; options.tiered_slow_prefix=m_DBName + "/slow"; DestroyDB("", options); } // ClearAllBackups }; // class HotBackupTester /** * Initial code used the existance of /etc/riak/hot_backup file * as flag to start a backup. */ TEST(HotBackupTester, FileTriggerTest) { char * dup_path, *path; int ret_val; bool ret_flag; uint64_t perf_before, perf_after; perf_before=gPerfCounters->Value(ePerfSyslogWrite); // cleanup anything existing, likely fails /// hmm, should there be a way to move this trigger /// to a "safe" area like /tmp? unlink(GetTriggerPath()); // does parent path exist? // bypass test if it does not ... Travis CI and // other users might not be able to access /etc/riak dup_path=strdup(GetTriggerPath()); path=dirname(dup_path); ret_val=access(path, R_OK | W_OK); ASSERT_TRUE(-1!=ret_val); // is a trigger seen (hope not) ret_flag=HotBackup::IsTriggerSet(); ASSERT_TRUE(!ret_flag); // make a trigger ret_val=open(GetTriggerPath(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ASSERT_TRUE(-1!=ret_val); close(ret_val); // test the trigger ret_flag=HotBackup::IsTriggerSet(); ASSERT_TRUE(ret_flag); // pretend to be back process /// schedule twice HotBackup::HotBackupScheduled(); HotBackup::HotBackupScheduled(); // trigger still there? ret_flag=HotBackup::IsTriggerSet(); ASSERT_TRUE(ret_flag); // release one, trigger goes away HotBackup::HotBackupFinished(); ret_flag=HotBackup::IsTriggerSet(); ASSERT_TRUE(!ret_flag); // did our simulation create a syslog entry? // (bonus if you manually check /var/log/syslog for actual entries) perf_after=gPerfCounters->Value(ePerfSyslogWrite) - perf_before; ASSERT_TRUE( 1==perf_after ); // clean up second count. HotBackupFinished(); // clean up free(dup_path); dup_path=NULL; } // FileTriggerTest /** * Verify that backup directories rotate */ TEST(HotBackupTester, DirectoryRotationTest) { int ret_val, loop, inner_loop, offset, file_num; Options options, backup_options, inner_options; bool ret_flag, should_find, did_find; std::string table_file, backup_name; options.tiered_slow_level=4; options.tiered_fast_prefix=m_DBName + "/fast"; options.tiered_slow_prefix=m_DBName + "/slow"; ClearAllBackups(options); // manually create database directories ret_val=mkdir(m_DBName.c_str(), 0777); ret_val=mkdir(options.tiered_fast_prefix.c_str(), 0777); ASSERT_TRUE(0==ret_val); ret_val=mkdir(options.tiered_slow_prefix.c_str(), 0777); ASSERT_TRUE(0==ret_val); MakeLevelDirectories(Env::Default(), options); backup_options=options; SetBackupPaths(backup_options, 0); // this loop goes one higher than permitted retention // to validate deletion of oldest for (loop=0; loop<=config::kNumBackups; ++loop) { // rotate directories ret_flag=PrepareDirectories(options); ASSERT_TRUE(ret_flag); // these files are to "mark" the backups, not // pretending this is a true file link // make a file in fast tier ... 10 + backup iteration table_file=TableFileName(backup_options, 10+loop, 1); ret_val=open(table_file.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ASSERT_TRUE(-1!=ret_val); close(ret_val); // make a file in slow tier ... 20 + backup iteration table_file=TableFileName(backup_options, 20+loop, 5); ret_val=open(table_file.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ASSERT_TRUE(-1!=ret_val); close(ret_val); // test files for (inner_loop=config::kNumBackups+1; 0<=inner_loop; --inner_loop) { offset=(loop<config::kNumBackups) ? 0 : loop-config::kNumBackups +1; should_find=(inner_loop<=loop) && (offset<=inner_loop); inner_options=options; SetBackupPaths(inner_options, inner_loop-offset); file_num=loop - inner_loop + offset; table_file=TableFileName(inner_options, 10+file_num, 1); ret_val=access(table_file.c_str(), F_OK); ASSERT_TRUE( (0==ret_val) == should_find); table_file=TableFileName(inner_options, 20+file_num, 5); ret_val=access(table_file.c_str(), F_OK); ASSERT_TRUE( (0==ret_val) == should_find); } // for } // for ClearAllBackups(options); // clean up ret_val=rmdir(m_DBName.c_str()); ASSERT_TRUE(0==ret_val); } // DirectoryRotationTest } // namespace leveldb
#include <iostream> #include <string> #include "Instructions.hpp" void run_part_one() { std::string line; InstructionRunner runner; std::array<int,REGISTER_COUNT> registers = {0,0}; while(std::getline(std::cin,line)) { runner.add_instruction(parse_instruction(line)); } runner.run(registers); std::cout<<registers[1]<<std::endl; } void run_part_two() { } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day23 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } } added runtime code for day 23 part two #include <iostream> #include <string> #include "Instructions.hpp" void run_part_one() { std::string line; InstructionRunner runner; std::array<int,REGISTER_COUNT> registers = {0,0}; while(std::getline(std::cin,line)) { runner.add_instruction(parse_instruction(line)); } runner.run(registers); std::cout<<registers[1]<<std::endl; } void run_part_two() { std::string line; InstructionRunner runner; std::array<int,REGISTER_COUNT> registers = {1,0}; while(std::getline(std::cin,line)) { runner.add_instruction(parse_instruction(line)); } runner.run(registers); std::cout<<registers[1]<<std::endl; } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day23 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } }
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "utilities/ttl/db_ttl.h" #include "include/utilities/utility_db.h" #include "db/filename.h" #include "util/coding.h" #include "include/leveldb/env.h" #include "include/leveldb/iterator.h" namespace leveldb { class TtlIterator : public Iterator { public: TtlIterator(Iterator* iter, int32_t ts_len) : iter_(iter), ts_len_(ts_len) { assert(iter_); } ~TtlIterator() { delete iter_; } bool Valid() const { return iter_->Valid(); } void SeekToFirst() { iter_->SeekToFirst(); } void SeekToLast() { iter_->SeekToLast(); } void Seek(const Slice& target) { iter_->Seek(target); } void Next() { iter_->Next(); } void Prev() { iter_->Prev(); } Slice key() const { return iter_->key(); } Slice value() const { assert(iter_->value().size() >= (unsigned)ts_len_); return std::string(iter_->value().data(), iter_->value().size() - ts_len_); } Status status() const { return iter_->status(); } private: Iterator* iter_; int32_t ts_len_; }; // Open the db inside DBWithTTL because options needs pointer to its ttl DBWithTTL::DBWithTTL(const int32_t ttl, const Options& options, const std::string& dbname, Status& st) : ttl_(ttl) { assert(options.CompactionFilter == nullptr); Options options_to_open = options; options_to_open.compaction_filter_args = &ttl_; options_to_open.CompactionFilter = DeleteByTS; st = DB::Open(options_to_open, dbname, &db_); } DBWithTTL::~DBWithTTL() { delete db_; } Status UtilityDB::OpenTtlDB( const Options& options, const std::string& dbname, DB** dbptr, int32_t ttl) { Status st; *dbptr = new DBWithTTL(ttl, options, dbname, st); if (!st.ok()) { delete dbptr; } return st; } // returns true(i.e. key-value to be deleted) if its TS has expired based on ttl bool DBWithTTL::DeleteByTS( void* args, int level, const Slice& key, const Slice& old_val, std::string* new_val, bool* value_changed) { return IsStale(old_val, *(int32_t*)args); } // Gives back the current time Status DBWithTTL::GetCurrentTime(int32_t& curtime) { return Env::Default()->GetCurrentTime((int64_t*)&curtime); } // Appends the current timestamp to the string. // Returns false if could not get the current_time, true if append succeeds Status DBWithTTL::AppendTS(const Slice& val, std::string& val_with_ts) { val_with_ts.reserve(kTSLength + val.size()); char ts_string[kTSLength]; int32_t curtime; Status st = GetCurrentTime(curtime); if (!st.ok()) { return st; } EncodeFixed32(ts_string, curtime); val_with_ts.append(val.data(), val.size()); val_with_ts.append(ts_string, kTSLength); return st; } // Checks if the string is stale or not according to TTl provided bool DBWithTTL::IsStale(const Slice& value, int32_t ttl) { if (ttl <= 0) { // Data is fresh if TTL is non-positive return false; } int32_t curtime; if (!GetCurrentTime(curtime).ok()) { return false; // Treat the data as fresh if could not get current time } else { int32_t timestamp_value = DecodeFixed32(value.data() + value.size() - kTSLength); if ((timestamp_value + ttl) < curtime) { return true; // Data is stale } } return false; } // Strips the TS from the end of the string Status DBWithTTL::StripTS(std::string* str) { Status st; if (str->length() < (unsigned)kTSLength) { return Status::IOError("Error: value's length less than timestamp's\n"); } // Erasing characters which hold the TS str->erase(str->length() - kTSLength, kTSLength); return st; } Status DBWithTTL::Put( const WriteOptions& o, const Slice& key, const Slice& val) { std::string value_with_ts; Status st = AppendTS(val, value_with_ts); if (!st.ok()) { return st; } return db_->Put(o, key, value_with_ts); } Status DBWithTTL::Get(const ReadOptions& options, const Slice& key, std::string* value) { Status st = db_->Get(options, key, value); if (!st.ok()) { return st; } return StripTS(value); } Status DBWithTTL::Delete(const WriteOptions& wopts, const Slice& key) { return db_->Delete(wopts, key); } Status DBWithTTL::Write(const WriteOptions& opts, WriteBatch* updates) { return db_->Write(opts, updates); } Iterator* DBWithTTL::NewIterator(const ReadOptions& opts) { return new TtlIterator(db_->NewIterator(opts), kTSLength); } const Snapshot* DBWithTTL::GetSnapshot() { return db_->GetSnapshot(); } void DBWithTTL::ReleaseSnapshot(const Snapshot* snapshot) { db_->ReleaseSnapshot(snapshot); } bool DBWithTTL::GetProperty(const Slice& property, std::string* value) { return db_->GetProperty(property, value); } void DBWithTTL::GetApproximateSizes(const Range* r, int n, uint64_t* sizes) { db_->GetApproximateSizes(r, n, sizes); } void DBWithTTL::CompactRange(const Slice* begin, const Slice* end) { db_->CompactRange(begin, end); } int DBWithTTL::NumberLevels() { return db_->NumberLevels(); } int DBWithTTL::MaxMemCompactionLevel() { return db_->MaxMemCompactionLevel(); } int DBWithTTL::Level0StopWriteTrigger() { return db_->Level0StopWriteTrigger(); } Status DBWithTTL::Flush(const FlushOptions& fopts) { return db_->Flush(fopts); } Status DBWithTTL::DisableFileDeletions() { return db_->DisableFileDeletions(); } Status DBWithTTL::EnableFileDeletions() { return db_->EnableFileDeletions(); } Status DBWithTTL::GetLiveFiles(std::vector<std::string>& vec, uint64_t* mfs) { return db_->GetLiveFiles(vec, mfs); } SequenceNumber DBWithTTL::GetLatestSequenceNumber() { return db_->GetLatestSequenceNumber(); } Status DBWithTTL::GetUpdatesSince( SequenceNumber seq_number, unique_ptr<TransactionLogIterator>* iter) { return db_->GetUpdatesSince(seq_number, iter); } void DBWithTTL::TEST_Destroy_DBWithTtl() { ((DBImpl*) db_)->TEST_Destroy_DBImpl(); } } // namespace leveldb Fix invalid-read to freed memory in ttl-iterator Summary: value function in ttl-iterator was returning string which would have been freed before its usage as a slice. Thanks valgrind! Test Plan: valgrind ./ttl_test Reviewers: dhruba, haobo, sheki, vamsi Reviewed By: haobo CC: leveldb Differential Revision: https://reviews.facebook.net/D10635 // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "utilities/ttl/db_ttl.h" #include "include/utilities/utility_db.h" #include "db/filename.h" #include "util/coding.h" #include "include/leveldb/env.h" #include "include/leveldb/iterator.h" namespace leveldb { class TtlIterator : public Iterator { public: TtlIterator(Iterator* iter, int32_t ts_len) : iter_(iter), ts_len_(ts_len) { assert(iter_); } ~TtlIterator() { delete iter_; } bool Valid() const { return iter_->Valid(); } void SeekToFirst() { iter_->SeekToFirst(); } void SeekToLast() { iter_->SeekToLast(); } void Seek(const Slice& target) { iter_->Seek(target); } void Next() { iter_->Next(); } void Prev() { iter_->Prev(); } Slice key() const { return iter_->key(); } Slice value() const { assert(iter_->value().size() >= (unsigned)ts_len_); Slice trimmed_value = iter_->value(); trimmed_value.size_ -= ts_len_; return trimmed_value; } Status status() const { return iter_->status(); } private: Iterator* iter_; int32_t ts_len_; }; // Open the db inside DBWithTTL because options needs pointer to its ttl DBWithTTL::DBWithTTL(const int32_t ttl, const Options& options, const std::string& dbname, Status& st) : ttl_(ttl) { assert(options.CompactionFilter == nullptr); Options options_to_open = options; options_to_open.compaction_filter_args = &ttl_; options_to_open.CompactionFilter = DeleteByTS; st = DB::Open(options_to_open, dbname, &db_); } DBWithTTL::~DBWithTTL() { delete db_; } Status UtilityDB::OpenTtlDB( const Options& options, const std::string& dbname, DB** dbptr, int32_t ttl) { Status st; *dbptr = new DBWithTTL(ttl, options, dbname, st); if (!st.ok()) { delete dbptr; } return st; } // returns true(i.e. key-value to be deleted) if its TS has expired based on ttl bool DBWithTTL::DeleteByTS( void* args, int level, const Slice& key, const Slice& old_val, std::string* new_val, bool* value_changed) { return IsStale(old_val, *(int32_t*)args); } // Gives back the current time Status DBWithTTL::GetCurrentTime(int32_t& curtime) { return Env::Default()->GetCurrentTime((int64_t*)&curtime); } // Appends the current timestamp to the string. // Returns false if could not get the current_time, true if append succeeds Status DBWithTTL::AppendTS(const Slice& val, std::string& val_with_ts) { val_with_ts.reserve(kTSLength + val.size()); char ts_string[kTSLength]; int32_t curtime; Status st = GetCurrentTime(curtime); if (!st.ok()) { return st; } EncodeFixed32(ts_string, curtime); val_with_ts.append(val.data(), val.size()); val_with_ts.append(ts_string, kTSLength); return st; } // Checks if the string is stale or not according to TTl provided bool DBWithTTL::IsStale(const Slice& value, int32_t ttl) { if (ttl <= 0) { // Data is fresh if TTL is non-positive return false; } int32_t curtime; if (!GetCurrentTime(curtime).ok()) { return false; // Treat the data as fresh if could not get current time } else { int32_t timestamp_value = DecodeFixed32(value.data() + value.size() - kTSLength); if ((timestamp_value + ttl) < curtime) { return true; // Data is stale } } return false; } // Strips the TS from the end of the string Status DBWithTTL::StripTS(std::string* str) { Status st; if (str->length() < (unsigned)kTSLength) { return Status::IOError("Error: value's length less than timestamp's\n"); } // Erasing characters which hold the TS str->erase(str->length() - kTSLength, kTSLength); return st; } Status DBWithTTL::Put( const WriteOptions& o, const Slice& key, const Slice& val) { std::string value_with_ts; Status st = AppendTS(val, value_with_ts); if (!st.ok()) { return st; } return db_->Put(o, key, value_with_ts); } Status DBWithTTL::Get(const ReadOptions& options, const Slice& key, std::string* value) { Status st = db_->Get(options, key, value); if (!st.ok()) { return st; } return StripTS(value); } Status DBWithTTL::Delete(const WriteOptions& wopts, const Slice& key) { return db_->Delete(wopts, key); } Status DBWithTTL::Write(const WriteOptions& opts, WriteBatch* updates) { return db_->Write(opts, updates); } Iterator* DBWithTTL::NewIterator(const ReadOptions& opts) { return new TtlIterator(db_->NewIterator(opts), kTSLength); } const Snapshot* DBWithTTL::GetSnapshot() { return db_->GetSnapshot(); } void DBWithTTL::ReleaseSnapshot(const Snapshot* snapshot) { db_->ReleaseSnapshot(snapshot); } bool DBWithTTL::GetProperty(const Slice& property, std::string* value) { return db_->GetProperty(property, value); } void DBWithTTL::GetApproximateSizes(const Range* r, int n, uint64_t* sizes) { db_->GetApproximateSizes(r, n, sizes); } void DBWithTTL::CompactRange(const Slice* begin, const Slice* end) { db_->CompactRange(begin, end); } int DBWithTTL::NumberLevels() { return db_->NumberLevels(); } int DBWithTTL::MaxMemCompactionLevel() { return db_->MaxMemCompactionLevel(); } int DBWithTTL::Level0StopWriteTrigger() { return db_->Level0StopWriteTrigger(); } Status DBWithTTL::Flush(const FlushOptions& fopts) { return db_->Flush(fopts); } Status DBWithTTL::DisableFileDeletions() { return db_->DisableFileDeletions(); } Status DBWithTTL::EnableFileDeletions() { return db_->EnableFileDeletions(); } Status DBWithTTL::GetLiveFiles(std::vector<std::string>& vec, uint64_t* mfs) { return db_->GetLiveFiles(vec, mfs); } SequenceNumber DBWithTTL::GetLatestSequenceNumber() { return db_->GetLatestSequenceNumber(); } Status DBWithTTL::GetUpdatesSince( SequenceNumber seq_number, unique_ptr<TransactionLogIterator>* iter) { return db_->GetUpdatesSince(seq_number, iter); } void DBWithTTL::TEST_Destroy_DBWithTtl() { ((DBImpl*) db_)->TEST_Destroy_DBImpl(); } } // namespace leveldb
// The MIT License // // Copyright (c) 2011 daniperez // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////// // roadef12 #include "roadef12-common/service/Service.hpp" #include "roadef12-common/service/ProgramOptions.hpp" #include "roadef12-common/service/ServiceExceptions.hpp" #include "roadef12-common/util/Util.hpp" /////////////////////////////////////////////////////////////////////////// // STD #include <iostream> /////////////////////////////////////////////////////////////////////////// class ExampleService : public ROADEF12COMMON::Service { public: ExampleService ( const ROADEF12COMMON::ServiceInput& input ) throw ( ROADEF12COMMON::IOException, ROADEF12COMMON::ParseException ) : ROADEF12COMMON::Service ( input ) { } virtual void optimize () throw ( ROADEF12COMMON::IOException, ROADEF12COMMON::ParseException ) { std::cout << "processes=" << params.processes.size() << " machines=" << params.machines.size() << " resources=" << params.resources.size() << std::endl; if ( options.nullCopy ) { firstAssignment.write ( options.solution.c_str() ); } else if ( options.nullNull ) { // Do not perform any optimization, no output is produced. } else { std::cout << "Your code goes here" << std::endl; // Don't forget to write a solution firstAssignment.write ( options.solution.c_str() ); } } }; int main ( int argc, char **argv ) { try { ROADEF12COMMON::ServiceInput input = ROADEF12COMMON::ProgramOptions::parseCommandLine ( argc, argv ); ExampleService service ( input ); std::cout << "Optimization started..." << std::endl; service.optimize(); std::cout << "Optimization finished!" << std::endl; exit ( EXIT_SUCCESS ); } catch ( ROADEF12COMMON::DoNotContinue& e ) { exit ( EXIT_SUCCESS ); } catch( ROADEF12COMMON::ParseException& e ) { std::cerr << "Error while parsing: " << e.what() << std::endl; } catch ( ROADEF12COMMON::InvalidSolution& e ) { std::cerr << "The produced solution is not valid" << std::endl; } catch ( std::exception& e ) { std::cerr << e.what() << std::endl; } exit ( EXIT_FAILURE ); } Removed headers not really needed. // The MIT License // // Copyright (c) 2011 daniperez // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////// // roadef12 #include <roadef12-common/service/Service.hpp> #include <roadef12-common/service/ProgramOptions.hpp> /////////////////////////////////////////////////////////////////////////// // STD #include <iostream> /////////////////////////////////////////////////////////////////////////// class ExampleService : public ROADEF12COMMON::Service { public: ExampleService ( const ROADEF12COMMON::ServiceInput& input ) throw ( ROADEF12COMMON::IOException, ROADEF12COMMON::ParseException ) : ROADEF12COMMON::Service ( input ) { } virtual void optimize () throw ( ROADEF12COMMON::IOException, ROADEF12COMMON::ParseException ) { std::cout << "processes=" << params.processes.size() << " machines=" << params.machines.size() << " resources=" << params.resources.size() << std::endl; if ( options.nullCopy ) { firstAssignment.write ( options.solution.c_str() ); } else if ( options.nullNull ) { // Do not perform any optimization, no output is produced. } else { std::cout << "Your code goes here" << std::endl; // Don't forget to write a solution firstAssignment.write ( options.solution.c_str() ); } } }; int main ( int argc, char **argv ) { try { ROADEF12COMMON::ServiceInput input = ROADEF12COMMON::ProgramOptions::parseCommandLine ( argc, argv ); ExampleService service ( input ); std::cout << "Optimization started..." << std::endl; service.optimize(); std::cout << "Optimization finished!" << std::endl; exit ( EXIT_SUCCESS ); } catch ( ROADEF12COMMON::DoNotContinue& e ) { exit ( EXIT_SUCCESS ); } catch( ROADEF12COMMON::ParseException& e ) { std::cerr << "Error while parsing: " << e.what() << std::endl; } catch ( ROADEF12COMMON::InvalidSolution& e ) { std::cerr << "The produced solution is not valid" << std::endl; } catch ( std::exception& e ) { std::cerr << e.what() << std::endl; } exit ( EXIT_FAILURE ); }
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code (advanced), about // // - loading an Abaqus tetahedrom mesh // - apply a load to the mesh using an external tool, // say CFD or SPH (here simulated as a function in this .cpp file) // that is perform a cosimulation. #include "chrono/geometry/ChTriangleMeshConnected.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/physics/ChLoadContainer.h" #include "chrono/physics/ChSystem.h" #include "chrono/physics/ChSystemDEM.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/DeformableTerrain.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; int main(int argc, char* argv[]) { // Global parameter for tire: double tire_rad = 0.8; double tire_vel_z0 = -3; ChVector<> tire_center(0, 0.02+tire_rad, 0); ChMatrix33<> tire_alignment(Q_from_AngAxis(CH_C_PI, VECT_Y)); // create rotated 180 on y double tire_w0 = tire_vel_z0/tire_rad; // Create a Chrono::Engine physical system ChSystemDEM my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0)); application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512, video::SColorf(0.8f, 0.8f, 1.0f)); std::shared_ptr<ChBody> mtruss (new ChBody); mtruss->SetBodyFixed(true); my_system.Add(mtruss); // // CREATE A RIGID BODY WITH A MESH // // Create also a rigid body with a rigid mesh that will be used for the cosimulation, // this time the ChLoadContactSurfaceMesh cannot be used as in the FEA case, so we // will use the ChLoadBodyMesh class: std::shared_ptr<ChBody> mrigidbody (new ChBody); my_system.Add(mrigidbody); mrigidbody->SetMass(200); mrigidbody->SetInertiaXX(ChVector<>(20,20,20)); mrigidbody->SetPos(tire_center + ChVector<>(0,0.3,0)); std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape); mrigidmesh->GetMesh().LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj")); mrigidmesh->GetMesh().Transform(VNULL, Q_from_AngAxis(CH_C_PI, VECT_Y) ); mrigidbody->AddAsset(mrigidmesh); mrigidbody->GetCollisionModel()->ClearModel(); mrigidbody->GetCollisionModel()->AddTriangleMesh(mrigidmesh->GetMesh(), false, false, VNULL, ChMatrix33<>(CH_C_PI, VECT_Y), 0.01); mrigidbody->GetCollisionModel()->BuildModel(); mrigidbody->SetCollide(true); std::shared_ptr<ChColorAsset> mcol(new ChColorAsset); mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f)); mrigidbody->AddAsset(mcol); std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine); myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM); myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED); if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(myengine->Get_spe_funct()) ) mfun->Set_yconst(CH_C_PI / 4.0); myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y))); my_system.Add(myengine); // // THE DEFORMABLE TERRAIN // // Create the 'deformable terrain' object vehicle::DeformableTerrain mterrain(&my_system); // Optionally, displace/tilt/rotate the terrain reference plane: mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.5))); // Initialize the geometry of the soil: use either a regular grid: mterrain.Initialize(0.2,1.5,5,100,200); // or use a height map: //mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3); // Set the soil terramechanical parameters: mterrain.SetSoilParametersSCM(1.2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 30, // Mohr friction limit (degrees) 0.01,// Janosi shear coefficient (m) 5e7 // Elastic stiffness (Pa/m), before plastic yeld, must be > Kphi ); mterrain.SetBulldozingFlow(true); // inflate soil at the border of the rut mterrain.SetBulldozingParameters(40, // angle of frictionfor erosion of displaced material at the border of the rut 1.6);// displaced material vs downward pressed material. // Set some visualization parameters: either with a texture, or with falsecolor plot, etc. //mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2); mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets application.AssetUpdateAll(); // Use shadows in realtime view application.AddShadowAll(); // ==IMPORTANT!== Mark completion of system construction my_system.SetupInitial(); // // THE SOFT-REAL-TIME CYCLE // /* // Change solver to embedded MINRES // NOTE! it is strongly advised that you compile the optional MKL module // if you need higher precision, and switch to its MKL solver - see demos for FEA & MKL. my_system.SetSolverType(ChSystem::SOLVER_MINRES); my_system.SetSolverWarmStarting(true); // this helps a lot to speedup convergence in this class of problems my_system.SetMaxItersSolverSpeed(40); my_system.SetTolForce(1e-10); */ application.SetTimestep(0.005); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.DoStep(); ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(), 1180); application.EndScene(); } return 0; } Updating the demo of SCM deformable soil to use the new mesh refinement // // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code (advanced), about // // - loading an Abaqus tetahedrom mesh // - apply a load to the mesh using an external tool, // say CFD or SPH (here simulated as a function in this .cpp file) // that is perform a cosimulation. #include "chrono/geometry/ChTriangleMeshConnected.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/physics/ChLoadContainer.h" #include "chrono/physics/ChSystem.h" #include "chrono/physics/ChSystemDEM.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/DeformableTerrain.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; int main(int argc, char* argv[]) { // Global parameter for tire: double tire_rad = 0.8; double tire_vel_z0 = -3; ChVector<> tire_center(0, 0.02+tire_rad, 0); ChMatrix33<> tire_alignment(Q_from_AngAxis(CH_C_PI, VECT_Y)); // create rotated 180 on y double tire_w0 = tire_vel_z0/tire_rad; // Create a Chrono::Engine physical system ChSystemDEM my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0)); application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512, video::SColorf(0.8f, 0.8f, 1.0f)); std::shared_ptr<ChBody> mtruss (new ChBody); mtruss->SetBodyFixed(true); my_system.Add(mtruss); // // CREATE A RIGID BODY WITH A MESH // // Create also a rigid body with a rigid mesh that will be used for the cosimulation, // this time the ChLoadContactSurfaceMesh cannot be used as in the FEA case, so we // will use the ChLoadBodyMesh class: std::shared_ptr<ChBody> mrigidbody (new ChBody); my_system.Add(mrigidbody); mrigidbody->SetMass(200); mrigidbody->SetInertiaXX(ChVector<>(20,20,20)); mrigidbody->SetPos(tire_center + ChVector<>(0,0.3,0)); std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape); mrigidmesh->GetMesh().LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj")); mrigidmesh->GetMesh().Transform(VNULL, Q_from_AngAxis(CH_C_PI, VECT_Y) ); mrigidbody->AddAsset(mrigidmesh); mrigidbody->GetCollisionModel()->ClearModel(); mrigidbody->GetCollisionModel()->AddTriangleMesh(mrigidmesh->GetMesh(), false, false, VNULL, ChMatrix33<>(CH_C_PI, VECT_Y), 0.01); mrigidbody->GetCollisionModel()->BuildModel(); mrigidbody->SetCollide(true); std::shared_ptr<ChColorAsset> mcol(new ChColorAsset); mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f)); mrigidbody->AddAsset(mcol); std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine); myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM); myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED); if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(myengine->Get_spe_funct()) ) mfun->Set_yconst(CH_C_PI / 4.0); myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y))); my_system.Add(myengine); // // THE DEFORMABLE TERRAIN // // Create the 'deformable terrain' object vehicle::DeformableTerrain mterrain(&my_system); // Optionally, displace/tilt/rotate the terrain reference plane: mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.5))); // Initialize the geometry of the soil: use either a regular grid: mterrain.Initialize(0.2,1.5,5,20,60); // or use a height map: //mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3); // Set the soil terramechanical parameters: mterrain.SetSoilParametersSCM(1.2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 30, // Mohr friction limit (degrees) 0.01,// Janosi shear coefficient (m) 5e7 // Elastic stiffness (Pa/m), before plastic yeld, must be > Kphi ); mterrain.SetBulldozingFlow(false); // inflate soil at the border of the rut mterrain.SetBulldozingParameters(40, // angle of frictionfor erosion of displaced material at the border of the rut 1.6);// displaced material vs downward pressed material. // Turn on the automatic level of detail refinement, so a coarse terrain mesh // is automatically improved by adding more points under the wheel contact patch: mterrain.SetAutomaticRefinement(true); mterrain.SetAutomaticRefinementResolution(0.02); // Set some visualization parameters: either with a texture, or with falsecolor plot, etc. //mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2); mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets application.AssetUpdateAll(); // Use shadows in realtime view application.AddShadowAll(); // ==IMPORTANT!== Mark completion of system construction my_system.SetupInitial(); // // THE SOFT-REAL-TIME CYCLE // /* // Change solver to embedded MINRES // NOTE! it is strongly advised that you compile the optional MKL module // if you need higher precision, and switch to its MKL solver - see demos for FEA & MKL. my_system.SetSolverType(ChSystem::SOLVER_MINRES); my_system.SetSolverWarmStarting(true); // this helps a lot to speedup convergence in this class of problems my_system.SetMaxItersSolverSpeed(40); my_system.SetTolForce(1e-10); */ application.SetTimestep(0.005); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.DoStep(); ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(), 1180); application.EndScene(); } return 0; }
/*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2015-2016 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file * \brief */ /*-------------------------------------------------------------------*/ #include "gl4cCopyImageTests.hpp" #include "gluDefs.hpp" #include "gluStrUtil.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuFloat.hpp" #include "tcuTestLog.hpp" #include <algorithm> #include <iomanip> #include <sstream> #include "deMath.h" /* There are far too much combinations specified for FunctionalTest. * * Following flags controls what is enabled. Set as 1 to enable * all test case from given category, 0 otherwise. * * By default everything is disabled - which still gives 14560 test cases. * * ALL_FORMAT - selects all internal formats, 61 x 61 * ALL_TARGETS - selects all valid targets, 10 x 10 * ALL_IMG_DIM - selects all image dimmensions, 9 x 9 * ALL_REG_DIM - selects all region dimmensions, 7 x 7 * ALL_REG_POS - selects all region positions, like left-top corner, 8 x 8 */ #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS 0 #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS 0 #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_IMG_DIM 0 #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_DIM 0 #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS 0 /* The following flags controls if workarounds are enabled */ #define COPY_IMAGE_WRKARD_FORMATS 0 using namespace glw; namespace gl4cts { namespace CopyImage { /** Various utilities used by all tests * **/ class Utils { public: /* Routines */ static bool areFormatsCompatible(glw::GLenum src, glw::GLenum dst); static bool comparePixels(glw::GLenum left_internal_format, const glw::GLdouble& left_red, const glw::GLdouble& left_green, const glw::GLdouble& left_blue, const glw::GLdouble& left_alpha, glw::GLenum right_internal_format, const glw::GLdouble& right_red, const glw::GLdouble& right_green, const glw::GLdouble& right_blue, const glw::GLdouble& right_alpha); static bool comparePixels(glw::GLuint left_pixel_size, const glw::GLubyte* left_pixel_data, glw::GLuint right_pixel_size, const glw::GLubyte* right_pixel_data, const glw::GLenum format); static void deleteTexture(deqp::Context& context, glw::GLenum target, glw::GLuint name); static bool isTargetMultilayer(glw::GLenum target); static bool isTargetMultilevel(glw::GLenum target); static bool isTargetMultisampled(glw::GLenum target); static glw::GLuint generateTexture(deqp::Context& context, glw::GLenum target); static void maskPixelForFormat(glw::GLenum internal_format, glw::GLubyte* pixel); static glw::GLdouble getEpsilon(glw::GLenum internal_format); static glw::GLuint getPixelSizeForFormat(glw::GLenum internal_format); static glw::GLenum getFormat(glw::GLenum internal_format); static glw::GLuint getNumberOfChannels(glw::GLenum internal_format); static std::string getPixelString(glw::GLenum internal_format, const glw::GLubyte* pixel); static glw::GLenum getType(glw::GLenum internal_format); static void makeTextureComplete(deqp::Context& context, glw::GLenum target, glw::GLuint id, glw::GLint base_level, glw::GLint max_level); static glw::GLuint prepareCompressedTex(deqp::Context& context, glw::GLenum target, glw::GLenum internal_format); static glw::GLuint prepareMultisampleTex(deqp::Context& context, glw::GLenum target, glw::GLsizei n_samples); static glw::GLuint prepareRenderBuffer(deqp::Context& context, glw::GLenum internal_format); static glw::GLuint prepareTex16x16x6(deqp::Context& context, glw::GLenum target, glw::GLenum internal_format, glw::GLenum format, glw::GLenum type, glw::GLuint& out_buf_id); static void prepareTexture(deqp::Context& context, glw::GLuint name, glw::GLenum target, glw::GLenum internal_format, glw::GLenum format, glw::GLenum type, glw::GLuint level, glw::GLuint width, glw::GLuint height, glw::GLuint depth, const glw::GLvoid* pixels, glw::GLuint& out_buf_id); static glw::GLenum transProxyToRealTarget(glw::GLenum target); static glw::GLenum transRealToBindTarget(glw::GLenum target); static void readChannel(glw::GLenum type, glw::GLuint channel, const glw::GLubyte* pixel, glw::GLdouble& out_value); static void writeChannel(glw::GLenum type, glw::GLuint channel, glw::GLdouble value, glw::GLubyte* pixel); static void packPixel(glw::GLenum internal_format, glw::GLenum type, glw::GLdouble red, glw::GLdouble green, glw::GLdouble blue, glw::GLdouble alpha, glw::GLubyte* out_pixel); static void unpackPixel(glw::GLenum format, glw::GLenum type, const glw::GLubyte* pixel, glw::GLdouble& out_red, glw::GLdouble& out_green, glw::GLdouble& out_blue, glw::GLdouble& out_alpha); static bool unpackAndComaprePixels(glw::GLenum left_format, glw::GLenum left_type, glw::GLenum left_internal_format, const glw::GLubyte* left_pixel, glw::GLenum right_format, glw::GLenum right_type, glw::GLenum right_internal_format, const glw::GLubyte* right_pixel); static inline bool roundComponent(glw::GLenum internal_format, glw::GLenum component, glw::GLdouble& value); }; /* Global constants */ static const GLenum s_internal_formats[] = { /* R8 */ GL_R8, GL_R8I, GL_R8UI, GL_R8_SNORM, /* R16 */ GL_R16, GL_R16F, GL_R16I, GL_R16UI, GL_R16_SNORM, /* R32 */ GL_R32F, GL_R32I, GL_R32UI, /* RG8 */ GL_RG8, GL_RG8I, GL_RG8UI, GL_RG8_SNORM, /* RG16 */ GL_RG16, GL_RG16F, GL_RG16I, GL_RG16UI, GL_RG16_SNORM, /* RG32 */ GL_RG32F, GL_RG32I, GL_RG32UI, /* RGB8 */ GL_RGB8, GL_RGB8I, GL_RGB8UI, GL_RGB8_SNORM, /* RGB16 */ GL_RGB16, GL_RGB16F, GL_RGB16I, GL_RGB16UI, GL_RGB16_SNORM, /* RGB32 */ GL_RGB32F, GL_RGB32I, GL_RGB32UI, /* RGBA8 */ GL_RGBA8, GL_RGBA8I, GL_RGBA8UI, GL_RGBA8_SNORM, /* RGBA16 */ GL_RGBA16, GL_RGBA16F, GL_RGBA16I, GL_RGBA16UI, GL_RGBA16_SNORM, /* RGBA32 */ GL_RGBA32F, GL_RGBA32I, GL_RGBA32UI, /* 8 */ GL_R3_G3_B2, GL_RGBA2, /* 12 */ GL_RGB4, /* 15 */ GL_RGB5, /* 16 */ GL_RGBA4, GL_RGB5_A1, /* 30 */ GL_RGB10, /* 32 */ GL_RGB10_A2, GL_RGB10_A2UI, GL_R11F_G11F_B10F, GL_RGB9_E5, /* 36 */ GL_RGB12, /* 48 */ GL_RGBA12, }; static const GLenum s_invalid_targets[] = { GL_TEXTURE_BUFFER, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_PROXY_TEXTURE_1D, GL_PROXY_TEXTURE_1D_ARRAY, GL_PROXY_TEXTURE_2D, GL_PROXY_TEXTURE_2D_ARRAY, GL_PROXY_TEXTURE_2D_MULTISAMPLE, GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY, GL_PROXY_TEXTURE_3D, GL_PROXY_TEXTURE_CUBE_MAP, GL_PROXY_TEXTURE_CUBE_MAP_ARRAY, GL_PROXY_TEXTURE_RECTANGLE, }; static const GLenum s_valid_targets[] = { GL_RENDERBUFFER, GL_TEXTURE_1D, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_2D_MULTISAMPLE_ARRAY, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_RECTANGLE, }; static const GLuint s_n_internal_formats = sizeof(s_internal_formats) / sizeof(s_internal_formats[0]); static const GLuint s_n_invalid_targets = sizeof(s_invalid_targets) / sizeof(s_invalid_targets[0]); static const GLuint s_n_valid_targets = sizeof(s_valid_targets) / sizeof(s_valid_targets[0]); /** * Pixel compatibility depends on pixel size. However value returned by getPixelSizeForFormat * needs some refinements * * @param internal_format Internal format of image * * @return Size of pixel for compatibility checks **/ GLuint getPixelSizeForCompatibilityVerification(GLenum internal_format) { GLuint size = Utils::getPixelSizeForFormat(internal_format); switch (internal_format) { case GL_RGBA2: size = 1; break; default: break; } return size; } #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS == 0 /** Filters out formats that should not be tested by FunctionalTest * * @param format Internal format * * @return true if format should be tested, false otherwise **/ bool filterFormats(GLenum format) { bool result = true; switch (format) { /* R8 */ case GL_R8I: case GL_R8UI: case GL_R8_SNORM: /* R16 */ case GL_R16: case GL_R16F: case GL_R16I: case GL_R16UI: case GL_R16_SNORM: /* R32 */ case GL_R32F: case GL_R32I: case GL_R32UI: /* RG8 */ case GL_RG8: case GL_RG8I: case GL_RG8UI: case GL_RG8_SNORM: /* RG16 */ case GL_RG16: case GL_RG16F: case GL_RG16I: case GL_RG16UI: case GL_RG16_SNORM: /* RG32 */ case GL_RG32F: case GL_RG32I: case GL_RG32UI: /* RGB8 */ case GL_RGB8: case GL_RGB8I: case GL_RGB8UI: case GL_RGB8_SNORM: /* RGB16 */ case GL_RGB16: case GL_RGB16F: case GL_RGB16I: case GL_RGB16UI: case GL_RGB16_SNORM: /* RGB32 */ case GL_RGB32I: case GL_RGB32UI: /* RGBA8 */ case GL_RGBA8: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGBA8_SNORM: /* RGBA16 */ case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA16_SNORM: /* RGBA32 */ case GL_RGBA32F: case GL_RGBA32I: case GL_RGBA32UI: result = false; break; default: result = true; break; } return result; } #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS */ /** Checks if two internal_formats are compatible * * @param src Internal format of source image * @param dst Internal format of destination image * * @return true for compatible formats, false otherwise **/ bool Utils::areFormatsCompatible(glw::GLenum src, glw::GLenum dst) { const GLuint dst_size = getPixelSizeForCompatibilityVerification(dst); const GLuint src_size = getPixelSizeForCompatibilityVerification(src); if (dst_size != src_size) { return false; } #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS == 0 if ((false == filterFormats(src)) || (false == filterFormats(dst))) { return false; } #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS */ if (src != dst) { if ((GL_R3_G3_B2 == dst) || (GL_R3_G3_B2 == src) || (GL_RGBA2 == dst) || (GL_RGBA2 == src) || (GL_RGBA4 == dst) || (GL_RGBA4 == src) || (GL_RGB5_A1 == dst) || (GL_RGB5_A1 == src) || (GL_RGB10 == dst) || (GL_RGB10 == src)) { return false; } } #if COPY_IMAGE_WRKARD_FORMATS if ((GL_RGB10_A2 == src) && (GL_R11F_G11F_B10F == dst) || (GL_RGB10_A2 == src) && (GL_RGB9_E5 == dst) || (GL_RGB10_A2UI == src) && (GL_R11F_G11F_B10F == dst) || (GL_RGB10_A2UI == src) && (GL_RGB9_E5 == dst) || (GL_RGB9_E5 == src) && (GL_RGB10_A2 == dst) || (GL_RGB9_E5 == src) && (GL_RGB10_A2UI == dst) || (GL_R11F_G11F_B10F == src) && (GL_RGB10_A2 == dst) || (GL_R11F_G11F_B10F == src) && (GL_RGB10_A2UI == dst)) { return false; } #endif /* COPY_IMAGE_WRKARD_FORMATS */ if (2 == dst_size) { if (src == dst) { return true; } if (((GL_RGB4 == src) && (GL_RGB4 != dst)) || ((GL_RGB4 != src) && (GL_RGB4 == dst)) || ((GL_RGB5 == src) && (GL_RGB5 != dst)) || ((GL_RGB5 != src) && (GL_RGB5 == dst))) { return false; } return true; } if (4 == dst_size) { if (src == dst) { return true; } return true; } return true; } /** Compare two pixels * * @param left_internal_format Internal format of left image * @param left_red Red channel of left image * @param left_green Green channel of left image * @param left_blue Blue channel of left image * @param left_alpha Alpha channel of left image * @param right_internal_format Internal format of right image * @param right_red Red channel of right image * @param right_green Green channel of right image * @param right_blue Blue channel of right image * @param right_alpha Alpha channel of right image * * @return true if pixels match, false otherwise **/ bool Utils::comparePixels(GLenum left_internal_format, const GLdouble& left_red, const GLdouble& left_green, const GLdouble& left_blue, const GLdouble& left_alpha, GLenum right_internal_format, const GLdouble& right_red, const GLdouble& right_green, const GLdouble& right_blue, const GLdouble& right_alpha) { const GLuint left_n_channels = getNumberOfChannels(left_internal_format); const GLuint right_n_channels = getNumberOfChannels(right_internal_format); const GLuint n_channels = (left_n_channels >= right_n_channels) ? right_n_channels : left_n_channels; const GLdouble left_channels[4] = { left_red, left_green, left_blue, left_alpha }; const GLdouble right_channels[4] = { right_red, right_green, right_blue, right_alpha }; for (GLuint i = 0; i < n_channels; ++i) { const GLdouble left = left_channels[i]; const GLdouble right = right_channels[i]; const GLdouble left_eps = getEpsilon(left_internal_format); const GLdouble right_eps = getEpsilon(right_internal_format); const GLdouble eps = fabs(std::max(left_eps, right_eps)); if (eps < fabs(left - right)) { return false; } } return true; } #define RGB9E5_EXPONENT_BITS 5 #define RGB9E5_MANTISSA_BITS 9 #define RGB9E5_EXP_BIAS 15 #define R11FG11FB10F_EXP_BIAS 15 typedef struct { unsigned int r : RGB9E5_MANTISSA_BITS; unsigned int g : RGB9E5_MANTISSA_BITS; unsigned int b : RGB9E5_MANTISSA_BITS; unsigned int biasedexponent : RGB9E5_EXPONENT_BITS; } BitsOfRGB9E5; typedef struct { unsigned int r : 11; unsigned int g : 11; unsigned int b : 10; } BitsOfR11FG11FB10F; typedef union { unsigned int raw; BitsOfRGB9E5 field; } rgb9e5; typedef union { unsigned int raw; BitsOfR11FG11FB10F field; } r11fg11fb10f; void rgb9e5_to_float3(rgb9e5 v, float retval[3]) { int exponent = v.field.biasedexponent - RGB9E5_EXP_BIAS - RGB9E5_MANTISSA_BITS; float scale = (float)pow(2.0, (double)exponent); retval[0] = v.field.r * scale; retval[1] = v.field.g * scale; retval[2] = v.field.b * scale; } // This function will expand a 10-bit or 11-bit float // based on the rules described in 2.3.4.3 and 2.3.4.4 float expandFloat(const unsigned int compressed, const unsigned int numMantissaBits) { unsigned int divisor = (unsigned int)deFloatPow(2, (float)numMantissaBits); float retval = 0.0; unsigned int exponent, mantissa; exponent = compressed / divisor; mantissa = compressed % divisor; if (exponent == 0 && mantissa == 0) retval = 0.0; else if (exponent == 0 && mantissa != 0) retval = deFloatPow(2.f, -14.f) * ((float)mantissa / (float)divisor); else if (0 < exponent && exponent < 31) retval = deFloatPow(2.f, (float)exponent - 15.f) * (1.f + (float)mantissa / (float)divisor); else if (exponent == 31 && mantissa == 0) retval = INFINITY; else if (exponent == 31 && mantissa != 0) retval = NAN; else DE_ASSERT(DE_FALSE && "Invalid exponent and mantissa"); return retval; } void r11fg11fb10f_to_float3(r11fg11fb10f v, float retval[3]) { retval[0] = expandFloat(v.field.r, 6); retval[1] = expandFloat(v.field.g, 6); retval[2] = expandFloat(v.field.b, 5); } bool compareRGB9E5(const void* ptr1, const void* ptr2, int num) { rgb9e5* data1 = (rgb9e5*)ptr1; rgb9e5* data2 = (rgb9e5*)ptr2; float value1[3]; float value2[3]; for (int i = 0; i<num>> 2; ++i) { rgb9e5_to_float3(data1[i], value1); rgb9e5_to_float3(data2[i], value2); for (int j = 0; j < 3; ++j) { if (value1[j] != value2[j]) { return false; } } } return true; } bool compareR11FG11FB10F(const void* ptr1, const void* ptr2, int num) { r11fg11fb10f* data1 = (r11fg11fb10f*)ptr1; r11fg11fb10f* data2 = (r11fg11fb10f*)ptr2; float value1[3]; float value2[3]; for (int i = 0; i<num>> 2; ++i) { r11fg11fb10f_to_float3(data1[i], value1); r11fg11fb10f_to_float3(data2[i], value2); for (int j = 0; j < 3; ++j) { if (value1[j] != value2[j]) { return false; } } } return true; } /** Compare two pixels with memcmp * * @param left_pixel_size Size of left pixel * @param left_pixel_data Data of left pixel * @param right_pixel_size Size of right pixel * @param right_pixel_data Data of right pixel * * @return true if memory match, false otherwise **/ bool Utils::comparePixels(GLuint left_pixel_size, const GLubyte* left_pixel_data, GLuint right_pixel_size, const GLubyte* right_pixel_data, const GLenum format) { const GLuint pixel_size = (left_pixel_size >= right_pixel_size) ? left_pixel_size : right_pixel_size; if (format == GL_RGB9_E5) { return compareRGB9E5(left_pixel_data, right_pixel_data, pixel_size); } else if (format == GL_R11F_G11F_B10F) { return compareR11FG11FB10F(left_pixel_data, right_pixel_data, pixel_size); } return 0 == memcmp(left_pixel_data, right_pixel_data, pixel_size); } /** Delete texture or renderbuffer * * @param context Test context * @param target Image target * @param name Name of image **/ void Utils::deleteTexture(deqp::Context& context, GLenum target, GLuint name) { const Functions& gl = context.getRenderContext().getFunctions(); if (GL_RENDERBUFFER == target) { gl.deleteRenderbuffers(1, &name); } else { gl.deleteTextures(1, &name); } } /** Get epsilon for given internal_format * * @param internal_format Internal format of image * * @return Epsilon value **/ GLdouble Utils::getEpsilon(GLenum internal_format) { GLdouble epsilon; switch (internal_format) { case GL_R8: case GL_R8_SNORM: case GL_R16: case GL_R16F: case GL_R16_SNORM: case GL_R32F: case GL_R8I: case GL_R8UI: case GL_R16I: case GL_R16UI: case GL_R32I: case GL_R32UI: case GL_RG8: case GL_RG8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16_SNORM: case GL_RG32F: case GL_RG8I: case GL_RG8UI: case GL_RG16I: case GL_RG16UI: case GL_RG32I: case GL_RG32UI: case GL_R3_G3_B2: case GL_RGB4: case GL_RGB5: case GL_RGB8: case GL_RGB8_SNORM: case GL_R11F_G11F_B10F: case GL_RGB16: case GL_RGB16F: case GL_RGB16_SNORM: case GL_RGB32F: case GL_RGB8I: case GL_RGB8UI: case GL_RGB10: case GL_RGB16I: case GL_RGB16UI: case GL_RGB32I: case GL_RGB32UI: case GL_RGB9_E5: case GL_RGBA2: case GL_RGBA4: case GL_RGB5_A1: case GL_RGBA8: case GL_RGBA8_SNORM: case GL_RGB10_A2: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16_SNORM: case GL_RGBA32F: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGB10_A2UI: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA32I: case GL_RGBA32UI: epsilon = 0.0; break; case GL_RGB12: case GL_RGBA12: epsilon = 0.00390625; break; default: TCU_FAIL("Invalid enum"); break; } return epsilon; } /** Get format for given internal format * * @param internal_format Internal format * * @return Format **/ GLenum Utils::getFormat(GLenum internal_format) { GLenum format = 0; switch (internal_format) { /* R */ case GL_R8: case GL_R8_SNORM: case GL_R16: case GL_R16F: case GL_R16_SNORM: case GL_R32F: format = GL_RED; break; case GL_R8I: case GL_R8UI: case GL_R16I: case GL_R16UI: case GL_R32I: case GL_R32UI: format = GL_RED_INTEGER; break; /* RG */ case GL_RG8: case GL_RG8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16_SNORM: case GL_RG32F: format = GL_RG; break; case GL_RG8I: case GL_RG8UI: case GL_RG16I: case GL_RG16UI: case GL_RG32I: case GL_RG32UI: format = GL_RG_INTEGER; break; /* RGB */ case GL_R3_G3_B2: case GL_RGB4: case GL_RGB5: case GL_RGB8: case GL_RGB8_SNORM: case GL_R11F_G11F_B10F: case GL_RGB12: case GL_RGB16: case GL_RGB16F: case GL_RGB16_SNORM: case GL_RGB32F: case GL_RGB9_E5: format = GL_RGB; break; case GL_RGB8I: case GL_RGB8UI: case GL_RGB16I: case GL_RGB16UI: case GL_RGB32I: case GL_RGB32UI: format = GL_RGB_INTEGER; break; /* RGBA */ case GL_RGB10: case GL_RGBA2: case GL_RGBA4: case GL_RGB5_A1: case GL_RGBA8: case GL_RGBA8_SNORM: case GL_RGB10_A2: case GL_RGBA12: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16_SNORM: case GL_RGBA32F: format = GL_RGBA; break; case GL_RGBA8I: case GL_RGBA8UI: case GL_RGB10_A2UI: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA32I: case GL_RGBA32UI: format = GL_RGBA_INTEGER; break; default: TCU_FAIL("Invalid enum"); break; } return format; } /** Get number of channels for given internal_format * * @param internal_format Internal format * * @return Number of channels **/ GLuint Utils::getNumberOfChannels(GLenum internal_format) { GLuint result = 0; switch (internal_format) { case GL_R8: case GL_R8_SNORM: case GL_R16: case GL_R16F: case GL_R16_SNORM: case GL_R32F: case GL_R8I: case GL_R8UI: case GL_R16I: case GL_R16UI: case GL_R32I: case GL_R32UI: result = 1; break; case GL_RG8: case GL_RG8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16_SNORM: case GL_RG32F: case GL_RG8I: case GL_RG8UI: case GL_RG16I: case GL_RG16UI: case GL_RG32I: case GL_RG32UI: result = 2; break; case GL_R3_G3_B2: case GL_RGB4: case GL_RGB5: case GL_RGB8: case GL_RGB8_SNORM: case GL_RGB10: case GL_R11F_G11F_B10F: case GL_RGB12: case GL_RGB16: case GL_RGB16F: case GL_RGB16_SNORM: case GL_RGB32F: case GL_RGB9_E5: case GL_RGB8I: case GL_RGB8UI: case GL_RGB16I: case GL_RGB16UI: case GL_RGB32I: case GL_RGB32UI: result = 3; break; case GL_RGBA2: case GL_RGBA4: case GL_RGB5_A1: case GL_RGBA8: case GL_RGBA8_SNORM: case GL_RGB10_A2: case GL_RGBA12: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16_SNORM: case GL_RGBA32F: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGB10_A2UI: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA32I: case GL_RGBA32UI: result = 4; break; default: TCU_FAIL("Invalid enum"); break; } return result; } /** Get type for given internal format * * @param internal_format Internal format * * @return Type **/ GLenum Utils::getType(GLenum internal_format) { GLenum type = 0; switch (internal_format) { case GL_R8: case GL_R8UI: case GL_RG8: case GL_RG8UI: case GL_RGB8: case GL_RGB8UI: case GL_RGBA8: case GL_RGBA8UI: type = GL_UNSIGNED_BYTE; break; case GL_R8_SNORM: case GL_R8I: case GL_RG8_SNORM: case GL_RG8I: case GL_RGB8_SNORM: case GL_RGB8I: case GL_RGBA8_SNORM: case GL_RGBA8I: type = GL_BYTE; break; case GL_R3_G3_B2: type = GL_UNSIGNED_BYTE_3_3_2; break; case GL_RGB4: case GL_RGB5: type = GL_UNSIGNED_SHORT_5_6_5; break; case GL_RGBA2: case GL_RGBA4: type = GL_UNSIGNED_SHORT_4_4_4_4; break; case GL_RGB5_A1: type = GL_UNSIGNED_SHORT_5_5_5_1; break; case GL_RGB10: case GL_RGB10_A2: case GL_RGB10_A2UI: type = GL_UNSIGNED_INT_2_10_10_10_REV; break; case GL_R16F: case GL_RG16F: case GL_RGB16F: case GL_RGBA16F: type = GL_HALF_FLOAT; break; case GL_R16: case GL_R16UI: case GL_RG16: case GL_RG16UI: case GL_RGB12: case GL_RGB16: case GL_RGB16UI: case GL_RGBA12: case GL_RGBA16: case GL_RGBA16UI: type = GL_UNSIGNED_SHORT; break; case GL_R16_SNORM: case GL_R16I: case GL_RG16_SNORM: case GL_RG16I: case GL_RGB16_SNORM: case GL_RGB16I: case GL_RGBA16_SNORM: case GL_RGBA16I: type = GL_SHORT; break; case GL_R32UI: case GL_RG32UI: case GL_RGB32UI: case GL_RGBA32UI: type = GL_UNSIGNED_INT; break; case GL_RGB9_E5: type = GL_UNSIGNED_INT_5_9_9_9_REV; break; case GL_R32I: case GL_RG32I: case GL_RGB32I: case GL_RGBA32I: type = GL_INT; break; case GL_R32F: case GL_RG32F: case GL_RGB32F: case GL_RGBA32F: type = GL_FLOAT; break; case GL_R11F_G11F_B10F: type = GL_UNSIGNED_INT_10F_11F_11F_REV; break; default: TCU_FAIL("Invalid enum"); break; } return type; } /** Returns mask that should be applied to pixel value * * @param internal_format Internal format of texture * @param pixel Pixel data * * @return Mask **/ void Utils::maskPixelForFormat(GLenum internal_format, GLubyte* pixel) { switch (internal_format) { case GL_RGB10: /* UINT_10_10_10_2 - ALPHA will be set to 3*/ pixel[0] |= 0x03; break; default: break; } } /** Get size of pixel for given internal format * * @param internal_format Internal format * * @return Number of bytes used by given format **/ GLuint Utils::getPixelSizeForFormat(GLenum internal_format) { GLuint size = 0; switch (internal_format) { /* 8 */ case GL_R8: case GL_R8I: case GL_R8UI: case GL_R8_SNORM: case GL_R3_G3_B2: size = 1; break; /* 8 */ case GL_RGBA2: size = 2; break; /* 12 */ case GL_RGB4: size = 2; break; /* 15 */ case GL_RGB5: size = 2; break; /* 16 */ case GL_RG8: case GL_RG8I: case GL_RG8UI: case GL_RG8_SNORM: case GL_R16: case GL_R16F: case GL_R16I: case GL_R16UI: case GL_R16_SNORM: case GL_RGBA4: case GL_RGB5_A1: size = 2; break; /* 24 */ case GL_RGB8: case GL_RGB8I: case GL_RGB8UI: case GL_RGB8_SNORM: size = 3; break; /* 30 */ case GL_RGB10: size = 4; break; /* 32 */ case GL_RGBA8: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGBA8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16I: case GL_RG16UI: case GL_RG16_SNORM: case GL_R32F: case GL_R32I: case GL_R32UI: case GL_RGB10_A2: case GL_RGB10_A2UI: case GL_R11F_G11F_B10F: case GL_RGB9_E5: size = 4; break; /* 36 */ case GL_RGB12: size = 6; break; /* 48 */ case GL_RGB16: case GL_RGB16F: case GL_RGB16I: case GL_RGB16UI: case GL_RGB16_SNORM: size = 6; break; /* 64 */ case GL_RGBA12: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA16_SNORM: case GL_RG32F: case GL_RG32I: case GL_RG32UI: size = 8; break; /* 96 */ case GL_RGB32F: case GL_RGB32I: case GL_RGB32UI: size = 12; break; /* 128 */ case GL_RGBA32F: case GL_RGBA32I: case GL_RGBA32UI: size = 16; break; default: TCU_FAIL("Invalid enum"); break; } return size; } /** Prepare string that represents bytes of pixel * * @param internal_format Format * @param pixel Pixel data * * @return String **/ std::string Utils::getPixelString(GLenum internal_format, const GLubyte* pixel) { const GLuint pixel_size = Utils::getPixelSizeForFormat(internal_format); std::stringstream stream; stream << "0x"; for (GLint i = pixel_size - 1; i >= 0; --i) { stream << std::setbase(16) << std::setw(2) << std::setfill('0') << (GLuint)pixel[i]; } return stream.str(); } /** Check if target supports multiple layers * * @param target Texture target * * @return true if target is multilayered **/ bool Utils::isTargetMultilayer(GLenum target) { bool result = false; switch (target) { case GL_TEXTURE_1D_ARRAY: case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: case GL_TEXTURE_3D: case GL_TEXTURE_CUBE_MAP_ARRAY: result = true; break; default: break; } return result; } /** Check if target supports multiple level * * @param target Texture target * * @return true if target supports mipmaps **/ bool Utils::isTargetMultilevel(GLenum target) { bool result = true; switch (target) { case GL_TEXTURE_2D_MULTISAMPLE: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: case GL_TEXTURE_RECTANGLE: case GL_RENDERBUFFER: result = false; break; default: break; } return result; } /** Check if target is multisampled * * @param target Texture target * * @return true when for multisampled formats, false otherwise **/ bool Utils::isTargetMultisampled(GLenum target) { bool result = false; switch (target) { case GL_TEXTURE_2D_MULTISAMPLE: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: result = true; break; default: break; } return result; } /** Generate texture object * * @param context Test context * @param target Target of texture * * @return Generated name **/ glw::GLuint Utils::generateTexture(deqp::Context& context, GLenum target) { const Functions& gl = context.getRenderContext().getFunctions(); GLuint name = 0; switch (target) { case GL_RENDERBUFFER: gl.genRenderbuffers(1, &name); GLU_EXPECT_NO_ERROR(gl.getError(), "GenRenderbuffers"); break; default: gl.genTextures(1, &name); GLU_EXPECT_NO_ERROR(gl.getError(), "GenTextures"); break; } return name; } /** Sets base and max level parameters of texture to make it complete * * @param context Test context * @param target GLenum representing target of texture that should be created * @param id Id of texture * @param base_level Base level value, eg 0 * @param max_level Max level value, eg 0 **/ void Utils::makeTextureComplete(deqp::Context& context, GLenum target, GLuint id, GLint base_level, GLint max_level) { const Functions& gl = context.getRenderContext().getFunctions(); if (GL_RENDERBUFFER == target) { return; } /* Translate proxies into real targets */ target = transRealToBindTarget(transProxyToRealTarget(target)); gl.bindTexture(target, id); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); /* Set levels */ if (GL_TEXTURE_BUFFER != target) { gl.texParameteri(target, GL_TEXTURE_BASE_LEVEL, base_level); GLU_EXPECT_NO_ERROR(gl.getError(), "TexParameteri"); gl.texParameteri(target, GL_TEXTURE_MAX_LEVEL, max_level); GLU_EXPECT_NO_ERROR(gl.getError(), "TexParameteri"); /* Integer textures won't be complete with the default min filter * of GL_NEAREST_MIPMAP_LINEAR (or GL_LINEAR for rectangle textures) * and default mag filter of GL_LINEAR, so switch to nearest. */ if (GL_TEXTURE_2D_MULTISAMPLE != target && GL_TEXTURE_2D_MULTISAMPLE_ARRAY != target) { gl.texParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (GL_TEXTURE_RECTANGLE != target) { gl.texParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); GLU_EXPECT_NO_ERROR(gl.getError(), "TexParameteri"); } else { gl.texParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GLU_EXPECT_NO_ERROR(gl.getError(), "TexParameteri"); } } } /* Clean binding point */ gl.bindTexture(target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); } /** Generate and initialize texture for given target * * @param context Test context * @param target GLenum representing target of texture that should be created * @param n_samples Number of samples * * @return "name" of texture **/ GLuint Utils::prepareMultisampleTex(deqp::Context& context, GLenum target, GLsizei n_samples) { static const GLuint depth = 6; const Functions& gl = context.getRenderContext().getFunctions(); static const GLuint height = 16; static const GLenum internal_format = GL_RGBA8; GLuint name = 0; static const GLuint width = 16; gl.genTextures(1, &name); GLU_EXPECT_NO_ERROR(gl.getError(), "GenTextures"); /* Initialize */ switch (target) { case GL_TEXTURE_2D_MULTISAMPLE: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage2DMultisample(target, n_samples, internal_format, width, height, GL_FALSE /* fixedsamplelocation */); GLU_EXPECT_NO_ERROR(gl.getError(), "TexImage2DMultisample"); break; case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage3DMultisample(target, n_samples, internal_format, width, height, depth, GL_FALSE /* fixedsamplelocation */); GLU_EXPECT_NO_ERROR(gl.getError(), "TexImage3DMultisample"); break; default: TCU_FAIL("Invalid enum"); break; } /* Clean binding point */ gl.bindTexture(target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); return name; } /** Generate and initialize texture for given target * * @param context Test context * @param internal_format Internal format of render buffer * * @return "name" of texture **/ GLuint Utils::prepareRenderBuffer(deqp::Context& context, GLenum internal_format) { const Functions& gl = context.getRenderContext().getFunctions(); static const GLuint height = 16; GLuint name = 0; static const GLuint width = 16; gl.genRenderbuffers(1, &name); GLU_EXPECT_NO_ERROR(gl.getError(), "GenRenderbuffers"); /* Initialize */ gl.bindRenderbuffer(GL_RENDERBUFFER, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindRenderbuffer"); gl.renderbufferStorage(GL_RENDERBUFFER, internal_format, width, height); GLU_EXPECT_NO_ERROR(gl.getError(), "RenderbufferStorage"); /* Clean binding point */ gl.bindRenderbuffer(GL_RENDERBUFFER, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindRenderbuffer"); return name; } /** Generate and initialize texture for given target * * @param context Test context * @param target GLenum representing target of texture that should be created * @param internal_format <internalformat> * @param format <format> * @param type <type> * @param out_buf_id ID of buffer that will be used for TEXTURE_BUFFER * * @return "name" of texture **/ GLuint Utils::prepareTex16x16x6(deqp::Context& context, GLenum target, GLenum internal_format, GLenum format, GLenum type, GLuint& out_buf_id) { static const GLuint depth = 6; static const GLuint height = 16; static const GLuint level = 0; GLuint name = 0; static const GLchar* pixels = 0; static const GLuint width = 16; name = generateTexture(context, target); prepareTexture(context, name, target, internal_format, format, type, level, width, height, depth, pixels, out_buf_id); return name; } /** Initialize texture * * @param context Test context * @param name Name of texture object * @param target GLenum representing target of texture that should be created * @param internal_format <internalformat> * @param format <format> * @param type <type> * @param level <level> * @param width <width> * @param height <height> * @param depth <depth> * @param pixels <pixels> * @param out_buf_id ID of buffer that will be used for TEXTURE_BUFFER * * @return "name" of texture **/ void Utils::prepareTexture(deqp::Context& context, GLuint name, GLenum target, GLenum internal_format, GLenum format, GLenum type, GLuint level, GLuint width, GLuint height, GLuint depth, const GLvoid* pixels, GLuint& out_buf_id) { static const GLint border = 0; GLenum error = 0; const GLchar* function_name = "unknown"; const Functions& gl = context.getRenderContext().getFunctions(); static const GLsizei samples = 1; /* Translate proxies into real targets */ target = transProxyToRealTarget(target); /* Initialize */ switch (target) { case GL_RENDERBUFFER: gl.bindRenderbuffer(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindRenderbuffer"); gl.renderbufferStorage(target, internal_format, width, height); GLU_EXPECT_NO_ERROR(gl.getError(), "RenderbufferStorage"); gl.bindRenderbuffer(target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindRenderbuffer"); break; case GL_TEXTURE_1D: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage1D(target, level, internal_format, width, border, format, type, pixels); error = gl.getError(); function_name = "TexImage1D"; break; case GL_TEXTURE_1D_ARRAY: case GL_TEXTURE_2D: case GL_TEXTURE_RECTANGLE: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage2D(target, level, internal_format, width, height, border, format, type, pixels); error = gl.getError(); function_name = "TexImage2D"; break; case GL_TEXTURE_2D_MULTISAMPLE: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage2DMultisample(target, samples, internal_format, width, height, GL_FALSE /* fixedsamplelocation */); error = gl.getError(); function_name = "TexImage2DMultisample"; break; case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage3DMultisample(target, samples, internal_format, width, height, depth, GL_FALSE /* fixedsamplelocation */); error = gl.getError(); function_name = "TexImage3DMultisample"; break; case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_3D: case GL_TEXTURE_CUBE_MAP_ARRAY: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage3D(target, level, internal_format, width, height, depth, border, format, type, pixels); error = gl.getError(); function_name = "TexImage3D"; break; case GL_TEXTURE_BUFFER: gl.genBuffers(1, &out_buf_id); GLU_EXPECT_NO_ERROR(gl.getError(), "GenBuffers"); gl.bindBuffer(GL_TEXTURE_BUFFER, out_buf_id); GLU_EXPECT_NO_ERROR(gl.getError(), "BindBuffer"); { GLsizei size = 16; const GLvoid* data = 0; if (0 != pixels) { size = width; data = pixels; } gl.bufferData(GL_TEXTURE_BUFFER, size, data, GL_DYNAMIC_COPY); GLU_EXPECT_NO_ERROR(gl.getError(), "BufferData"); } gl.bindTexture(GL_TEXTURE_BUFFER, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texBuffer(GL_TEXTURE_BUFFER, internal_format, out_buf_id); GLU_EXPECT_NO_ERROR(gl.getError(), "TexBuffer"); break; case GL_TEXTURE_CUBE_MAP: case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: case GL_TEXTURE_CUBE_MAP_POSITIVE_X: case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: /* Change target to CUBE_MAP, it will be used later to change base and max level */ target = GL_TEXTURE_CUBE_MAP; gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, level, internal_format, width, height, border, format, type, pixels); error = gl.getError(); function_name = "TexImage2D"; break; default: TCU_FAIL("Invalid enum"); break; } if (GL_NO_ERROR != error) { context.getTestContext().getLog() << tcu::TestLog::Message << "Error: " << glu::getErrorStr(error) << ". Function: " << function_name << ". Target: " << glu::getTextureTargetStr(target) << ". Format: " << glu::getInternalFormatParameterStr(internal_format) << ", " << glu::getTextureFormatName(format) << ", " << glu::getTypeStr(type) << tcu::TestLog::EndMessage; TCU_FAIL("Failed to create texture"); } if (GL_RENDERBUFFER != target) { /* Clean binding point */ gl.bindTexture(target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); } } /** Translate proxies into real targets * * @param target Target to be converted * * @return Converted target for proxies, <target> otherwise **/ GLenum Utils::transProxyToRealTarget(GLenum target) { switch (target) { case GL_PROXY_TEXTURE_1D: target = GL_TEXTURE_1D; break; case GL_PROXY_TEXTURE_1D_ARRAY: target = GL_TEXTURE_1D_ARRAY; break; case GL_PROXY_TEXTURE_2D: target = GL_TEXTURE_2D; break; case GL_PROXY_TEXTURE_2D_ARRAY: target = GL_TEXTURE_2D_ARRAY; break; case GL_PROXY_TEXTURE_2D_MULTISAMPLE: target = GL_TEXTURE_2D_MULTISAMPLE; break; case GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY: target = GL_TEXTURE_2D_MULTISAMPLE_ARRAY; break; case GL_PROXY_TEXTURE_3D: target = GL_TEXTURE_3D; break; case GL_PROXY_TEXTURE_CUBE_MAP: target = GL_TEXTURE_CUBE_MAP; break; case GL_PROXY_TEXTURE_CUBE_MAP_ARRAY: target = GL_TEXTURE_CUBE_MAP_ARRAY; break; case GL_PROXY_TEXTURE_RECTANGLE: target = GL_TEXTURE_RECTANGLE; break; default: break; } return target; } /** Translate real targets into binding targets * * @param target Target to be converted * * @return Converted target for cube map faces, <target> otherwise **/ GLenum Utils::transRealToBindTarget(GLenum target) { switch (target) { case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_X: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: target = GL_TEXTURE_CUBE_MAP; break; default: break; } return target; } /** Read value of channel * * @tparam T Type used to store channel value * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ template <typename T> void readBaseTypeFromUnsignedChannel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { static const T max = -1; const GLdouble d_max = (GLdouble)max; const T* ptr = (T*)pixel; const T t_value = ptr[channel]; const GLdouble d_value = (GLdouble)t_value; out_value = d_value / d_max; } /** Read value of channel * * @tparam T Type used to store channel value * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ template <typename T> void readBaseTypeFromSignedChannel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { static const GLuint n_bytes = sizeof(T); static const GLuint n_bits = 8u * n_bytes; static const T max = (T)((1u << (n_bits - 1u)) - 1u); const GLdouble d_max = (GLdouble)max; const T* ptr = (T*)pixel; const T t_value = ptr[channel]; const GLdouble d_value = (GLdouble)t_value; out_value = d_value / d_max; } /** Read value of channel * * @tparam T Type used to store channel value * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ void readBaseTypeFromFloatChannel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { const GLfloat* ptr = (const GLfloat*)pixel; const GLfloat t_value = ptr[channel]; const GLdouble d_value = (GLdouble)t_value; out_value = d_value; } /** Read value of channel * * @tparam T Type used to store channel value * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ void readBaseTypeFromHalfFloatChannel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { const deUint16* ptr = (const deUint16*)pixel; const deUint16 bits = ptr[channel]; tcu::Float16 val(bits); const GLdouble d_value = val.asDouble(); out_value = d_value; } /** Read value of channel * * @tparam T Type used to store pixel * @tparam size_1 Size of channel in bits * @tparam size_2 Size of channel in bits * @tparam size_3 Size of channel in bits * @tparam off_1 Offset of channel in bits * @tparam off_2 Offset of channel in bits * @tparam off_3 Offset of channel in bits * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ template <typename T, unsigned int size_1, unsigned int size_2, unsigned int size_3, unsigned int off_1, unsigned int off_2, unsigned int off_3> void read3Channel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { T mask = 0; T max = 0; T off = 0; const T* ptr = (T*)pixel; T result = 0; const T t_value = ptr[0]; static const T max_1 = (1 << size_1) - 1; static const T max_2 = (1 << size_2) - 1; static const T max_3 = (1 << size_3) - 1; switch (channel) { case 0: mask = max_1; max = max_1; off = off_1; break; case 1: mask = max_2; max = max_2; off = off_2; break; case 2: mask = max_3; max = max_3; off = off_3; break; default: TCU_FAIL("Invalid channel"); break; } result = (T)((t_value >> off) & mask); const GLdouble d_max = (GLdouble)max; const GLdouble d_value = (GLdouble)result; out_value = d_value / d_max; } /** Read value of channel * * @tparam T Type used to store pixel * @tparam size_1 Size of channel in bits * @tparam size_2 Size of channel in bits * @tparam size_3 Size of channel in bits * @tparam size_4 Size of channel in bits * @tparam off_1 Offset of channel in bits * @tparam off_2 Offset of channel in bits * @tparam off_3 Offset of channel in bits * @tparam off_4 Offset of channel in bits * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ template <typename T, unsigned int size_1, unsigned int size_2, unsigned int size_3, unsigned int size_4, unsigned int off_1, unsigned int off_2, unsigned int off_3, unsigned int off_4> void read4Channel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { T mask = 0; T max = 0; T off = 0; const T* ptr = (T*)pixel; T result = 0; const T t_value = ptr[0]; static const T max_1 = (1 << size_1) - 1; static const T max_2 = (1 << size_2) - 1; static const T max_3 = (1 << size_3) - 1; static const T max_4 = (1 << size_4) - 1; switch (channel) { case 0: mask = max_1; max = max_1; off = off_1; break; case 1: mask = max_2; max = max_2; off = off_2; break; case 2: mask = max_3; max = max_3; off = off_3; break; case 3: mask = max_4; max = max_4; off = off_4; break; default: TCU_FAIL("Invalid channel"); break; } result = (T)((t_value >> off) & mask); const GLdouble d_max = (GLdouble)max; const GLdouble d_value = (GLdouble)result; out_value = d_value / d_max; } /** Read value of channel * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ void read11F_11F_10F_Channel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { const deUint32* ptr = (deUint32*)pixel; deUint32 val = *ptr; switch (channel) { case 0: { deUint32 bits = (val & 0x000007ff); tcu::Float<deUint32, 5, 6, 15, tcu::FLOAT_SUPPORT_DENORM> temp_val(bits); out_value = temp_val.asDouble(); } break; case 1: { deUint32 bits = ((val >> 11) & 0x000007ff); tcu::Float<deUint32, 5, 6, 15, tcu::FLOAT_SUPPORT_DENORM> temp_val(bits); out_value = temp_val.asDouble(); } break; case 2: { deUint32 bits = ((val >> 22) & 0x000003ff); tcu::Float<deUint32, 5, 5, 15, tcu::FLOAT_SUPPORT_DENORM> temp_val(bits); out_value = temp_val.asDouble(); } break; default: TCU_FAIL("Invalid channel"); break; } } /** Write value of channel * * @tparam T Type used to store pixel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ template <typename T> void writeBaseTypeToUnsignedChannel(GLuint channel, GLdouble value, GLubyte* pixel) { static const T max = -1; const GLdouble d_max = (GLdouble)max; const GLdouble d_value = value * d_max; const T t_value = (T)d_value; T* ptr = (T*)pixel; ptr[channel] = t_value; } /** Write value of channel * * @tparam T Type used to store pixel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ template <typename T> void writeBaseTypeToSignedChannel(GLuint channel, GLdouble value, GLubyte* pixel) { static const GLuint n_bytes = sizeof(T); static const GLuint n_bits = 8u * n_bytes; static const T max = (T)((1u << (n_bits - 1u)) - 1u); const GLdouble d_max = (GLdouble)max; const GLdouble d_value = value * d_max; const T t_value = (T)d_value; T* ptr = (T*)pixel; ptr[channel] = t_value; } /** Write value of channel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ void writeBaseTypeToFloatChannel(GLuint channel, GLdouble value, GLubyte* pixel) { const GLfloat t_value = (GLfloat)value; GLfloat* ptr = (GLfloat*)pixel; ptr[channel] = t_value; } /** Write value of channel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ void writeBaseTypeToHalfFloatChannel(GLuint channel, GLdouble value, GLubyte* pixel) { deUint16* ptr = (deUint16*)pixel; tcu::Float16 val(value); ptr[channel] = val.bits(); } /** Write value of channel * * @tparam T Type used to store pixel * @tparam size_1 Size of channel in bits * @tparam size_2 Size of channel in bits * @tparam size_3 Size of channel in bits * @tparam off_1 Offset of channel in bits * @tparam off_2 Offset of channel in bits * @tparam off_3 Offset of channel in bits * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ template <typename T, unsigned int size_1, unsigned int size_2, unsigned int size_3, unsigned int off_1, unsigned int off_2, unsigned int off_3> void write3Channel(GLuint channel, GLdouble value, GLubyte* pixel) { T mask = 0; T max = 0; T off = 0; T* ptr = (T*)pixel; T result = 0; static const T max_1 = (1 << size_1) - 1; static const T max_2 = (1 << size_2) - 1; static const T max_3 = (1 << size_3) - 1; switch (channel) { case 0: mask = max_1; max = max_1; off = off_1; break; case 1: mask = max_2; max = max_2; off = off_2; break; case 2: mask = max_3; max = max_3; off = off_3; break; default: TCU_FAIL("Invalid channel"); break; } const GLdouble d_max = (GLdouble)max; const GLdouble d_value = value * d_max; const T t_value = (T)d_value; result = (T)((t_value & mask) << off); *ptr |= result; } /** Write value of channel * * @tparam T Type used to store pixel * @tparam size_1 Size of channel in bits * @tparam size_2 Size of channel in bits * @tparam size_3 Size of channel in bits * @tparam size_4 Size of channel in bits * @tparam off_1 Offset of channel in bits * @tparam off_2 Offset of channel in bits * @tparam off_3 Offset of channel in bits * @tparam off_4 Offset of channel in bits * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ template <typename T, unsigned int size_1, unsigned int size_2, unsigned int size_3, unsigned int size_4, unsigned int off_1, unsigned int off_2, unsigned int off_3, unsigned int off_4> void write4Channel(GLuint channel, GLdouble value, GLubyte* pixel) { T mask = 0; T max = 0; T off = 0; T* ptr = (T*)pixel; T result = 0; static const T max_1 = (1 << size_1) - 1; static const T max_2 = (1 << size_2) - 1; static const T max_3 = (1 << size_3) - 1; static const T max_4 = (1 << size_4) - 1; switch (channel) { case 0: mask = max_1; max = max_1; off = off_1; break; case 1: mask = max_2; max = max_2; off = off_2; break; case 2: mask = max_3; max = max_3; off = off_3; break; case 3: mask = max_4; max = max_4; off = off_4; break; default: TCU_FAIL("Invalid channel"); break; } const GLdouble d_max = (GLdouble)max; const GLdouble d_value = value * d_max; const T t_value = (T)d_value; result = (T)((t_value & mask) << off); *ptr |= result; } /** Write value of channel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ void write11F_11F_10F_Channel(GLuint channel, GLdouble value, GLubyte* pixel) { deUint32* ptr = (deUint32*)pixel; switch (channel) { case 0: { tcu::Float<deUint32, 5, 6, 15, tcu::FLOAT_SUPPORT_DENORM> val(value); deUint32 bits = val.bits(); *ptr |= bits; } break; case 1: { tcu::Float<deUint32, 5, 6, 15, tcu::FLOAT_SUPPORT_DENORM> val(value); deUint32 bits = val.bits(); *ptr |= (bits << 11); } break; case 2: { tcu::Float<deUint32, 5, 5, 15, tcu::FLOAT_SUPPORT_DENORM> val(value); deUint32 bits = val.bits(); *ptr |= (bits << 22); } break; default: TCU_FAIL("Invalid channel"); break; } } /** Read value of channel * * @param type Type used by pixel * @param channel Channel index * @param pixel Pixel data * @param value Read value **/ void Utils::readChannel(GLenum type, GLuint channel, const GLubyte* pixel, GLdouble& value) { switch (type) { /* Base types */ case GL_UNSIGNED_BYTE: readBaseTypeFromUnsignedChannel<GLubyte>(channel, pixel, value); break; case GL_UNSIGNED_SHORT: readBaseTypeFromUnsignedChannel<GLushort>(channel, pixel, value); break; case GL_UNSIGNED_INT: readBaseTypeFromUnsignedChannel<GLuint>(channel, pixel, value); break; case GL_BYTE: readBaseTypeFromSignedChannel<GLbyte>(channel, pixel, value); break; case GL_SHORT: readBaseTypeFromSignedChannel<GLshort>(channel, pixel, value); break; case GL_INT: readBaseTypeFromSignedChannel<GLint>(channel, pixel, value); break; case GL_HALF_FLOAT: readBaseTypeFromHalfFloatChannel(channel, pixel, value); break; case GL_FLOAT: readBaseTypeFromFloatChannel(channel, pixel, value); break; /* Complicated */ /* 3 channles */ case GL_UNSIGNED_BYTE_3_3_2: read3Channel<GLubyte, 3, 3, 2, 5, 2, 0>(channel, pixel, value); break; case GL_UNSIGNED_SHORT_5_6_5: read3Channel<GLushort, 5, 6, 5, 11, 5, 0>(channel, pixel, value); break; /* 4 channels */ case GL_UNSIGNED_SHORT_4_4_4_4: read4Channel<GLushort, 4, 4, 4, 4, 12, 8, 4, 0>(channel, pixel, value); break; case GL_UNSIGNED_SHORT_5_5_5_1: read4Channel<GLushort, 5, 5, 5, 1, 11, 6, 1, 0>(channel, pixel, value); break; case GL_UNSIGNED_INT_2_10_10_10_REV: read4Channel<GLuint, 2, 10, 10, 10, 30, 20, 10, 0>(3 - channel, pixel, value); break; case GL_UNSIGNED_INT_5_9_9_9_REV: read4Channel<GLuint, 5, 9, 9, 9, 27, 18, 9, 0>(3 - channel, pixel, value); break; /* R11F_G11F_B10F - uber complicated */ case GL_UNSIGNED_INT_10F_11F_11F_REV: read11F_11F_10F_Channel(channel, pixel, value); break; default: TCU_FAIL("Invalid enum"); break; } } /** Write value of channel * * @param type Type used by pixel * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ void Utils::writeChannel(GLenum type, GLuint channel, GLdouble value, GLubyte* pixel) { switch (type) { /* Base types */ case GL_UNSIGNED_BYTE: writeBaseTypeToUnsignedChannel<GLubyte>(channel, value, pixel); break; case GL_UNSIGNED_SHORT: writeBaseTypeToUnsignedChannel<GLushort>(channel, value, pixel); break; case GL_UNSIGNED_INT: writeBaseTypeToUnsignedChannel<GLuint>(channel, value, pixel); break; case GL_BYTE: writeBaseTypeToSignedChannel<GLbyte>(channel, value, pixel); break; case GL_SHORT: writeBaseTypeToSignedChannel<GLshort>(channel, value, pixel); break; case GL_INT: writeBaseTypeToSignedChannel<GLint>(channel, value, pixel); break; case GL_HALF_FLOAT: writeBaseTypeToHalfFloatChannel(channel, value, pixel); break; case GL_FLOAT: writeBaseTypeToFloatChannel(channel, value, pixel); break; /* Complicated */ /* 3 channles */ case GL_UNSIGNED_BYTE_3_3_2: write3Channel<GLubyte, 3, 3, 2, 5, 2, 0>(channel, value, pixel); break; case GL_UNSIGNED_SHORT_5_6_5: write3Channel<GLushort, 5, 6, 5, 11, 5, 0>(channel, value, pixel); break; /* 4 channels */ case GL_UNSIGNED_SHORT_4_4_4_4: write4Channel<GLushort, 4, 4, 4, 4, 12, 8, 4, 0>(channel, value, pixel); break; case GL_UNSIGNED_SHORT_5_5_5_1: write4Channel<GLushort, 5, 5, 5, 1, 11, 6, 1, 0>(channel, value, pixel); break; case GL_UNSIGNED_INT_2_10_10_10_REV: write4Channel<GLuint, 2, 10, 10, 10, 30, 20, 10, 0>(3 - channel, value, pixel); break; case GL_UNSIGNED_INT_5_9_9_9_REV: write4Channel<GLuint, 5, 9, 9, 9, 27, 18, 9, 0>(3 - channel, value, pixel); break; /* R11F_G11F_B10F - uber complicated */ case GL_UNSIGNED_INT_10F_11F_11F_REV: write11F_11F_10F_Channel(channel, value, pixel); break; default: TCU_FAIL("Invalid enum"); break; } } /** Packs given channels to pixel * * @param internal_format Internal format of image * @param type Type used by image * @param red Red channel * @param green Green channel * @param blue Blue channel * @param alpha Alpha channel * @param out_pixel Pixel data **/ void Utils::packPixel(GLenum internal_format, GLenum type, GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha, GLubyte* out_pixel) { switch (internal_format) { case GL_R8: case GL_R8_SNORM: case GL_R16: case GL_R16F: case GL_R16_SNORM: case GL_R32F: case GL_R8I: case GL_R8UI: case GL_R16I: case GL_R16UI: case GL_R32I: case GL_R32UI: writeChannel(type, 0, red, out_pixel); break; case GL_RG8: case GL_RG8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16_SNORM: case GL_RG32F: case GL_RG8I: case GL_RG8UI: case GL_RG16I: case GL_RG16UI: case GL_RG32I: case GL_RG32UI: writeChannel(type, 0, red, out_pixel); writeChannel(type, 1, green, out_pixel); break; case GL_R3_G3_B2: case GL_RGB4: case GL_RGB5: case GL_RGB8: case GL_RGB8_SNORM: case GL_RGB10: case GL_R11F_G11F_B10F: case GL_RGB12: case GL_RGB16: case GL_RGB16F: case GL_RGB16_SNORM: case GL_RGB32F: case GL_RGB8I: case GL_RGB8UI: case GL_RGB16I: case GL_RGB16UI: case GL_RGB32I: case GL_RGB32UI: writeChannel(type, 0, red, out_pixel); writeChannel(type, 1, green, out_pixel); writeChannel(type, 2, blue, out_pixel); break; case GL_RGB9_E5: case GL_RGBA2: case GL_RGBA4: case GL_RGB5_A1: case GL_RGBA8: case GL_RGBA8_SNORM: case GL_RGB10_A2: case GL_RGBA12: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16_SNORM: case GL_RGBA32F: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGB10_A2UI: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA32I: case GL_RGBA32UI: writeChannel(type, 0, red, out_pixel); writeChannel(type, 1, green, out_pixel); writeChannel(type, 2, blue, out_pixel); writeChannel(type, 3, alpha, out_pixel); break; default: TCU_FAIL("Invalid enum"); break; } } /** Unpacks channels from pixel * * @param internal_format Internal format of image * @param type Type used by image * @param pixel Pixel data * @param red Red channel * @param green Green channel * @param blue Blue channel * @param alpha Alpha channel **/ void Utils::unpackPixel(GLenum format, GLenum type, const GLubyte* pixel, GLdouble& out_red, GLdouble& out_green, GLdouble& out_blue, GLdouble& out_alpha) { switch (format) { case GL_RED: case GL_RED_INTEGER: readChannel(type, 0, pixel, out_red); out_green = 1.0; out_blue = 1.0; out_alpha = 1.0; break; case GL_RG: case GL_RG_INTEGER: readChannel(type, 0, pixel, out_red); readChannel(type, 1, pixel, out_green); out_blue = 1.0; out_alpha = 1.0; break; case GL_RGB: case GL_RGB_INTEGER: switch (type) { case GL_UNSIGNED_INT_5_9_9_9_REV: readChannel(type, 0, pixel, out_red); readChannel(type, 1, pixel, out_green); readChannel(type, 2, pixel, out_blue); readChannel(type, 3, pixel, out_alpha); break; default: readChannel(type, 0, pixel, out_red); readChannel(type, 1, pixel, out_green); readChannel(type, 2, pixel, out_blue); out_alpha = 1.0; break; } break; case GL_RGBA: case GL_RGBA_INTEGER: readChannel(type, 0, pixel, out_red); readChannel(type, 1, pixel, out_green); readChannel(type, 2, pixel, out_blue); readChannel(type, 3, pixel, out_alpha); break; default: TCU_FAIL("Invalid enum"); break; } } inline bool Utils::roundComponent(GLenum internal_format, GLenum component, GLdouble& value) { int exponent = (internal_format == GL_RGB4 ? 4 : (internal_format == GL_RGB5 ? 5 : 0)); if (!exponent) return false; //Currently this only happens with GL_RGB4 and GL_RGB5 when stored as 565 type. int rounded_value = static_cast<int>(floor((pow(2, exponent) - 1) * value + 0.5)); int multiplier = (component == GL_GREEN ? 2 : 1); if (internal_format == GL_RGB4) { multiplier *= 2; } value = rounded_value * multiplier; return true; } /** Unpacks pixels and compars them * * @param left_format Format of left image * @param left_type Type of left image * @param left_internal_format Internal format of left image * @param left_pixel Data of left pixel * @param right_format Format of right image * @param right_type Type of right image * @param right_internal_format Internal format of right image * @param right_pixel Data of right pixel * * @return true if pixels match, false otherwise **/ bool Utils::unpackAndComaprePixels(GLenum left_format, GLenum left_type, GLenum left_internal_format, const GLubyte* left_pixel, GLenum right_format, GLenum right_type, GLenum right_internal_format, const GLubyte* right_pixel) { GLdouble left_red; GLdouble left_green; GLdouble left_blue; GLdouble left_alpha; GLdouble right_red; GLdouble right_green; GLdouble right_blue; GLdouble right_alpha; unpackPixel(left_format, left_type, left_pixel, left_red, left_green, left_blue, left_alpha); unpackPixel(right_format, right_type, right_pixel, right_red, right_green, right_blue, right_alpha); roundComponent(left_internal_format, GL_RED, left_red); roundComponent(left_internal_format, GL_GREEN, left_green); roundComponent(left_internal_format, GL_BLUE, left_blue); roundComponent(right_internal_format, GL_RED, right_red); roundComponent(right_internal_format, GL_GREEN, right_green); roundComponent(right_internal_format, GL_BLUE, right_blue); return comparePixels(left_internal_format, left_red, left_green, left_blue, left_alpha, right_internal_format, right_red, right_green, right_blue, right_alpha); } /* FunctionalTest */ #define FUNCTIONAL_TEST_N_LAYERS 12 #define FUNCTIONAL_TEST_N_LEVELS 3 /** Constructor * * @param context Text context **/ FunctionalTest::FunctionalTest(deqp::Context& context) : TestCase(context, "functional", "Test verifies CopySubImageData copy data as requested") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_rb_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { for (GLuint src_tgt_id = 0; src_tgt_id < s_n_valid_targets; ++src_tgt_id) { const GLenum src_target = s_valid_targets[src_tgt_id]; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS == 0 if ((GL_TEXTURE_1D == src_target) || (GL_TEXTURE_1D_ARRAY == src_target) || (GL_TEXTURE_2D == src_target) || (GL_TEXTURE_CUBE_MAP == src_target) || (GL_TEXTURE_CUBE_MAP_ARRAY == src_target)) { continue; } #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS == 0 */ for (GLuint dst_tgt_id = 0; dst_tgt_id < s_n_valid_targets; ++dst_tgt_id) { const GLenum dst_target = s_valid_targets[dst_tgt_id]; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS == 0 if ((GL_TEXTURE_1D == dst_target) || (GL_TEXTURE_1D_ARRAY == dst_target) || (GL_TEXTURE_2D == dst_target) || (GL_TEXTURE_CUBE_MAP == dst_target) || (GL_TEXTURE_CUBE_MAP_ARRAY == dst_target)) { continue; } #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS == 0 */ /* Skip render buffer as destination */ if (GL_RENDERBUFFER == dst_target) { continue; } /* Skip multisampled */ if ((true == Utils::isTargetMultisampled(src_target)) || (true == Utils::isTargetMultisampled(dst_target))) { continue; } for (GLuint src_frmt_id = 0; src_frmt_id < s_n_internal_formats; ++src_frmt_id) { const GLenum src_format = s_internal_formats[src_frmt_id]; if (src_format == GL_RGB9_E5 && src_target == GL_RENDERBUFFER) { continue; } for (GLuint dst_frmt_id = 0; dst_frmt_id < s_n_internal_formats; ++dst_frmt_id) { const GLenum dst_format = s_internal_formats[dst_frmt_id]; /* Skip not compatible formats */ if (false == Utils::areFormatsCompatible(src_format, dst_format)) { continue; } prepareTestCases(dst_format, dst_target, src_format, src_target); } } } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult FunctionalTest::iterate() { GLubyte* dst_pixels[FUNCTIONAL_TEST_N_LEVELS] = { 0 }; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLubyte* src_pixels[FUNCTIONAL_TEST_N_LEVELS] = { 0 }; const testCase& test_case = m_test_cases[m_test_case_index]; gl.pixelStorei(GL_PACK_ALIGNMENT, 1); gl.pixelStorei(GL_UNPACK_ALIGNMENT, 1); GLU_EXPECT_NO_ERROR(gl.getError(), "PixelStorei"); try { /* Prepare pixels */ prepareDstPxls(test_case.m_dst, dst_pixels); prepareSrcPxls(test_case.m_src, test_case.m_dst.m_internal_format, src_pixels); /* Prepare textures */ m_dst_tex_name = prepareTexture(test_case.m_dst, (const GLubyte**)dst_pixels, m_dst_buf_name); if (GL_RENDERBUFFER == test_case.m_src.m_target) { targetDesc desc = test_case.m_src; desc.m_target = GL_TEXTURE_2D; m_rb_name = prepareTexture(test_case.m_src, (const GLubyte**)src_pixels, m_src_buf_name); m_src_tex_name = prepareTexture(desc, (const GLubyte**)src_pixels, m_src_buf_name); } else { m_src_tex_name = prepareTexture(test_case.m_src, (const GLubyte**)src_pixels, m_src_buf_name); } /* Copy images and verify results */ result = copyAndVerify(test_case, (const GLubyte**)dst_pixels, (const GLubyte**)src_pixels); } catch (tcu::Exception& exc) { clean(); cleanPixels((GLubyte**)dst_pixels); cleanPixels((GLubyte**)src_pixels); throw exc; } /* Free resources */ clean(); cleanPixels((GLubyte**)dst_pixels); cleanPixels((GLubyte**)src_pixels); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. " << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Calculate dimmensions of all levels based on size of specific level * * @param target Target of image * @param level Level index * @param width Width of image at <level> * @param height Height of image at <level> * @param out_widths Calcualted widths, array of FUNCTIONAL_TEST_N_LEVELS'th elements * @param out_heights Calculated heights, array of FUNCTIONAL_TEST_N_LEVELS'th elements * @param out_depths Calculated dephts, array of FUNCTIONAL_TEST_N_LEVELS'th elements **/ void FunctionalTest::calculateDimmensions(GLenum target, GLuint level, GLuint width, GLuint height, GLuint* out_widths, GLuint* out_heights, GLuint* out_depths) const { GLuint divide = 100; GLuint factors[FUNCTIONAL_TEST_N_LEVELS]; GLuint factor = divide; const bool is_multi_layer = Utils::isTargetMultilayer(target); const GLuint n_layers = (true == is_multi_layer) ? FUNCTIONAL_TEST_N_LAYERS : 1; for (GLint i = (GLint)level; i >= 0; --i) { factors[i] = factor; factor *= 2; } factor = divide / 2; for (GLuint i = level + 1; i < FUNCTIONAL_TEST_N_LEVELS; ++i) { factors[i] = factor; factor /= 2; } for (GLuint i = 0; i < FUNCTIONAL_TEST_N_LEVELS; ++i) { out_widths[i] = width * factors[i] / divide; out_heights[i] = height * factors[i] / divide; if (GL_TEXTURE_3D == target) { out_depths[i] = FUNCTIONAL_TEST_N_LAYERS * factors[i] / divide; } else { out_depths[i] = n_layers; } } } /** Execute copyImageSubData for given test case and verify results * * @param test_case Test case * @param dst_pixels Data of destination image * @param src_pixels Data of source image * * @return true if there is no error and results match expectations, false otherwise **/ bool FunctionalTest::copyAndVerify(const testCase& test_case, const GLubyte** dst_pixels, const GLubyte** src_pixels) { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); GLuint region_depth = 1; GLuint dst_layer_step = 0; const bool is_dst_multi_layer = Utils::isTargetMultilayer(test_case.m_dst.m_target); const bool is_src_multi_layer = Utils::isTargetMultilayer(test_case.m_src.m_target); bool result = false; GLuint src_layer_step = 0; GLuint n_layers = 1; /* Configure layers */ if ((true == is_dst_multi_layer) || (true == is_src_multi_layer)) { if (is_src_multi_layer == is_dst_multi_layer) { /* Both objects are multilayered, copy all layers at once, verify at once */ region_depth = FUNCTIONAL_TEST_N_LAYERS; } else if (true == is_dst_multi_layer) { /* Destination is multilayered, copy each layer separetly, verify at once */ n_layers = FUNCTIONAL_TEST_N_LAYERS; dst_layer_step = 1; } else { /* Destination is multilayered, copy and verify each layer separetly */ n_layers = FUNCTIONAL_TEST_N_LAYERS; src_layer_step = 1; } } /* Copy and verification */ { GLuint dst_layer = 0; GLuint src_layer = 0; /* For each layer */ for (GLuint layer = 0; layer < n_layers; ++layer) { if (0 == m_rb_name) { gl.copyImageSubData(m_src_tex_name, test_case.m_src.m_target, test_case.m_src.m_level, test_case.m_src_x, test_case.m_src_y, src_layer, m_dst_tex_name, test_case.m_dst.m_target, test_case.m_dst.m_level, test_case.m_dst_x, test_case.m_dst_y, dst_layer, test_case.m_width, test_case.m_height, region_depth); } else /* Copy from src to rb and from rb to dst */ { /* Src and rb shares differs only on target */ gl.copyImageSubData(m_src_tex_name, GL_TEXTURE_2D, test_case.m_src.m_level, test_case.m_src_x, test_case.m_src_y, src_layer, m_rb_name, test_case.m_src.m_target, test_case.m_src.m_level, test_case.m_src_x, test_case.m_src_y, src_layer, test_case.m_width, test_case.m_height, region_depth); gl.copyImageSubData(m_rb_name, test_case.m_src.m_target, test_case.m_src.m_level, test_case.m_src_x, test_case.m_src_y, src_layer, m_dst_tex_name, test_case.m_dst.m_target, test_case.m_dst.m_level, test_case.m_dst_x, test_case.m_dst_y, dst_layer, test_case.m_width, test_case.m_height, region_depth); } /* Verify generated error */ error = gl.getError(); if (GL_NO_ERROR == error) { /* Verify copy results */ result = verify(test_case, dst_layer, dst_pixels, src_layer, src_pixels, region_depth); } if ((GL_NO_ERROR != error) || (false == result)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Targets src: " << glu::getTextureTargetStr(test_case.m_src.m_target) << ", dst: " << glu::getTextureTargetStr(test_case.m_dst.m_target) << ". Levels src: " << test_case.m_src.m_level << ", dst: " << test_case.m_dst.m_level << ". Dimmensions src [" << test_case.m_src.m_width << ", " << test_case.m_src.m_height << "], dst [" << test_case.m_dst.m_width << ", " << test_case.m_dst.m_height << "]. Region [" << test_case.m_width << " x " << test_case.m_height << " x " << region_depth << "] from [" << test_case.m_src_x << ", " << test_case.m_src_y << ", " << src_layer << "] to [" << test_case.m_dst_x << ", " << test_case.m_dst_y << ", " << dst_layer << "]. Format src: " << glu::getInternalFormatParameterStr(test_case.m_src.m_internal_format) << ", dst: " << glu::getInternalFormatParameterStr(test_case.m_dst.m_internal_format) << tcu::TestLog::EndMessage; if (GL_NO_ERROR != error) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failed due to error: " << glu::getErrorStr(error) << tcu::TestLog::EndMessage; TCU_FAIL("Copy operation failed"); } return false; } /* Step one layer */ dst_layer += dst_layer_step; src_layer += src_layer_step; } } return true; } /** Cleans resources * **/ void FunctionalTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_rb_name) { gl.deleteRenderbuffers(1, &m_rb_name); m_rb_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /** Free memory allocated for images * * @param pixels Array of pointers to image data **/ void FunctionalTest::cleanPixels(GLubyte** pixels) const { for (GLuint i = 0; i < FUNCTIONAL_TEST_N_LEVELS; ++i) { if (0 != pixels[i]) { delete[] pixels[i]; pixels[i] = 0; } } } /** Compare two images * @param left_desc Descriptor of left image * @param left_data Data of left image * @param left_x X of left image * @param left_y Y of left image * @param left_layer Layer of left image * @param left_level Level of left image * @param right_desc Descriptor of right image * @param right_data Data of right image * @param right_x X of right image * @param right_y Y of right image * @param right_layer Layer of right image * @param right_level Level of right image * @param region_width Width of region to compare * @param region_height Height of region to compare * * @return true if images are considered idenctial, false otherwise **/ bool FunctionalTest::compareImages(const targetDesc& left_desc, const GLubyte* left_data, GLuint left_x, GLuint left_y, GLuint left_layer, GLuint left_level, const targetDesc& right_desc, const glw::GLubyte* right_data, GLuint right_x, GLuint right_y, GLuint right_layer, GLuint right_level, GLuint region_width, GLuint region_height) const { /* Get level dimmensions */ GLuint left_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint left_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint left_depths[FUNCTIONAL_TEST_N_LEVELS]; GLuint right_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint right_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint right_depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(left_desc.m_target, left_desc.m_level, left_desc.m_width, left_desc.m_height, left_widths, left_heights, left_depths); calculateDimmensions(right_desc.m_target, right_desc.m_level, right_desc.m_width, right_desc.m_height, right_widths, right_heights, right_depths); /* Constants */ /* Dimmensions */ const GLuint left_height = left_heights[left_level]; const GLuint left_width = left_widths[left_level]; const GLuint right_height = right_heights[right_level]; const GLuint right_width = right_widths[right_level]; /* Sizes */ const GLuint left_pixel_size = Utils::getPixelSizeForFormat(left_desc.m_internal_format); const GLuint left_line_size = left_pixel_size * left_width; const GLuint left_layer_size = left_line_size * left_height; const GLuint right_pixel_size = Utils::getPixelSizeForFormat(right_desc.m_internal_format); const GLuint right_line_size = right_pixel_size * right_width; const GLuint right_layer_size = right_line_size * right_height; /* Offsets */ const GLuint left_layer_offset = left_layer_size * left_layer; const GLuint left_reg_line_offset = left_line_size * left_y; const GLuint left_reg_pix_offset = left_pixel_size * left_x; const GLuint right_layer_offset = right_layer_size * right_layer; const GLuint right_reg_line_offset = right_line_size * right_y; const GLuint right_reg_pix_offset = right_pixel_size * right_x; /* Pointers */ const GLubyte* left_layer_data = left_data + left_layer_offset; const GLubyte* right_layer_data = right_data + right_layer_offset; /* For each line of region */ for (GLuint y = 0; y < region_height; ++y) { /* Offsets */ const GLuint left_line_offset = left_reg_line_offset + y * left_line_size; const GLuint right_line_offset = right_reg_line_offset + y * right_line_size; /* Pointers */ const GLubyte* left_line_data = left_layer_data + left_line_offset; const GLubyte* right_line_data = right_layer_data + right_line_offset; /* For each pixel of region */ for (GLuint x = 0; x < region_width; ++x) { /* Offsets */ const GLuint left_pixel_offset = left_reg_pix_offset + x * left_pixel_size; const GLuint right_pixel_offset = right_reg_pix_offset + x * right_pixel_size; /* Pointers */ const GLubyte* left_pixel_data = left_line_data + left_pixel_offset; const GLubyte* right_pixel_data = right_line_data + right_pixel_offset; /* Compare */ if (false == Utils::comparePixels(left_pixel_size, left_pixel_data, right_pixel_size, right_pixel_data, left_desc.m_internal_format)) { if (false == Utils::unpackAndComaprePixels(left_desc.m_format, left_desc.m_type, left_desc.m_internal_format, left_pixel_data, right_desc.m_format, right_desc.m_type, right_desc.m_internal_format, right_pixel_data)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Not matching pixels found. Left: [" << x + left_x << ", " << y + left_y << ", " << left_layer << "] lvl:" << left_level << ", off: " << left_pixel_data - left_data << ", data: " << Utils::getPixelString(left_desc.m_internal_format, left_pixel_data) << ". Right: [" << x + right_x << ", " << y + right_y << ", " << right_layer << "] lvl: " << right_level << ", off: " << right_pixel_data - right_data << ", data: " << Utils::getPixelString(right_desc.m_internal_format, right_pixel_data) << tcu::TestLog::EndMessage; return false; } } } } return true; } /** Prepare regions that should not be modified during test case * * @param test_case Test case descriptor * @param dst_level Level of destination image * @param out_regions Number of regions * @param out_n_regions Regions **/ void FunctionalTest::getCleanRegions(const testCase& test_case, GLuint dst_level, GLuint out_regions[4][4], GLuint& out_n_regions) const { GLuint dst_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_depths[FUNCTIONAL_TEST_N_LEVELS]; out_n_regions = 0; calculateDimmensions(test_case.m_dst.m_target, dst_level, test_case.m_dst.m_width, test_case.m_dst.m_height, dst_widths, dst_heights, dst_depths); /* Constants */ /* Copied region */ const GLuint reg_x = test_case.m_dst_x; const GLuint reg_y = test_case.m_dst_y; const GLuint reg_w = test_case.m_width; const GLuint reg_h = test_case.m_height; const GLuint reg_r = reg_x + reg_w; const GLuint reg_t = reg_y + reg_h; /* Image */ const GLuint img_w = dst_widths[dst_level]; const GLuint img_h = dst_heights[dst_level]; /* Bottom row */ if (0 != reg_y) { out_regions[out_n_regions][0] = 0; out_regions[out_n_regions][1] = 0; out_regions[out_n_regions][2] = img_w; out_regions[out_n_regions][3] = reg_y; out_n_regions += 1; } /* Left edge */ if (0 != reg_x) { out_regions[out_n_regions][0] = 0; out_regions[out_n_regions][1] = reg_y; out_regions[out_n_regions][2] = reg_x; out_regions[out_n_regions][3] = reg_h; out_n_regions += 1; } /* Right edge */ if (img_w != reg_r) { out_regions[out_n_regions][0] = reg_r; out_regions[out_n_regions][1] = reg_y; out_regions[out_n_regions][2] = img_w - reg_r; out_regions[out_n_regions][3] = reg_h; out_n_regions += 1; } /* Top row */ if (img_h != reg_t) { out_regions[out_n_regions][0] = 0; out_regions[out_n_regions][1] = reg_t; out_regions[out_n_regions][2] = img_w; out_regions[out_n_regions][3] = img_h - reg_t; out_n_regions += 1; } } /** Get pixel data for image * * @param name Name of image * @param desc Descriptor of image * @param level Level to capture * @param out_pixels Pixels **/ void FunctionalTest::getPixels(GLuint name, const targetDesc& desc, GLuint level, GLubyte* out_pixels) const { const Functions& gl = m_context.getRenderContext().getFunctions(); gl.bindTexture(desc.m_target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.getTexImage(desc.m_target, level, desc.m_format, desc.m_type, out_pixels); GLU_EXPECT_NO_ERROR(gl.getError(), "GetTexImage"); gl.bindTexture(desc.m_target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); } /** Prepare data for destination image * * @param desc Descriptor * @param out_pixels Array of pointer to image data **/ void FunctionalTest::prepareDstPxls(const FunctionalTest::targetDesc& desc, GLubyte** out_pixels) const { const GLenum internal_format = desc.m_internal_format; const bool is_multi_level = Utils::isTargetMultilevel(desc.m_target); GLuint n_levels = 1; const GLuint pixel_size = Utils::getPixelSizeForFormat(desc.m_internal_format); const GLenum type = desc.m_type; /* Configure levels */ if (true == is_multi_level) { n_levels = FUNCTIONAL_TEST_N_LEVELS; } /* Calculate dimmensions */ GLuint heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(desc.m_target, desc.m_level, desc.m_width, desc.m_height, widths, heights, depths); /* Prepare storage */ for (GLuint i = 0; i < n_levels; ++i) { const GLuint req_memory_per_layer = pixel_size * widths[i] * heights[i]; const GLuint req_memory_for_level = req_memory_per_layer * depths[i]; out_pixels[i] = new GLubyte[req_memory_for_level]; if (0 == out_pixels[i]) { TCU_FAIL("Memory allocation failed"); } memset(out_pixels[i], 0, req_memory_for_level); } /* Fill pixels */ for (GLuint i = 0; i < n_levels; ++i) { const GLuint n_layers = depths[i]; const GLuint n_pixels = widths[i] * heights[i]; GLubyte* ptr = (GLubyte*)out_pixels[i]; for (GLuint j = 0; j < n_pixels * n_layers; ++j) { GLubyte* pixel_data = ptr + j * pixel_size; Utils::packPixel(internal_format, type, 1.0, 1.0, 1.0, 1.0, pixel_data); } } } /** Prepare data for source image * * @param desc Descriptor * @param dst_internal_format Internal format of destination image * @param out_pixels Array of pointer to image data **/ void FunctionalTest::prepareSrcPxls(const FunctionalTest::targetDesc& desc, GLenum /* dst_internal_format */, GLubyte** out_pixels) const { const GLenum internal_format = desc.m_internal_format; const bool is_multi_level = Utils::isTargetMultilevel(desc.m_target); GLuint n_levels = 1; const GLuint pixel_size = Utils::getPixelSizeForFormat(desc.m_internal_format); const GLenum type = desc.m_type; /* Configure levels */ if (true == is_multi_level) { n_levels = FUNCTIONAL_TEST_N_LEVELS; } /* Calculate dimmensions */ GLuint heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(desc.m_target, desc.m_level, desc.m_width, desc.m_height, widths, heights, depths); /* Prepare storage */ for (GLuint i = 0; i < n_levels; ++i) { const GLuint req_memory_per_layer = pixel_size * widths[i] * heights[i]; const GLuint req_memory_for_level = req_memory_per_layer * depths[i]; out_pixels[i] = new GLubyte[req_memory_for_level]; if (0 == out_pixels[i]) { TCU_FAIL("Memory allocation failed"); } memset(out_pixels[i], 0, req_memory_for_level); } for (GLuint lvl = 0; lvl < n_levels; ++lvl) { const GLuint n_layers = depths[lvl]; const GLuint line_size = pixel_size * widths[lvl]; const GLuint req_memory_per_layer = line_size * heights[lvl]; GLubyte* level = (GLubyte*)out_pixels[lvl]; for (GLuint lay = 0; lay < n_layers; ++lay) { const GLuint layer_offset = lay * req_memory_per_layer; GLubyte* layer = ((GLubyte*)level) + layer_offset; for (GLuint y = 0; y < heights[lvl]; ++y) { const GLuint line_offset = line_size * y; GLubyte* line = layer + line_offset; for (GLuint x = 0; x < widths[lvl]; ++x) { const GLuint pixel_offset = x * pixel_size; GLubyte* pixel = line + pixel_offset; /* 255 is max ubyte. 1/15.9375 = 16/255 */ const GLdouble red = ((GLdouble)x) / 255.0 + (((GLdouble)y) / 15.9375); const GLdouble green = ((GLdouble)lay) / 255.0 + (((GLdouble)lvl) / 15.9375); const GLdouble blue = 0.125; const GLdouble alpha = 1.0; /* This value has special meaning for some internal_formats */ Utils::packPixel(internal_format, type, red, green, blue, alpha, pixel); } } } } } /** Prepare test cases for given targets and internal formats * * @param dst_internal_format Internal format of destination image * @param dst_target Target of destination image * @param src_internal_format Internal format of source image * @param src_target Target of source image **/ void FunctionalTest::prepareTestCases(GLenum dst_internal_format, GLenum dst_target, GLenum src_internal_format, GLenum src_target) { static const GLuint image_dimmensions[] = { 7, #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_IMG_DIM 8, 9, 10, 11, 12, 13, 14, #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_IMG_DIM */ 15 }; static const GLuint region_dimmensions[] = { 1, #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_DIM 2, 3, 4, 5, 6, #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_DIM */ 7 }; static const GLuint n_image_dimmensions = sizeof(image_dimmensions) / sizeof(image_dimmensions[0]); static const GLuint n_region_dimmensions = sizeof(region_dimmensions) / sizeof(region_dimmensions[0]); const bool is_dst_multi_level = Utils::isTargetMultilevel(dst_target); const bool is_src_multi_level = Utils::isTargetMultilevel(src_target); const GLenum dst_format = Utils::getFormat(dst_internal_format); const GLuint dst_n_levels = (true == is_dst_multi_level) ? FUNCTIONAL_TEST_N_LEVELS : 1; const GLenum dst_type = Utils::getType(dst_internal_format); const GLenum src_format = Utils::getFormat(src_internal_format); const GLuint src_n_levels = (true == is_src_multi_level) ? FUNCTIONAL_TEST_N_LEVELS : 1; const GLenum src_type = Utils::getType(src_internal_format); for (GLuint src_level = 0; src_level < src_n_levels; ++src_level) { for (GLuint dst_level = 0; dst_level < dst_n_levels; ++dst_level) { for (GLuint src_img_dim_id = 0; src_img_dim_id < n_image_dimmensions; ++src_img_dim_id) { const GLuint src_image_dimmension = image_dimmensions[src_img_dim_id]; for (GLuint dst_img_dim_id = 0; dst_img_dim_id < n_image_dimmensions; ++dst_img_dim_id) { const GLuint dst_image_dimmension = image_dimmensions[dst_img_dim_id]; for (GLuint reg_dim_id = 0; reg_dim_id < n_region_dimmensions; ++reg_dim_id) { const GLuint region_dimmension = region_dimmensions[reg_dim_id]; GLuint dst_coord[3] = { 0, 0, 0 }; const GLuint dst_dim_diff = dst_image_dimmension - region_dimmension; GLuint n_dst_coords = 1; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS GLuint n_src_coords = 1; #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ GLuint src_coord[3] = { 0, 0, 0 }; const GLuint src_dim_diff = src_image_dimmension - region_dimmension; /* Calculate coords */ if (1 == dst_dim_diff) { dst_coord[1] = 1; n_dst_coords = 2; } else if (1 < dst_dim_diff) { dst_coord[1] = dst_dim_diff / 2; dst_coord[2] = dst_dim_diff; n_dst_coords = 3; } if (1 == src_dim_diff) { src_coord[1] = 1; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS n_src_coords = 2; #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ } else if (1 < src_dim_diff) { src_coord[1] = src_dim_diff / 2; src_coord[2] = src_dim_diff; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS n_src_coords = 3; #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ } testCase test_case = { { /* m_dst */ dst_target, dst_image_dimmension, /* width */ dst_image_dimmension, /* height */ dst_level, dst_internal_format, dst_format, dst_type }, 0, /* dst_x */ 0, /* dst_y */ { /* m_src */ src_target, src_image_dimmension, /* width */ src_image_dimmension, /* height */ src_level, src_internal_format, src_format, src_type }, 0, /* src_x */ 0, /* src_y */ region_dimmension, /* width */ region_dimmension, /* height */ }; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS for (GLuint src_x = 0; src_x < n_src_coords; ++src_x) { for (GLuint src_y = 0; src_y < n_src_coords; ++src_y) { for (GLuint dst_x = 0; dst_x < n_dst_coords; ++dst_x) { for (GLuint dst_y = 0; dst_y < n_dst_coords; ++dst_y) { test_case.m_dst_x = dst_coord[dst_x]; test_case.m_dst_y = dst_coord[dst_y]; test_case.m_src_x = src_coord[src_x]; test_case.m_src_y = src_coord[src_y]; m_test_cases.push_back(test_case); } } } } #else /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ test_case.m_dst_x = dst_coord[n_dst_coords - 1]; test_case.m_dst_y = dst_coord[n_dst_coords - 1]; test_case.m_src_x = src_coord[0]; test_case.m_src_y = src_coord[0]; m_test_cases.push_back(test_case); #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ /* Whole image, for non 7x7 */ if ((dst_image_dimmension == src_image_dimmension) && (image_dimmensions[0] != dst_image_dimmension)) { test_case.m_dst_x = 0; test_case.m_dst_y = 0; test_case.m_src_x = 0; test_case.m_src_y = 0; test_case.m_width = dst_image_dimmension; test_case.m_height = dst_image_dimmension; m_test_cases.push_back(test_case); } } } } } } } /** Prepare texture * * @param desc Descriptor * @param pixels Image data * @param out_buf_id Id of buffer used by texture buffer * * @return Name of iamge **/ GLuint FunctionalTest::prepareTexture(const targetDesc& desc, const GLubyte** pixels, GLuint& out_buf_id) { GLuint name = Utils::generateTexture(m_context, desc.m_target); if (false == Utils::isTargetMultilevel(desc.m_target)) { Utils::prepareTexture(m_context, name, desc.m_target, desc.m_internal_format, desc.m_format, desc.m_type, 0 /* level */, desc.m_width, desc.m_height, FUNCTIONAL_TEST_N_LAYERS /* depth - 12 for multilayered, 1D and 2D will ignore that */, pixels[0], out_buf_id); Utils::makeTextureComplete(m_context, desc.m_target, name, 0 /* base */, 0 /* max */); } else { /* Calculate dimmensions */ GLuint heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(desc.m_target, desc.m_level, desc.m_width, desc.m_height, widths, heights, depths); for (GLuint level = 0; level < FUNCTIONAL_TEST_N_LEVELS; ++level) { Utils::prepareTexture(m_context, name, desc.m_target, desc.m_internal_format, desc.m_format, desc.m_type, level, widths[level], heights[level], depths[level], pixels[level], out_buf_id); Utils::makeTextureComplete(m_context, desc.m_target, name, 0 /* base */, 2 /* max */); } } return name; } /** Verify copy operation * * @param test_case Test case * @param dst_layer First layer modified by copy * @param dst_pixels Origiranl data of destination image * @param src_layer First layer read by copy * @param src_pixels Original data of source image * @param depth Number of copied layers * * @return true if everything is as expected, false otherwise **/ bool FunctionalTest::verify(const testCase& test_case, GLuint dst_layer, const GLubyte** dst_pixels, GLuint src_layer, const GLubyte** src_pixels, GLuint depth) { const bool is_dst_multi_level = Utils::isTargetMultilevel(test_case.m_dst.m_target); const bool is_src_multi_level = Utils::isTargetMultilevel(test_case.m_src.m_target); const GLuint dst_level = test_case.m_dst.m_level; std::vector<GLubyte> dst_level_data; const GLuint dst_pixel_size = Utils::getPixelSizeForFormat(test_case.m_dst.m_internal_format); targetDesc src_desc = test_case.m_src; const GLuint src_level = src_desc.m_level; std::vector<GLubyte> src_level_data; const GLuint src_pixel_size = Utils::getPixelSizeForFormat(src_desc.m_internal_format); if (0 != m_rb_name) { src_desc.m_target = GL_TEXTURE_2D; } /* Calculate storage requirements */ GLuint dst_req_mem_per_layer[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_depths[FUNCTIONAL_TEST_N_LEVELS]; GLuint src_req_mem_per_layer[FUNCTIONAL_TEST_N_LEVELS]; GLuint src_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint src_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint src_depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(test_case.m_dst.m_target, dst_level, test_case.m_dst.m_width, test_case.m_dst.m_height, dst_widths, dst_heights, dst_depths); calculateDimmensions(src_desc.m_target, src_level, src_desc.m_width, src_desc.m_height, src_widths, src_heights, src_depths); for (GLuint i = 0; i < FUNCTIONAL_TEST_N_LEVELS; ++i) { dst_req_mem_per_layer[i] = dst_widths[i] * dst_heights[i] * dst_pixel_size; src_req_mem_per_layer[i] = src_widths[i] * src_heights[i] * src_pixel_size; } /* Prepare storage, use 0 level as it is the biggest one */ dst_level_data.resize(dst_req_mem_per_layer[0] * dst_depths[0]); src_level_data.resize(src_req_mem_per_layer[0] * src_depths[0]); /* Verification of contents * - source image - expect no modification * - destination image, mipmap before and after dst_level - expect no modification * - destination image, mipmap at dst_level: * * layers after dst_layer + depth - expect no modification * * layers <0, dst_layer + depth> - expect that contents at selected region were copied */ /* Check if source image was not modified */ { const GLuint n_levels = (true == is_src_multi_level) ? FUNCTIONAL_TEST_N_LEVELS : 1; for (GLuint level = 0; level < n_levels; ++level) { getPixels(m_src_tex_name, src_desc, level, &src_level_data[0]); for (GLuint layer = 0; layer < src_depths[level]; ++layer) { if (false == compareImages(src_desc, src_pixels[level], 0, 0, layer, level, src_desc, &src_level_data[0], 0, 0, layer, level, src_widths[level], src_heights[level])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents of source image. Original data: left." << tcu::TestLog::EndMessage; return false; } } } } /* Check if contents of destination at levels != dst_level were not modified */ { const GLuint n_levels = (true == is_dst_multi_level) ? FUNCTIONAL_TEST_N_LEVELS : 1; for (GLuint level = 0; level < n_levels; ++level) { if (dst_level == level) { continue; } getPixels(m_dst_tex_name, test_case.m_dst, level, &dst_level_data[0]); for (GLuint layer = 0; layer < dst_depths[level]; ++layer) { if (false == compareImages(test_case.m_dst, dst_pixels[level], 0, 0, layer, level, test_case.m_dst, &dst_level_data[0], 0, 0, layer, level, dst_widths[level], dst_heights[level])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents of wrong mipmap level. Original data: left." << tcu::TestLog::EndMessage; return false; } } } } /* Check contents of modified level */ { getPixels(m_dst_tex_name, test_case.m_dst, dst_level, &dst_level_data[0]); /* Check anything after dst_layer + depth */ { for (GLuint layer = dst_layer + depth; layer < dst_depths[dst_level]; ++layer) { if (false == compareImages(test_case.m_dst, dst_pixels[dst_level], 0, 0, layer, dst_level, test_case.m_dst, &dst_level_data[0], 0, 0, layer, dst_level, dst_widths[dst_level], dst_heights[dst_level])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents of wrong layer. Original data: left." << tcu::TestLog::EndMessage; return false; } } } /* Check modified layers */ for (GLuint layer = 0; layer < depth; ++layer) { /* Check contents outside of copied region */ { GLuint n_regions = 0; GLuint regions[4][4] = { { 0 } }; getCleanRegions(test_case, dst_level, regions, n_regions); for (GLuint region = 0; region < n_regions; ++region) { const GLuint x = regions[region][0]; const GLuint y = regions[region][1]; const GLuint w = regions[region][2]; const GLuint h = regions[region][3]; if (false == compareImages(test_case.m_dst, dst_pixels[dst_level], x, y, layer + dst_layer, dst_level, test_case.m_dst, &dst_level_data[0], x, y, layer + dst_layer, dst_level, w, h)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents outside of copied region. Original data: left." << tcu::TestLog::EndMessage; return false; } } } /* Check contents of copied region */ if (false == compareImages(test_case.m_dst, &dst_level_data[0], test_case.m_dst_x, test_case.m_dst_y, layer + dst_layer, dst_level, src_desc, src_pixels[src_level], test_case.m_src_x, test_case.m_src_y, layer + src_layer, src_level, test_case.m_width, test_case.m_height)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData stored invalid data in copied region. Destination data: left." << tcu::TestLog::EndMessage; return false; } } } return true; } /* SmokeTest */ /* Constants */ const GLuint SmokeTest::m_width = 16; const GLuint SmokeTest::m_height = 16; const GLuint SmokeTest::m_depth = 1; /** Constructor * * @param context Text context **/ SmokeTest::SmokeTest(deqp::Context& context) : TestCase(context, "smoke_test", "Test tries all formats and targets") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_rb_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* Iterate over valid targets */ for (GLuint tgt_id = 0; tgt_id < s_n_valid_targets; ++tgt_id) { const GLenum target = s_valid_targets[tgt_id]; if (true == Utils::isTargetMultisampled(target)) { continue; } const testCase test_case = { target, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT }; m_test_cases.push_back(test_case); } /* Iterate over internal formats */ for (GLuint fmt_id = 0; fmt_id < s_n_internal_formats; ++fmt_id) { const GLenum internal_format = s_internal_formats[fmt_id]; const GLenum format = Utils::getFormat(internal_format); const GLenum type = Utils::getType(internal_format); const testCase test_case = { GL_TEXTURE_2D, internal_format, format, type }; m_test_cases.push_back(test_case); } } /** Cleans resources * **/ void SmokeTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_rb_name) { gl.deleteRenderbuffers(1, &m_rb_name); m_rb_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /** Free memory allocated for images * * @param pixels Pointers to image data **/ void SmokeTest::cleanPixels(GLubyte*& pixels) const { if (0 == pixels) { return; } delete[] pixels; pixels = 0; } /** Compare two images * @param test_case Test case descriptor * @param left_data Data of left image * @param right_data Data of right image * * @return true if images are considered idenctial, false otherwise **/ bool SmokeTest::compareImages(const testCase& test_case, const GLubyte* left_data, const GLubyte* right_data) const { /* Constants */ /* Sizes */ const GLuint pixel_size = Utils::getPixelSizeForFormat(test_case.m_internal_format); const GLuint line_size = pixel_size * m_width; GLuint height = m_height; if ((GL_TEXTURE_1D == test_case.m_target) || (GL_TEXTURE_1D_ARRAY == test_case.m_target)) { height = 1; } /* For each line */ for (GLuint y = 0; y < height; ++y) { /* Offsets */ const GLuint line_offset = y * line_size; /* Pointers */ const GLubyte* left_line_data = left_data + line_offset; const GLubyte* right_line_data = right_data + line_offset; /* For each pixel of region */ for (GLuint x = 0; x < m_width; ++x) { /* Offsets */ const GLuint pixel_offset = x * pixel_size; /* Pointers */ const GLubyte* left_pixel_data = left_line_data + pixel_offset; const GLubyte* right_pixel_data = right_line_data + pixel_offset; /* Compare */ if (false == Utils::comparePixels(pixel_size, left_pixel_data, pixel_size, right_pixel_data, test_case.m_internal_format)) { if (false == Utils::unpackAndComaprePixels( test_case.m_format, test_case.m_type, test_case.m_internal_format, left_pixel_data, test_case.m_format, test_case.m_type, test_case.m_internal_format, right_pixel_data)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Not matching pixels found. " << "[" << x << ", " << y << "], off: " << left_pixel_data - left_data << ". Data left: " << Utils::getPixelString(test_case.m_internal_format, left_pixel_data) << ", right: " << Utils::getPixelString(test_case.m_internal_format, right_pixel_data) << tcu::TestLog::EndMessage; return false; } } } } return true; } /** Execute copyImageSubData for given test case and verify results * * @param test_case Test case * @param src_pixels Data of source image * * @return true if there is no error and results match expectations, false otherwise **/ bool SmokeTest::copyAndVerify(const testCase& test_case, const GLubyte* src_pixels) { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); bool result = false; /* Copy and verification */ { if (0 == m_rb_name) { GLuint height = m_height; if ((GL_TEXTURE_1D == test_case.m_target) || (GL_TEXTURE_1D_ARRAY == test_case.m_target)) { height = 1; } gl.copyImageSubData(m_src_tex_name, test_case.m_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, m_width, height, m_depth); } else /* Copy from src to rb and from rb to dst */ { /* Src and rb shares differs only on target */ gl.copyImageSubData(m_src_tex_name, GL_TEXTURE_2D, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_rb_name, test_case.m_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, m_width, m_height, m_depth); gl.copyImageSubData(m_rb_name, test_case.m_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, m_dst_tex_name, GL_TEXTURE_2D, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, m_width, m_height, m_depth); } /* Verify generated error */ error = gl.getError(); if (GL_NO_ERROR == error) { /* Verify copy results */ result = verify(test_case, src_pixels); } if ((GL_NO_ERROR != error) || (false == result)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Target: " << glu::getTextureTargetStr(test_case.m_target) << ". Format: " << glu::getInternalFormatParameterStr(test_case.m_internal_format) << tcu::TestLog::EndMessage; if (GL_NO_ERROR != error) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failed due to error: " << glu::getErrorStr(error) << tcu::TestLog::EndMessage; TCU_FAIL("Copy operation failed"); } return false; } } return true; } /** Get pixel data for image * * @param name Name of image * @param test_case Test case descriptor * @param out_pixels Pixels **/ void SmokeTest::getPixels(GLuint name, const SmokeTest::testCase& test_case, GLubyte* out_pixels) const { const Functions& gl = m_context.getRenderContext().getFunctions(); GLenum tgt_bind = test_case.m_target; GLenum tgt_get = test_case.m_target; if (GL_RENDERBUFFER == test_case.m_target) { tgt_bind = GL_TEXTURE_2D; tgt_get = GL_TEXTURE_2D; } else if (GL_TEXTURE_CUBE_MAP == test_case.m_target) { tgt_get = GL_TEXTURE_CUBE_MAP_POSITIVE_X; } gl.bindTexture(tgt_bind, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.getTexImage(tgt_get, 0 /* level */, test_case.m_format, test_case.m_type, out_pixels); GLU_EXPECT_NO_ERROR(gl.getError(), "GetTexImage"); gl.bindTexture(tgt_bind, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult SmokeTest::iterate() { GLubyte* dst_pixels = 0; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLubyte* src_pixels = 0; const testCase& test_case = m_test_cases[m_test_case_index]; gl.pixelStorei(GL_PACK_ALIGNMENT, 1); gl.pixelStorei(GL_UNPACK_ALIGNMENT, 1); GLU_EXPECT_NO_ERROR(gl.getError(), "PixelStorei"); try { /* Prepare pixels */ prepareDstPxls(test_case, dst_pixels); prepareSrcPxls(test_case, src_pixels); /* Prepare textures */ if (GL_RENDERBUFFER == test_case.m_target) { testCase desc = test_case; GLuint ignored = 0; desc.m_target = GL_TEXTURE_2D; m_rb_name = prepareTexture(test_case, 0 /* pixels */, ignored /* buffer name */); m_dst_tex_name = prepareTexture(desc, dst_pixels, m_dst_buf_name); m_src_tex_name = prepareTexture(desc, src_pixels, m_src_buf_name); } else { m_dst_tex_name = prepareTexture(test_case, dst_pixels, m_dst_buf_name); m_src_tex_name = prepareTexture(test_case, src_pixels, m_src_buf_name); } /* Copy images and verify results */ result = copyAndVerify(test_case, src_pixels); } catch (tcu::Exception& exc) { clean(); cleanPixels(dst_pixels); cleanPixels(src_pixels); throw exc; } /* Free resources */ clean(); cleanPixels(dst_pixels); cleanPixels(src_pixels); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. " << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Prepare data for destination image * * @param test_case Test case descriptor * @param out_pixels Pointer to image data **/ void SmokeTest::prepareDstPxls(const SmokeTest::testCase& test_case, GLubyte*& out_pixels) const { static const GLuint n_pixels_per_layer = m_width * m_height; const GLenum internal_format = test_case.m_internal_format; const GLuint n_layers = (GL_TEXTURE_CUBE_MAP_ARRAY != test_case.m_target) ? m_depth : 6; const GLuint n_pixels = n_pixels_per_layer * n_layers; const GLuint pixel_size = Utils::getPixelSizeForFormat(internal_format); const GLuint req_memory = pixel_size * n_pixels; const GLenum type = test_case.m_type; /* Prepare storage */ out_pixels = new GLubyte[req_memory]; if (0 == out_pixels) { TCU_FAIL("Memory allocation failed"); } memset(out_pixels, 0, req_memory); /* Fill pixels */ for (GLuint j = 0; j < n_pixels; ++j) { GLubyte* pixel_data = out_pixels + j * pixel_size; Utils::packPixel(internal_format, type, 1.0, 1.0, 1.0, 1.0, pixel_data); } } /** Prepare data for source image * * @param test_case Test case descriptor * @param out_pixels Pointer to image data **/ void SmokeTest::prepareSrcPxls(const SmokeTest::testCase& test_case, GLubyte*& out_pixels) const { static const GLuint n_pixels_per_layer = m_width * m_height; const GLenum internal_format = test_case.m_internal_format; const GLuint n_layers = (GL_TEXTURE_CUBE_MAP_ARRAY != test_case.m_target) ? m_depth : 6; const GLuint n_pixels = n_pixels_per_layer * n_layers; const GLuint pixel_size = Utils::getPixelSizeForFormat(internal_format); const GLuint layer_size = pixel_size * n_pixels_per_layer; const GLuint line_size = pixel_size * m_width; const GLuint req_memory = pixel_size * n_pixels; const GLenum type = test_case.m_type; /* Prepare storage */ out_pixels = new GLubyte[req_memory]; if (0 == out_pixels) { TCU_FAIL("Memory allocation failed"); } memset(out_pixels, 0, req_memory); /* Fill pixels */ for (GLuint layer = 0; layer < n_layers; ++layer) { const GLuint layer_offset = layer * layer_size; GLubyte* layer_data = out_pixels + layer_offset; for (GLuint y = 0; y < m_height; ++y) { const GLuint line_offset = line_size * y; GLubyte* line_data = layer_data + line_offset; for (GLuint x = 0; x < m_width; ++x) { const GLuint pixel_offset = x * pixel_size; GLubyte* pixel_data = line_data + pixel_offset; /* 255 is max ubyte. 1/15.9375 = 16/255 */ const GLdouble red = ((GLdouble)x) / 255.0 + (((GLdouble)y) / 15.9375); const GLdouble green = ((GLdouble)layer) / 255.0 + (1.0 / 15.9375); const GLdouble blue = 0.125; const GLdouble alpha = 1.0; /* This value has special meaning for some internal_formats */ Utils::packPixel(internal_format, type, red, green, blue, alpha, pixel_data); } } } } /** Prepare texture * * @param desc Descriptor * @param pixels Image data * @param out_buf_id Id of buffer used by texture buffer * * @return Name of iamge **/ GLuint SmokeTest::prepareTexture(const testCase& test_case, const GLubyte* pixels, GLuint& out_buf_id) { const GLuint n_layers = (GL_TEXTURE_CUBE_MAP_ARRAY != test_case.m_target) ? m_depth : 6; GLuint name = Utils::generateTexture(m_context, test_case.m_target); Utils::prepareTexture(m_context, name, test_case.m_target, test_case.m_internal_format, test_case.m_format, test_case.m_type, 0 /* level */, m_width, m_height, n_layers, pixels, out_buf_id); Utils::makeTextureComplete(m_context, test_case.m_target, name, 0 /* base */, 0 /* max */); return name; } /** Verify copy operation * * @param test_case Test case * @param src_pixels Original data of source image * * @return true if everything is as expected, false otherwise **/ bool SmokeTest::verify(const testCase& test_case, const GLubyte* src_pixels) { std::vector<GLubyte> dst_data; const GLuint n_layers = (GL_TEXTURE_CUBE_MAP_ARRAY != test_case.m_target) ? m_depth : 6; const GLuint pixel_size = Utils::getPixelSizeForFormat(test_case.m_internal_format); const GLuint line_size = pixel_size * m_width; const GLuint req_memory = line_size * m_height * n_layers; std::vector<GLubyte> src_data; /* Prepare storage */ dst_data.resize(req_memory); src_data.resize(req_memory); /* Check if source image was not modified */ { getPixels(m_src_tex_name, test_case, &src_data[0]); if (false == compareImages(test_case, src_pixels, &src_data[0])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents of source image. Original data: left." << tcu::TestLog::EndMessage; return false; } } /* Check contents of destination image */ { getPixels(m_dst_tex_name, test_case, &dst_data[0]); if (false == compareImages(test_case, src_pixels, &dst_data[0])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData stored invalid contents in destination image. Source data: left." << tcu::TestLog::EndMessage; return false; } } return true; } /* InvalidTargetTest */ /** Constructor * * @param context Text context **/ InvalidTargetTest::InvalidTargetTest(deqp::Context& context) : TestCase(context, "invalid_target", "Test verifies if INVALID_ENUM is generated when invalid target is provided to CopySubImageData") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* Valid source, valid dst */ for (GLuint src = 0; src < s_n_valid_targets; ++src) { for (GLuint dst = 0; dst < s_n_valid_targets; ++dst) { const GLenum src_target = s_valid_targets[src]; const GLenum dst_target = s_valid_targets[dst]; testCase test_case = { src_target, dst_target, GL_NO_ERROR }; if (Utils::isTargetMultisampled(dst_target) != Utils::isTargetMultisampled(src_target)) { test_case.m_expected_result = GL_INVALID_OPERATION; } m_test_cases.push_back(test_case); } } /* Invalid source, invalid dst */ for (GLuint src = 0; src < s_n_invalid_targets; ++src) { for (GLuint dst = 0; dst < s_n_invalid_targets; ++dst) { const GLenum src_target = s_invalid_targets[src]; const GLenum dst_target = s_invalid_targets[dst]; const testCase test_case = { src_target, dst_target, GL_INVALID_ENUM }; m_test_cases.push_back(test_case); } } /* Invalid source, valid dst */ for (GLuint src = 0; src < s_n_invalid_targets; ++src) { for (GLuint dst = 0; dst < s_n_valid_targets; ++dst) { const GLenum src_target = s_invalid_targets[src]; const GLenum dst_target = s_valid_targets[dst]; const testCase test_case = { src_target, dst_target, GL_INVALID_ENUM }; m_test_cases.push_back(test_case); } } /* Valid source, invalid dst */ for (GLuint src = 0; src < s_n_valid_targets; ++src) { for (GLuint dst = 0; dst < s_n_invalid_targets; ++dst) { const GLenum src_target = s_valid_targets[src]; const GLenum dst_target = s_invalid_targets[dst]; const testCase test_case = { src_target, dst_target, GL_INVALID_ENUM }; m_test_cases.push_back(test_case); } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult InvalidTargetTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_dst_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_dst_buf_name); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_src_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_src_buf_name); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_dst_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_src_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_src_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_dst_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Source target: " << glu::getTextureTargetStr(test_case.m_src_target) << ", destination target: " << glu::getTextureTargetStr(test_case.m_dst_target) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void InvalidTargetTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); const testCase& test_case = m_test_cases[m_test_case_index]; /* Clean textures and buffers. Errors ignored */ Utils::deleteTexture(m_context, test_case.m_dst_target, m_dst_tex_name); Utils::deleteTexture(m_context, test_case.m_src_target, m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /* TargetMissMatchTest */ /** Constructor * * @param context Text context **/ TargetMissMatchTest::TargetMissMatchTest(deqp::Context& context) : TestCase( context, "target_miss_match", "Test verifies if INVALID_ENUM is generated when target provided to CopySubImageData does not match texture") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* Wrong dst target */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { for (GLuint dst = 0; dst < s_n_valid_targets; ++dst) { const GLenum dst_target = s_valid_targets[dst]; const GLenum src_target = s_valid_targets[target]; const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, src_target, dst_target, GL_INVALID_ENUM }; /* Skip renderbuffers */ if ((GL_RENDERBUFFER == tex_target) || (GL_RENDERBUFFER == dst_target) || (GL_RENDERBUFFER == src_target)) { continue; } /* Valid case */ if (dst_target == tex_target) { test_case.m_expected_result = GL_NO_ERROR; } /* Skip cases with multisampling conflict */ if (Utils::isTargetMultisampled(dst_target) != Utils::isTargetMultisampled(src_target)) { continue; } m_test_cases.push_back(test_case); } } /* Wrong src target */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { for (GLuint src = 0; src < s_n_valid_targets; ++src) { const GLenum dst_target = s_valid_targets[target]; const GLenum src_target = s_valid_targets[src]; const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, src_target, dst_target, GL_INVALID_ENUM }; /* Skip renderbuffers */ if ((GL_RENDERBUFFER == tex_target) || (GL_RENDERBUFFER == dst_target) || (GL_RENDERBUFFER == src_target)) { continue; } /* Valid case */ if (src_target == tex_target) { test_case.m_expected_result = GL_NO_ERROR; } /* Skip cases with multisampling conflict */ if (Utils::isTargetMultisampled(dst_target) != Utils::isTargetMultisampled(src_target)) { continue; } m_test_cases.push_back(test_case); } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult TargetMissMatchTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_dst_buf_name); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_src_buf_name); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_src_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_dst_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ". Source target: " << glu::getTextureTargetStr(test_case.m_src_target) << ", destination target: " << glu::getTextureTargetStr(test_case.m_dst_target) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void TargetMissMatchTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /* TargetMissMatchTest */ /** Constructor * * @param context Text context **/ IncompleteTexTest::IncompleteTexTest(deqp::Context& context) : TestCase( context, "incomplete_tex", "Test verifies if INVALID_OPERATION is generated when texture provided to CopySubImageData is incomplete") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, false, false, GL_INVALID_OPERATION }; /* Skip targets that are not multi level */ if (false == Utils::isTargetMultilevel(tex_target)) { continue; } m_test_cases.push_back(test_case); test_case.m_is_dst_complete = true; test_case.m_is_src_complete = false; m_test_cases.push_back(test_case); test_case.m_is_dst_complete = false; test_case.m_is_src_complete = true; m_test_cases.push_back(test_case); test_case.m_is_dst_complete = true; test_case.m_is_src_complete = true; test_case.m_expected_result = GL_NO_ERROR; m_test_cases.push_back(test_case); } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult IncompleteTexTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_dst_buf_name); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_src_buf_name); /* Make textures complete */ if (true == test_case.m_is_dst_complete) { Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); } if (true == test_case.m_is_src_complete) { Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_tex_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ". Is source complete: " << test_case.m_is_src_complete << ", is destination complete: " << test_case.m_is_dst_complete << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void IncompleteTexTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /* IncompatibleFormatsTest */ /** Constructor * * @param context Text context **/ IncompatibleFormatsTest::IncompatibleFormatsTest(deqp::Context& context) : TestCase( context, "incompatible_formats", "Test verifies if INVALID_OPERATION is generated when textures provided to CopySubImageData are incompatible") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* RGBA8UI vs RGBA16UI */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_INVALID_OPERATION }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } /* RGBA8UI vs RGBA32UI */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_INVALID_OPERATION }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } /* RGBA16UI vs RG16UI */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT, GL_INVALID_OPERATION }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } /* RGBA32UI vs RGBA32F */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_RGBA32F, GL_RGBA, GL_FLOAT, GL_NO_ERROR }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } /* RGBA8 vs RGBA32F */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA32F, GL_RGBA, GL_FLOAT, GL_INVALID_OPERATION }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult IncompatibleFormatsTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, test_case.m_dst_internal_format, test_case.m_dst_format, test_case.m_dst_type, m_dst_buf_name); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, test_case.m_src_internal_format, test_case.m_src_format, test_case.m_src_type, m_src_buf_name); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_tex_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ". Source format: " << glu::getInternalFormatParameterStr(test_case.m_src_internal_format) << ". Destination format: " << glu::getInternalFormatParameterStr(test_case.m_dst_internal_format) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void IncompatibleFormatsTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); const testCase& test_case = m_test_cases[m_test_case_index]; /* Clean textures and buffers. Errors ignored */ Utils::deleteTexture(m_context, test_case.m_tex_target, m_dst_tex_name); Utils::deleteTexture(m_context, test_case.m_tex_target, m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /* InvalidTargetTest */ /** Constructor * * @param context Text context **/ SamplesMissMatchTest::SamplesMissMatchTest(deqp::Context& context) : TestCase(context, "samples_missmatch", "Test verifies if INVALID_OPERATION is generated when textures provided " "to CopySubImageData have different number of samples") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { testCase test_case; static const GLsizei n_samples[2] = { 1, 4 }; static const GLenum targets[2] = { GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_2D_MULTISAMPLE_ARRAY }; for (GLuint src_sample = 0; src_sample < 2; ++src_sample) { for (GLuint dst_sample = 0; dst_sample < 2; ++dst_sample) { for (GLuint src_target = 0; src_target < 2; ++src_target) { for (GLuint dst_target = 0; dst_target < 2; ++dst_target) { test_case.m_src_target = targets[src_target]; test_case.m_src_n_samples = n_samples[src_sample]; test_case.m_dst_target = targets[dst_target]; test_case.m_dst_n_samples = n_samples[dst_sample]; if (test_case.m_src_n_samples == test_case.m_dst_n_samples) { test_case.m_expected_result = GL_NO_ERROR; } else { test_case.m_expected_result = GL_INVALID_OPERATION; } m_test_cases.push_back(test_case); } } } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult SamplesMissMatchTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareMultisampleTex(m_context, test_case.m_dst_target, test_case.m_dst_n_samples); m_src_tex_name = Utils::prepareMultisampleTex(m_context, test_case.m_src_target, test_case.m_src_n_samples); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_src_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_dst_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Source target: " << glu::getTextureTargetStr(test_case.m_src_target) << " samples: " << test_case.m_src_n_samples << ", destination target: " << glu::getTextureTargetStr(test_case.m_dst_target) << " samples: " << test_case.m_dst_n_samples << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void SamplesMissMatchTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures . Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } /* IncompatibleFormatsCompressionTest */ /** Constructor * * @param context Text context **/ IncompatibleFormatsCompressionTest::IncompatibleFormatsCompressionTest(deqp::Context& context) : TestCase(context, "incompatible_formats_compression", "Test verifies if INVALID_OPERATION is generated when " "textures provided to CopySubImageData are incompatible, " "one of formats is compressed") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; /* Skip 1D targets, not supported */ if ((GL_TEXTURE_1D == tex_target) || (GL_TEXTURE_1D_ARRAY == tex_target) || (GL_TEXTURE_3D == tex_target) || (GL_TEXTURE_RECTANGLE == tex_target) || (GL_RENDERBUFFER == tex_target)) { continue; } /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } /* Compressed 128bit vs RGBA32UI */ { testCase test_case = { tex_target, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, GL_NO_ERROR }; m_test_cases.push_back(test_case); } /* Compressed 128bit vs RGBA16UI */ { testCase test_case = { tex_target, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, GL_INVALID_OPERATION }; m_test_cases.push_back(test_case); } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult IncompatibleFormatsCompressionTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, test_case.m_dst_internal_format, test_case.m_dst_format, test_case.m_dst_type, temp); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, test_case.m_src_internal_format, test_case.m_src_format, test_case.m_src_type, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_tex_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 4 /* srcWidth */, 4 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ". Source format: " << glu::getInternalFormatParameterStr(test_case.m_src_internal_format) << ". Destination format: " << glu::getInternalFormatParameterStr(test_case.m_dst_internal_format) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void IncompatibleFormatsCompressionTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } /* MissMatchObjectTest */ /** Constructor * * @param context Text context **/ MissMatchObjectTest::MissMatchObjectTest(deqp::Context& context) : TestCase( context, "missmatch_object", "Test verifies if INVALID_VALUE is generated when object & target provided to CopySubImageData do not match") , m_dst_name(0) , m_src_name(0) , m_test_case_index(0) { static const testCase test_cases[] = { { GL_TEXTURE_2D, GL_TEXTURE_2D, GL_TEXTURE_2D, GL_NO_ERROR }, { GL_TEXTURE_2D, GL_RENDERBUFFER, GL_TEXTURE_2D, GL_INVALID_VALUE }, { GL_TEXTURE_2D, GL_TEXTURE_2D, GL_RENDERBUFFER, GL_INVALID_VALUE }, { GL_TEXTURE_2D, GL_RENDERBUFFER, GL_RENDERBUFFER, GL_INVALID_VALUE }, { GL_RENDERBUFFER, GL_TEXTURE_2D, GL_TEXTURE_2D, GL_INVALID_VALUE }, { GL_RENDERBUFFER, GL_RENDERBUFFER, GL_TEXTURE_2D, GL_INVALID_VALUE }, { GL_RENDERBUFFER, GL_TEXTURE_2D, GL_RENDERBUFFER, GL_INVALID_VALUE }, { GL_RENDERBUFFER, GL_RENDERBUFFER, GL_RENDERBUFFER, GL_NO_ERROR } }; static const GLuint n_test_cases = sizeof(test_cases) / sizeof(testCase); for (GLuint i = 0; i < n_test_cases; ++i) { const testCase& test_case = test_cases[i]; m_test_cases.push_back(test_case); } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult MissMatchObjectTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare objects */ if (GL_RENDERBUFFER == test_case.m_obj_target) { m_dst_name = Utils::prepareRenderBuffer(m_context, GL_RGBA8); m_src_name = Utils::prepareRenderBuffer(m_context, GL_RGBA8); } else { m_dst_name = Utils::prepareTex16x16x6(m_context, test_case.m_obj_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); m_src_name = Utils::prepareTex16x16x6(m_context, test_case.m_obj_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_obj_target, m_dst_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_obj_target, m_src_name, 0 /* base */, 0 /* max */); } } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_name, test_case.m_src_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_name, test_case.m_dst_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Object target: " << glu::getTextureTargetStr(test_case.m_obj_target) << ". Source target: " << glu::getTextureTargetStr(test_case.m_src_target) << ". Destination target: " << glu::getTextureTargetStr(test_case.m_dst_target) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void MissMatchObjectTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); const testCase& test_case = m_test_cases[m_test_case_index]; /* Clean textures or renderbuffers. Errors ignored */ if (GL_RENDERBUFFER == test_case.m_obj_target) { gl.deleteRenderbuffers(1, &m_dst_name); gl.deleteRenderbuffers(1, &m_src_name); } else { gl.deleteTextures(1, &m_dst_name); gl.deleteTextures(1, &m_src_name); } m_dst_name = 0; m_src_name = 0; } /* NonExistentMipMapTest */ /** Constructor * * @param context Text context **/ NonExistentMipMapTest::NonExistentMipMapTest(deqp::Context& context) : TestCase(context, "non_existent_mipmap", "Test verifies if INVALID_VALUE is generated when CopySubImageData is " "executed for mipmap that does not exist") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, 0, 0, GL_NO_ERROR }; if (GL_RENDERBUFFER == tex_target) { continue; } m_test_cases.push_back(test_case); /* Rest of cases is invalid */ test_case.m_expected_result = GL_INVALID_VALUE; test_case.m_dst_level = 1; test_case.m_src_level = 0; m_test_cases.push_back(test_case); test_case.m_dst_level = 0; test_case.m_src_level = 1; m_test_cases.push_back(test_case); test_case.m_dst_level = 1; test_case.m_src_level = 1; m_test_cases.push_back(test_case); } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult NonExistentMipMapTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, test_case.m_src_level, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_tex_target, test_case.m_dst_level, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ", source level: " << test_case.m_src_level << ", destination level: " << test_case.m_dst_level << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void NonExistentMipMapTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } /* ExceedingBoundariesTest */ const glw::GLuint ExceedingBoundariesTest::m_region_depth = 4; const glw::GLuint ExceedingBoundariesTest::m_region_height = 4; const glw::GLuint ExceedingBoundariesTest::m_region_width = 4; /** Constructor * * @param context Text context **/ ExceedingBoundariesTest::ExceedingBoundariesTest(deqp::Context& context) : TestCase(context, "exceeding_boundaries", "Test verifies if INVALID_VALUE is generated when CopySubImageData is " "executed for regions exceeding image boundaries") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* 16x16x6 are values used by prepareTex16x16x6 */ static const GLuint invalid_x = 16 - (m_region_width / 2); static const GLuint invalid_y = 16 - (m_region_height / 2); static const GLuint invalid_z = 6 - (m_region_depth / 2); static const GLuint x_vals[] = { 0, invalid_x }; static const GLuint y_vals[] = { 0, invalid_y }; static const GLuint z_vals[] = { 0, invalid_z }; static const GLuint n_x_vals = sizeof(x_vals) / sizeof(x_vals[0]); static const GLuint n_y_vals = sizeof(y_vals) / sizeof(y_vals[0]); static const GLuint n_z_vals = sizeof(z_vals) / sizeof(z_vals[0]); for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; GLuint height = m_region_height; if (GL_TEXTURE_BUFFER == tex_target) { continue; } if ((GL_TEXTURE_1D == tex_target) || (GL_TEXTURE_1D_ARRAY == tex_target)) { height = 1; } for (GLuint x = 0; x < n_x_vals; ++x) { for (GLuint y = 0; y < n_y_vals; ++y) { for (GLuint z = 0; z < n_z_vals; ++z) { const GLuint x_val = x_vals[x]; const GLuint y_val = y_vals[y]; const GLuint z_val = z_vals[z]; const GLenum res = ((0 == x_val) && (0 == y_val) && (0 == z_val)) ? GL_NO_ERROR : GL_INVALID_VALUE; GLuint depth = 1; if (0 != z_val) { if ((GL_TEXTURE_2D_ARRAY != tex_target) || (GL_TEXTURE_2D_MULTISAMPLE_ARRAY != tex_target) || (GL_TEXTURE_3D != tex_target) || (GL_TEXTURE_CUBE_MAP_ARRAY != tex_target)) { /* Skip z != 0 for 2d textures */ continue; } else { /* Set depth so as to exceed boundary */ depth = m_region_depth; } } testCase src_test_case = { tex_target, depth, height, x_val, y_val, z_val, 0, 0, 0, res }; testCase dst_test_case = { tex_target, depth, height, 0, 0, 0, x_val, y_val, z_val, res }; m_test_cases.push_back(src_test_case); m_test_cases.push_back(dst_test_case); } } } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult ExceedingBoundariesTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, 0 /* level */, test_case.m_src_x /* srcX */, test_case.m_src_y /* srcY */, test_case.m_src_z /* srcZ */, m_dst_tex_name, test_case.m_tex_target, 0 /* level */, test_case.m_dst_x /* dstX */, test_case.m_dst_y /* dstY */, test_case.m_dst_z /* dstZ */, m_region_width /* srcWidth */, test_case.m_height /* srcHeight */, test_case.m_depth /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ", source: [" << test_case.m_src_x << ", " << test_case.m_src_y << ", " << test_case.m_src_z << "], destination: [" << test_case.m_src_x << ", " << test_case.m_src_y << ", " << test_case.m_src_z << "], depth: " << test_case.m_depth << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void ExceedingBoundariesTest::clean() { const testCase& test_case = m_test_cases[m_test_case_index]; /* Clean textures and buffers. Errors ignored */ Utils::deleteTexture(m_context, test_case.m_tex_target, m_dst_tex_name); Utils::deleteTexture(m_context, test_case.m_tex_target, m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } /* InvalidAlignmentTest */ /** Constructor * * @param context Text context **/ InvalidAlignmentTest::InvalidAlignmentTest(deqp::Context& context) : TestCase(context, "invalid_alignment", "Test verifies if INVALID_VALUE is generated when CopySubImageData is " "executed for regions with invalid alignment") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* 16x16x6 are values used by prepareTex16x16x6 */ static const GLuint invalid_h = 2; static const GLuint invalid_w = 2; static const GLuint invalid_x = 2; static const GLuint invalid_y = 2; static const GLuint valid_h = 4; static const GLuint valid_w = 4; static const GLuint h_vals[] = { valid_h, invalid_h }; static const GLuint w_vals[] = { valid_w, invalid_w }; static const GLuint x_vals[] = { 0, invalid_x }; static const GLuint y_vals[] = { 0, invalid_y }; static const GLuint n_h_vals = sizeof(h_vals) / sizeof(h_vals[0]); static const GLuint n_w_vals = sizeof(w_vals) / sizeof(w_vals[0]); static const GLuint n_x_vals = sizeof(x_vals) / sizeof(x_vals[0]); static const GLuint n_y_vals = sizeof(y_vals) / sizeof(y_vals[0]); for (GLuint x = 0; x < n_x_vals; ++x) { for (GLuint y = 0; y < n_y_vals; ++y) { for (GLuint h = 0; h < n_h_vals; ++h) { for (GLuint w = 0; w < n_w_vals; ++w) { const GLuint h_val = h_vals[h]; const GLuint w_val = w_vals[w]; const GLuint x_val = x_vals[x]; const GLuint y_val = y_vals[y]; const GLenum res = ((valid_h == h_val) && (valid_w == w_val) && (0 == x_val) && (0 == y_val)) ? GL_NO_ERROR : GL_INVALID_VALUE; testCase dst_test_case = { h_val, w_val, 0, 0, x_val, y_val, res }; testCase src_test_case = { h_val, w_val, x_val, y_val, 0, 0, res }; m_test_cases.push_back(dst_test_case); m_test_cases.push_back(src_test_case); } } } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult InvalidAlignmentTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, GL_TEXTURE_2D, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, temp); m_src_tex_name = Utils::prepareTex16x16x6(m_context, GL_TEXTURE_2D, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, GL_TEXTURE_2D, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, GL_TEXTURE_2D, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, GL_TEXTURE_2D, 0 /* level */, test_case.m_src_x /* srcX */, test_case.m_src_y /* srcY */, 0 /* srcZ */, m_dst_tex_name, GL_TEXTURE_2D, 0 /* level */, test_case.m_dst_x /* dstX */, test_case.m_dst_y /* dstY */, 0 /* dstZ */, test_case.m_width /* srcWidth */, test_case.m_height /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". source: [" << test_case.m_src_x << ", " << test_case.m_src_y << "], destination: [" << test_case.m_src_x << ", " << test_case.m_src_y << "], size: " << test_case.m_width << " x " << test_case.m_height << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void InvalidAlignmentTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } } /* namespace CopyImage */ CopyImageTests::CopyImageTests(deqp::Context& context) : TestCaseGroup(context, "copy_image", "") { } CopyImageTests::~CopyImageTests(void) { } void CopyImageTests::init() { addChild(new CopyImage::FunctionalTest(m_context)); addChild(new CopyImage::IncompleteTexTest(m_context)); addChild(new CopyImage::MissMatchObjectTest(m_context)); addChild(new CopyImage::SmokeTest(m_context)); addChild(new CopyImage::InvalidTargetTest(m_context)); addChild(new CopyImage::TargetMissMatchTest(m_context)); addChild(new CopyImage::IncompatibleFormatsTest(m_context)); addChild(new CopyImage::SamplesMissMatchTest(m_context)); addChild(new CopyImage::IncompatibleFormatsCompressionTest(m_context)); addChild(new CopyImage::NonExistentMipMapTest(m_context)); addChild(new CopyImage::ExceedingBoundariesTest(m_context)); addChild(new CopyImage::InvalidAlignmentTest(m_context)); } } /* namespace gl4cts */ copy_image test: do not require compressed formats on CM_ARRAY Spec: "An INVALID_OPERATION error is generated by TexImage3D if internalformat is one of the EAC, ETC2, or RGTC compressed formats and either border is non-zero, or target is not TEXTURE_2D_ARRAY." Affects: GL44-CTS.copy_image.incompatible_formats_compression Components: OpenGL VK-GL-CTS issue: 352 Change-Id: I77cbc09c2383d7d055776e1665f25b8c6051ee7d /*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2015-2016 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file * \brief */ /*-------------------------------------------------------------------*/ #include "gl4cCopyImageTests.hpp" #include "gluDefs.hpp" #include "gluStrUtil.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuFloat.hpp" #include "tcuTestLog.hpp" #include <algorithm> #include <iomanip> #include <sstream> #include "deMath.h" /* There are far too much combinations specified for FunctionalTest. * * Following flags controls what is enabled. Set as 1 to enable * all test case from given category, 0 otherwise. * * By default everything is disabled - which still gives 14560 test cases. * * ALL_FORMAT - selects all internal formats, 61 x 61 * ALL_TARGETS - selects all valid targets, 10 x 10 * ALL_IMG_DIM - selects all image dimmensions, 9 x 9 * ALL_REG_DIM - selects all region dimmensions, 7 x 7 * ALL_REG_POS - selects all region positions, like left-top corner, 8 x 8 */ #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS 0 #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS 0 #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_IMG_DIM 0 #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_DIM 0 #define COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS 0 /* The following flags controls if workarounds are enabled */ #define COPY_IMAGE_WRKARD_FORMATS 0 using namespace glw; namespace gl4cts { namespace CopyImage { /** Various utilities used by all tests * **/ class Utils { public: /* Routines */ static bool areFormatsCompatible(glw::GLenum src, glw::GLenum dst); static bool comparePixels(glw::GLenum left_internal_format, const glw::GLdouble& left_red, const glw::GLdouble& left_green, const glw::GLdouble& left_blue, const glw::GLdouble& left_alpha, glw::GLenum right_internal_format, const glw::GLdouble& right_red, const glw::GLdouble& right_green, const glw::GLdouble& right_blue, const glw::GLdouble& right_alpha); static bool comparePixels(glw::GLuint left_pixel_size, const glw::GLubyte* left_pixel_data, glw::GLuint right_pixel_size, const glw::GLubyte* right_pixel_data, const glw::GLenum format); static void deleteTexture(deqp::Context& context, glw::GLenum target, glw::GLuint name); static bool isTargetMultilayer(glw::GLenum target); static bool isTargetMultilevel(glw::GLenum target); static bool isTargetMultisampled(glw::GLenum target); static glw::GLuint generateTexture(deqp::Context& context, glw::GLenum target); static void maskPixelForFormat(glw::GLenum internal_format, glw::GLubyte* pixel); static glw::GLdouble getEpsilon(glw::GLenum internal_format); static glw::GLuint getPixelSizeForFormat(glw::GLenum internal_format); static glw::GLenum getFormat(glw::GLenum internal_format); static glw::GLuint getNumberOfChannels(glw::GLenum internal_format); static std::string getPixelString(glw::GLenum internal_format, const glw::GLubyte* pixel); static glw::GLenum getType(glw::GLenum internal_format); static void makeTextureComplete(deqp::Context& context, glw::GLenum target, glw::GLuint id, glw::GLint base_level, glw::GLint max_level); static glw::GLuint prepareCompressedTex(deqp::Context& context, glw::GLenum target, glw::GLenum internal_format); static glw::GLuint prepareMultisampleTex(deqp::Context& context, glw::GLenum target, glw::GLsizei n_samples); static glw::GLuint prepareRenderBuffer(deqp::Context& context, glw::GLenum internal_format); static glw::GLuint prepareTex16x16x6(deqp::Context& context, glw::GLenum target, glw::GLenum internal_format, glw::GLenum format, glw::GLenum type, glw::GLuint& out_buf_id); static void prepareTexture(deqp::Context& context, glw::GLuint name, glw::GLenum target, glw::GLenum internal_format, glw::GLenum format, glw::GLenum type, glw::GLuint level, glw::GLuint width, glw::GLuint height, glw::GLuint depth, const glw::GLvoid* pixels, glw::GLuint& out_buf_id); static glw::GLenum transProxyToRealTarget(glw::GLenum target); static glw::GLenum transRealToBindTarget(glw::GLenum target); static void readChannel(glw::GLenum type, glw::GLuint channel, const glw::GLubyte* pixel, glw::GLdouble& out_value); static void writeChannel(glw::GLenum type, glw::GLuint channel, glw::GLdouble value, glw::GLubyte* pixel); static void packPixel(glw::GLenum internal_format, glw::GLenum type, glw::GLdouble red, glw::GLdouble green, glw::GLdouble blue, glw::GLdouble alpha, glw::GLubyte* out_pixel); static void unpackPixel(glw::GLenum format, glw::GLenum type, const glw::GLubyte* pixel, glw::GLdouble& out_red, glw::GLdouble& out_green, glw::GLdouble& out_blue, glw::GLdouble& out_alpha); static bool unpackAndComaprePixels(glw::GLenum left_format, glw::GLenum left_type, glw::GLenum left_internal_format, const glw::GLubyte* left_pixel, glw::GLenum right_format, glw::GLenum right_type, glw::GLenum right_internal_format, const glw::GLubyte* right_pixel); static inline bool roundComponent(glw::GLenum internal_format, glw::GLenum component, glw::GLdouble& value); }; /* Global constants */ static const GLenum s_internal_formats[] = { /* R8 */ GL_R8, GL_R8I, GL_R8UI, GL_R8_SNORM, /* R16 */ GL_R16, GL_R16F, GL_R16I, GL_R16UI, GL_R16_SNORM, /* R32 */ GL_R32F, GL_R32I, GL_R32UI, /* RG8 */ GL_RG8, GL_RG8I, GL_RG8UI, GL_RG8_SNORM, /* RG16 */ GL_RG16, GL_RG16F, GL_RG16I, GL_RG16UI, GL_RG16_SNORM, /* RG32 */ GL_RG32F, GL_RG32I, GL_RG32UI, /* RGB8 */ GL_RGB8, GL_RGB8I, GL_RGB8UI, GL_RGB8_SNORM, /* RGB16 */ GL_RGB16, GL_RGB16F, GL_RGB16I, GL_RGB16UI, GL_RGB16_SNORM, /* RGB32 */ GL_RGB32F, GL_RGB32I, GL_RGB32UI, /* RGBA8 */ GL_RGBA8, GL_RGBA8I, GL_RGBA8UI, GL_RGBA8_SNORM, /* RGBA16 */ GL_RGBA16, GL_RGBA16F, GL_RGBA16I, GL_RGBA16UI, GL_RGBA16_SNORM, /* RGBA32 */ GL_RGBA32F, GL_RGBA32I, GL_RGBA32UI, /* 8 */ GL_R3_G3_B2, GL_RGBA2, /* 12 */ GL_RGB4, /* 15 */ GL_RGB5, /* 16 */ GL_RGBA4, GL_RGB5_A1, /* 30 */ GL_RGB10, /* 32 */ GL_RGB10_A2, GL_RGB10_A2UI, GL_R11F_G11F_B10F, GL_RGB9_E5, /* 36 */ GL_RGB12, /* 48 */ GL_RGBA12, }; static const GLenum s_invalid_targets[] = { GL_TEXTURE_BUFFER, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_PROXY_TEXTURE_1D, GL_PROXY_TEXTURE_1D_ARRAY, GL_PROXY_TEXTURE_2D, GL_PROXY_TEXTURE_2D_ARRAY, GL_PROXY_TEXTURE_2D_MULTISAMPLE, GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY, GL_PROXY_TEXTURE_3D, GL_PROXY_TEXTURE_CUBE_MAP, GL_PROXY_TEXTURE_CUBE_MAP_ARRAY, GL_PROXY_TEXTURE_RECTANGLE, }; static const GLenum s_valid_targets[] = { GL_RENDERBUFFER, GL_TEXTURE_1D, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_2D_MULTISAMPLE_ARRAY, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_RECTANGLE, }; static const GLuint s_n_internal_formats = sizeof(s_internal_formats) / sizeof(s_internal_formats[0]); static const GLuint s_n_invalid_targets = sizeof(s_invalid_targets) / sizeof(s_invalid_targets[0]); static const GLuint s_n_valid_targets = sizeof(s_valid_targets) / sizeof(s_valid_targets[0]); /** * Pixel compatibility depends on pixel size. However value returned by getPixelSizeForFormat * needs some refinements * * @param internal_format Internal format of image * * @return Size of pixel for compatibility checks **/ GLuint getPixelSizeForCompatibilityVerification(GLenum internal_format) { GLuint size = Utils::getPixelSizeForFormat(internal_format); switch (internal_format) { case GL_RGBA2: size = 1; break; default: break; } return size; } #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS == 0 /** Filters out formats that should not be tested by FunctionalTest * * @param format Internal format * * @return true if format should be tested, false otherwise **/ bool filterFormats(GLenum format) { bool result = true; switch (format) { /* R8 */ case GL_R8I: case GL_R8UI: case GL_R8_SNORM: /* R16 */ case GL_R16: case GL_R16F: case GL_R16I: case GL_R16UI: case GL_R16_SNORM: /* R32 */ case GL_R32F: case GL_R32I: case GL_R32UI: /* RG8 */ case GL_RG8: case GL_RG8I: case GL_RG8UI: case GL_RG8_SNORM: /* RG16 */ case GL_RG16: case GL_RG16F: case GL_RG16I: case GL_RG16UI: case GL_RG16_SNORM: /* RG32 */ case GL_RG32F: case GL_RG32I: case GL_RG32UI: /* RGB8 */ case GL_RGB8: case GL_RGB8I: case GL_RGB8UI: case GL_RGB8_SNORM: /* RGB16 */ case GL_RGB16: case GL_RGB16F: case GL_RGB16I: case GL_RGB16UI: case GL_RGB16_SNORM: /* RGB32 */ case GL_RGB32I: case GL_RGB32UI: /* RGBA8 */ case GL_RGBA8: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGBA8_SNORM: /* RGBA16 */ case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA16_SNORM: /* RGBA32 */ case GL_RGBA32F: case GL_RGBA32I: case GL_RGBA32UI: result = false; break; default: result = true; break; } return result; } #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS */ /** Checks if two internal_formats are compatible * * @param src Internal format of source image * @param dst Internal format of destination image * * @return true for compatible formats, false otherwise **/ bool Utils::areFormatsCompatible(glw::GLenum src, glw::GLenum dst) { const GLuint dst_size = getPixelSizeForCompatibilityVerification(dst); const GLuint src_size = getPixelSizeForCompatibilityVerification(src); if (dst_size != src_size) { return false; } #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS == 0 if ((false == filterFormats(src)) || (false == filterFormats(dst))) { return false; } #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_FORMATS */ if (src != dst) { if ((GL_R3_G3_B2 == dst) || (GL_R3_G3_B2 == src) || (GL_RGBA2 == dst) || (GL_RGBA2 == src) || (GL_RGBA4 == dst) || (GL_RGBA4 == src) || (GL_RGB5_A1 == dst) || (GL_RGB5_A1 == src) || (GL_RGB10 == dst) || (GL_RGB10 == src)) { return false; } } #if COPY_IMAGE_WRKARD_FORMATS if ((GL_RGB10_A2 == src) && (GL_R11F_G11F_B10F == dst) || (GL_RGB10_A2 == src) && (GL_RGB9_E5 == dst) || (GL_RGB10_A2UI == src) && (GL_R11F_G11F_B10F == dst) || (GL_RGB10_A2UI == src) && (GL_RGB9_E5 == dst) || (GL_RGB9_E5 == src) && (GL_RGB10_A2 == dst) || (GL_RGB9_E5 == src) && (GL_RGB10_A2UI == dst) || (GL_R11F_G11F_B10F == src) && (GL_RGB10_A2 == dst) || (GL_R11F_G11F_B10F == src) && (GL_RGB10_A2UI == dst)) { return false; } #endif /* COPY_IMAGE_WRKARD_FORMATS */ if (2 == dst_size) { if (src == dst) { return true; } if (((GL_RGB4 == src) && (GL_RGB4 != dst)) || ((GL_RGB4 != src) && (GL_RGB4 == dst)) || ((GL_RGB5 == src) && (GL_RGB5 != dst)) || ((GL_RGB5 != src) && (GL_RGB5 == dst))) { return false; } return true; } if (4 == dst_size) { if (src == dst) { return true; } return true; } return true; } /** Compare two pixels * * @param left_internal_format Internal format of left image * @param left_red Red channel of left image * @param left_green Green channel of left image * @param left_blue Blue channel of left image * @param left_alpha Alpha channel of left image * @param right_internal_format Internal format of right image * @param right_red Red channel of right image * @param right_green Green channel of right image * @param right_blue Blue channel of right image * @param right_alpha Alpha channel of right image * * @return true if pixels match, false otherwise **/ bool Utils::comparePixels(GLenum left_internal_format, const GLdouble& left_red, const GLdouble& left_green, const GLdouble& left_blue, const GLdouble& left_alpha, GLenum right_internal_format, const GLdouble& right_red, const GLdouble& right_green, const GLdouble& right_blue, const GLdouble& right_alpha) { const GLuint left_n_channels = getNumberOfChannels(left_internal_format); const GLuint right_n_channels = getNumberOfChannels(right_internal_format); const GLuint n_channels = (left_n_channels >= right_n_channels) ? right_n_channels : left_n_channels; const GLdouble left_channels[4] = { left_red, left_green, left_blue, left_alpha }; const GLdouble right_channels[4] = { right_red, right_green, right_blue, right_alpha }; for (GLuint i = 0; i < n_channels; ++i) { const GLdouble left = left_channels[i]; const GLdouble right = right_channels[i]; const GLdouble left_eps = getEpsilon(left_internal_format); const GLdouble right_eps = getEpsilon(right_internal_format); const GLdouble eps = fabs(std::max(left_eps, right_eps)); if (eps < fabs(left - right)) { return false; } } return true; } #define RGB9E5_EXPONENT_BITS 5 #define RGB9E5_MANTISSA_BITS 9 #define RGB9E5_EXP_BIAS 15 #define R11FG11FB10F_EXP_BIAS 15 typedef struct { unsigned int r : RGB9E5_MANTISSA_BITS; unsigned int g : RGB9E5_MANTISSA_BITS; unsigned int b : RGB9E5_MANTISSA_BITS; unsigned int biasedexponent : RGB9E5_EXPONENT_BITS; } BitsOfRGB9E5; typedef struct { unsigned int r : 11; unsigned int g : 11; unsigned int b : 10; } BitsOfR11FG11FB10F; typedef union { unsigned int raw; BitsOfRGB9E5 field; } rgb9e5; typedef union { unsigned int raw; BitsOfR11FG11FB10F field; } r11fg11fb10f; void rgb9e5_to_float3(rgb9e5 v, float retval[3]) { int exponent = v.field.biasedexponent - RGB9E5_EXP_BIAS - RGB9E5_MANTISSA_BITS; float scale = (float)pow(2.0, (double)exponent); retval[0] = v.field.r * scale; retval[1] = v.field.g * scale; retval[2] = v.field.b * scale; } // This function will expand a 10-bit or 11-bit float // based on the rules described in 2.3.4.3 and 2.3.4.4 float expandFloat(const unsigned int compressed, const unsigned int numMantissaBits) { unsigned int divisor = (unsigned int)deFloatPow(2, (float)numMantissaBits); float retval = 0.0; unsigned int exponent, mantissa; exponent = compressed / divisor; mantissa = compressed % divisor; if (exponent == 0 && mantissa == 0) retval = 0.0; else if (exponent == 0 && mantissa != 0) retval = deFloatPow(2.f, -14.f) * ((float)mantissa / (float)divisor); else if (0 < exponent && exponent < 31) retval = deFloatPow(2.f, (float)exponent - 15.f) * (1.f + (float)mantissa / (float)divisor); else if (exponent == 31 && mantissa == 0) retval = INFINITY; else if (exponent == 31 && mantissa != 0) retval = NAN; else DE_ASSERT(DE_FALSE && "Invalid exponent and mantissa"); return retval; } void r11fg11fb10f_to_float3(r11fg11fb10f v, float retval[3]) { retval[0] = expandFloat(v.field.r, 6); retval[1] = expandFloat(v.field.g, 6); retval[2] = expandFloat(v.field.b, 5); } bool compareRGB9E5(const void* ptr1, const void* ptr2, int num) { rgb9e5* data1 = (rgb9e5*)ptr1; rgb9e5* data2 = (rgb9e5*)ptr2; float value1[3]; float value2[3]; for (int i = 0; i<num>> 2; ++i) { rgb9e5_to_float3(data1[i], value1); rgb9e5_to_float3(data2[i], value2); for (int j = 0; j < 3; ++j) { if (value1[j] != value2[j]) { return false; } } } return true; } bool compareR11FG11FB10F(const void* ptr1, const void* ptr2, int num) { r11fg11fb10f* data1 = (r11fg11fb10f*)ptr1; r11fg11fb10f* data2 = (r11fg11fb10f*)ptr2; float value1[3]; float value2[3]; for (int i = 0; i<num>> 2; ++i) { r11fg11fb10f_to_float3(data1[i], value1); r11fg11fb10f_to_float3(data2[i], value2); for (int j = 0; j < 3; ++j) { if (value1[j] != value2[j]) { return false; } } } return true; } /** Compare two pixels with memcmp * * @param left_pixel_size Size of left pixel * @param left_pixel_data Data of left pixel * @param right_pixel_size Size of right pixel * @param right_pixel_data Data of right pixel * * @return true if memory match, false otherwise **/ bool Utils::comparePixels(GLuint left_pixel_size, const GLubyte* left_pixel_data, GLuint right_pixel_size, const GLubyte* right_pixel_data, const GLenum format) { const GLuint pixel_size = (left_pixel_size >= right_pixel_size) ? left_pixel_size : right_pixel_size; if (format == GL_RGB9_E5) { return compareRGB9E5(left_pixel_data, right_pixel_data, pixel_size); } else if (format == GL_R11F_G11F_B10F) { return compareR11FG11FB10F(left_pixel_data, right_pixel_data, pixel_size); } return 0 == memcmp(left_pixel_data, right_pixel_data, pixel_size); } /** Delete texture or renderbuffer * * @param context Test context * @param target Image target * @param name Name of image **/ void Utils::deleteTexture(deqp::Context& context, GLenum target, GLuint name) { const Functions& gl = context.getRenderContext().getFunctions(); if (GL_RENDERBUFFER == target) { gl.deleteRenderbuffers(1, &name); } else { gl.deleteTextures(1, &name); } } /** Get epsilon for given internal_format * * @param internal_format Internal format of image * * @return Epsilon value **/ GLdouble Utils::getEpsilon(GLenum internal_format) { GLdouble epsilon; switch (internal_format) { case GL_R8: case GL_R8_SNORM: case GL_R16: case GL_R16F: case GL_R16_SNORM: case GL_R32F: case GL_R8I: case GL_R8UI: case GL_R16I: case GL_R16UI: case GL_R32I: case GL_R32UI: case GL_RG8: case GL_RG8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16_SNORM: case GL_RG32F: case GL_RG8I: case GL_RG8UI: case GL_RG16I: case GL_RG16UI: case GL_RG32I: case GL_RG32UI: case GL_R3_G3_B2: case GL_RGB4: case GL_RGB5: case GL_RGB8: case GL_RGB8_SNORM: case GL_R11F_G11F_B10F: case GL_RGB16: case GL_RGB16F: case GL_RGB16_SNORM: case GL_RGB32F: case GL_RGB8I: case GL_RGB8UI: case GL_RGB10: case GL_RGB16I: case GL_RGB16UI: case GL_RGB32I: case GL_RGB32UI: case GL_RGB9_E5: case GL_RGBA2: case GL_RGBA4: case GL_RGB5_A1: case GL_RGBA8: case GL_RGBA8_SNORM: case GL_RGB10_A2: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16_SNORM: case GL_RGBA32F: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGB10_A2UI: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA32I: case GL_RGBA32UI: epsilon = 0.0; break; case GL_RGB12: case GL_RGBA12: epsilon = 0.00390625; break; default: TCU_FAIL("Invalid enum"); break; } return epsilon; } /** Get format for given internal format * * @param internal_format Internal format * * @return Format **/ GLenum Utils::getFormat(GLenum internal_format) { GLenum format = 0; switch (internal_format) { /* R */ case GL_R8: case GL_R8_SNORM: case GL_R16: case GL_R16F: case GL_R16_SNORM: case GL_R32F: format = GL_RED; break; case GL_R8I: case GL_R8UI: case GL_R16I: case GL_R16UI: case GL_R32I: case GL_R32UI: format = GL_RED_INTEGER; break; /* RG */ case GL_RG8: case GL_RG8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16_SNORM: case GL_RG32F: format = GL_RG; break; case GL_RG8I: case GL_RG8UI: case GL_RG16I: case GL_RG16UI: case GL_RG32I: case GL_RG32UI: format = GL_RG_INTEGER; break; /* RGB */ case GL_R3_G3_B2: case GL_RGB4: case GL_RGB5: case GL_RGB8: case GL_RGB8_SNORM: case GL_R11F_G11F_B10F: case GL_RGB12: case GL_RGB16: case GL_RGB16F: case GL_RGB16_SNORM: case GL_RGB32F: case GL_RGB9_E5: format = GL_RGB; break; case GL_RGB8I: case GL_RGB8UI: case GL_RGB16I: case GL_RGB16UI: case GL_RGB32I: case GL_RGB32UI: format = GL_RGB_INTEGER; break; /* RGBA */ case GL_RGB10: case GL_RGBA2: case GL_RGBA4: case GL_RGB5_A1: case GL_RGBA8: case GL_RGBA8_SNORM: case GL_RGB10_A2: case GL_RGBA12: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16_SNORM: case GL_RGBA32F: format = GL_RGBA; break; case GL_RGBA8I: case GL_RGBA8UI: case GL_RGB10_A2UI: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA32I: case GL_RGBA32UI: format = GL_RGBA_INTEGER; break; default: TCU_FAIL("Invalid enum"); break; } return format; } /** Get number of channels for given internal_format * * @param internal_format Internal format * * @return Number of channels **/ GLuint Utils::getNumberOfChannels(GLenum internal_format) { GLuint result = 0; switch (internal_format) { case GL_R8: case GL_R8_SNORM: case GL_R16: case GL_R16F: case GL_R16_SNORM: case GL_R32F: case GL_R8I: case GL_R8UI: case GL_R16I: case GL_R16UI: case GL_R32I: case GL_R32UI: result = 1; break; case GL_RG8: case GL_RG8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16_SNORM: case GL_RG32F: case GL_RG8I: case GL_RG8UI: case GL_RG16I: case GL_RG16UI: case GL_RG32I: case GL_RG32UI: result = 2; break; case GL_R3_G3_B2: case GL_RGB4: case GL_RGB5: case GL_RGB8: case GL_RGB8_SNORM: case GL_RGB10: case GL_R11F_G11F_B10F: case GL_RGB12: case GL_RGB16: case GL_RGB16F: case GL_RGB16_SNORM: case GL_RGB32F: case GL_RGB9_E5: case GL_RGB8I: case GL_RGB8UI: case GL_RGB16I: case GL_RGB16UI: case GL_RGB32I: case GL_RGB32UI: result = 3; break; case GL_RGBA2: case GL_RGBA4: case GL_RGB5_A1: case GL_RGBA8: case GL_RGBA8_SNORM: case GL_RGB10_A2: case GL_RGBA12: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16_SNORM: case GL_RGBA32F: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGB10_A2UI: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA32I: case GL_RGBA32UI: result = 4; break; default: TCU_FAIL("Invalid enum"); break; } return result; } /** Get type for given internal format * * @param internal_format Internal format * * @return Type **/ GLenum Utils::getType(GLenum internal_format) { GLenum type = 0; switch (internal_format) { case GL_R8: case GL_R8UI: case GL_RG8: case GL_RG8UI: case GL_RGB8: case GL_RGB8UI: case GL_RGBA8: case GL_RGBA8UI: type = GL_UNSIGNED_BYTE; break; case GL_R8_SNORM: case GL_R8I: case GL_RG8_SNORM: case GL_RG8I: case GL_RGB8_SNORM: case GL_RGB8I: case GL_RGBA8_SNORM: case GL_RGBA8I: type = GL_BYTE; break; case GL_R3_G3_B2: type = GL_UNSIGNED_BYTE_3_3_2; break; case GL_RGB4: case GL_RGB5: type = GL_UNSIGNED_SHORT_5_6_5; break; case GL_RGBA2: case GL_RGBA4: type = GL_UNSIGNED_SHORT_4_4_4_4; break; case GL_RGB5_A1: type = GL_UNSIGNED_SHORT_5_5_5_1; break; case GL_RGB10: case GL_RGB10_A2: case GL_RGB10_A2UI: type = GL_UNSIGNED_INT_2_10_10_10_REV; break; case GL_R16F: case GL_RG16F: case GL_RGB16F: case GL_RGBA16F: type = GL_HALF_FLOAT; break; case GL_R16: case GL_R16UI: case GL_RG16: case GL_RG16UI: case GL_RGB12: case GL_RGB16: case GL_RGB16UI: case GL_RGBA12: case GL_RGBA16: case GL_RGBA16UI: type = GL_UNSIGNED_SHORT; break; case GL_R16_SNORM: case GL_R16I: case GL_RG16_SNORM: case GL_RG16I: case GL_RGB16_SNORM: case GL_RGB16I: case GL_RGBA16_SNORM: case GL_RGBA16I: type = GL_SHORT; break; case GL_R32UI: case GL_RG32UI: case GL_RGB32UI: case GL_RGBA32UI: type = GL_UNSIGNED_INT; break; case GL_RGB9_E5: type = GL_UNSIGNED_INT_5_9_9_9_REV; break; case GL_R32I: case GL_RG32I: case GL_RGB32I: case GL_RGBA32I: type = GL_INT; break; case GL_R32F: case GL_RG32F: case GL_RGB32F: case GL_RGBA32F: type = GL_FLOAT; break; case GL_R11F_G11F_B10F: type = GL_UNSIGNED_INT_10F_11F_11F_REV; break; default: TCU_FAIL("Invalid enum"); break; } return type; } /** Returns mask that should be applied to pixel value * * @param internal_format Internal format of texture * @param pixel Pixel data * * @return Mask **/ void Utils::maskPixelForFormat(GLenum internal_format, GLubyte* pixel) { switch (internal_format) { case GL_RGB10: /* UINT_10_10_10_2 - ALPHA will be set to 3*/ pixel[0] |= 0x03; break; default: break; } } /** Get size of pixel for given internal format * * @param internal_format Internal format * * @return Number of bytes used by given format **/ GLuint Utils::getPixelSizeForFormat(GLenum internal_format) { GLuint size = 0; switch (internal_format) { /* 8 */ case GL_R8: case GL_R8I: case GL_R8UI: case GL_R8_SNORM: case GL_R3_G3_B2: size = 1; break; /* 8 */ case GL_RGBA2: size = 2; break; /* 12 */ case GL_RGB4: size = 2; break; /* 15 */ case GL_RGB5: size = 2; break; /* 16 */ case GL_RG8: case GL_RG8I: case GL_RG8UI: case GL_RG8_SNORM: case GL_R16: case GL_R16F: case GL_R16I: case GL_R16UI: case GL_R16_SNORM: case GL_RGBA4: case GL_RGB5_A1: size = 2; break; /* 24 */ case GL_RGB8: case GL_RGB8I: case GL_RGB8UI: case GL_RGB8_SNORM: size = 3; break; /* 30 */ case GL_RGB10: size = 4; break; /* 32 */ case GL_RGBA8: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGBA8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16I: case GL_RG16UI: case GL_RG16_SNORM: case GL_R32F: case GL_R32I: case GL_R32UI: case GL_RGB10_A2: case GL_RGB10_A2UI: case GL_R11F_G11F_B10F: case GL_RGB9_E5: size = 4; break; /* 36 */ case GL_RGB12: size = 6; break; /* 48 */ case GL_RGB16: case GL_RGB16F: case GL_RGB16I: case GL_RGB16UI: case GL_RGB16_SNORM: size = 6; break; /* 64 */ case GL_RGBA12: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA16_SNORM: case GL_RG32F: case GL_RG32I: case GL_RG32UI: size = 8; break; /* 96 */ case GL_RGB32F: case GL_RGB32I: case GL_RGB32UI: size = 12; break; /* 128 */ case GL_RGBA32F: case GL_RGBA32I: case GL_RGBA32UI: size = 16; break; default: TCU_FAIL("Invalid enum"); break; } return size; } /** Prepare string that represents bytes of pixel * * @param internal_format Format * @param pixel Pixel data * * @return String **/ std::string Utils::getPixelString(GLenum internal_format, const GLubyte* pixel) { const GLuint pixel_size = Utils::getPixelSizeForFormat(internal_format); std::stringstream stream; stream << "0x"; for (GLint i = pixel_size - 1; i >= 0; --i) { stream << std::setbase(16) << std::setw(2) << std::setfill('0') << (GLuint)pixel[i]; } return stream.str(); } /** Check if target supports multiple layers * * @param target Texture target * * @return true if target is multilayered **/ bool Utils::isTargetMultilayer(GLenum target) { bool result = false; switch (target) { case GL_TEXTURE_1D_ARRAY: case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: case GL_TEXTURE_3D: case GL_TEXTURE_CUBE_MAP_ARRAY: result = true; break; default: break; } return result; } /** Check if target supports multiple level * * @param target Texture target * * @return true if target supports mipmaps **/ bool Utils::isTargetMultilevel(GLenum target) { bool result = true; switch (target) { case GL_TEXTURE_2D_MULTISAMPLE: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: case GL_TEXTURE_RECTANGLE: case GL_RENDERBUFFER: result = false; break; default: break; } return result; } /** Check if target is multisampled * * @param target Texture target * * @return true when for multisampled formats, false otherwise **/ bool Utils::isTargetMultisampled(GLenum target) { bool result = false; switch (target) { case GL_TEXTURE_2D_MULTISAMPLE: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: result = true; break; default: break; } return result; } /** Generate texture object * * @param context Test context * @param target Target of texture * * @return Generated name **/ glw::GLuint Utils::generateTexture(deqp::Context& context, GLenum target) { const Functions& gl = context.getRenderContext().getFunctions(); GLuint name = 0; switch (target) { case GL_RENDERBUFFER: gl.genRenderbuffers(1, &name); GLU_EXPECT_NO_ERROR(gl.getError(), "GenRenderbuffers"); break; default: gl.genTextures(1, &name); GLU_EXPECT_NO_ERROR(gl.getError(), "GenTextures"); break; } return name; } /** Sets base and max level parameters of texture to make it complete * * @param context Test context * @param target GLenum representing target of texture that should be created * @param id Id of texture * @param base_level Base level value, eg 0 * @param max_level Max level value, eg 0 **/ void Utils::makeTextureComplete(deqp::Context& context, GLenum target, GLuint id, GLint base_level, GLint max_level) { const Functions& gl = context.getRenderContext().getFunctions(); if (GL_RENDERBUFFER == target) { return; } /* Translate proxies into real targets */ target = transRealToBindTarget(transProxyToRealTarget(target)); gl.bindTexture(target, id); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); /* Set levels */ if (GL_TEXTURE_BUFFER != target) { gl.texParameteri(target, GL_TEXTURE_BASE_LEVEL, base_level); GLU_EXPECT_NO_ERROR(gl.getError(), "TexParameteri"); gl.texParameteri(target, GL_TEXTURE_MAX_LEVEL, max_level); GLU_EXPECT_NO_ERROR(gl.getError(), "TexParameteri"); /* Integer textures won't be complete with the default min filter * of GL_NEAREST_MIPMAP_LINEAR (or GL_LINEAR for rectangle textures) * and default mag filter of GL_LINEAR, so switch to nearest. */ if (GL_TEXTURE_2D_MULTISAMPLE != target && GL_TEXTURE_2D_MULTISAMPLE_ARRAY != target) { gl.texParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (GL_TEXTURE_RECTANGLE != target) { gl.texParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); GLU_EXPECT_NO_ERROR(gl.getError(), "TexParameteri"); } else { gl.texParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GLU_EXPECT_NO_ERROR(gl.getError(), "TexParameteri"); } } } /* Clean binding point */ gl.bindTexture(target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); } /** Generate and initialize texture for given target * * @param context Test context * @param target GLenum representing target of texture that should be created * @param n_samples Number of samples * * @return "name" of texture **/ GLuint Utils::prepareMultisampleTex(deqp::Context& context, GLenum target, GLsizei n_samples) { static const GLuint depth = 6; const Functions& gl = context.getRenderContext().getFunctions(); static const GLuint height = 16; static const GLenum internal_format = GL_RGBA8; GLuint name = 0; static const GLuint width = 16; gl.genTextures(1, &name); GLU_EXPECT_NO_ERROR(gl.getError(), "GenTextures"); /* Initialize */ switch (target) { case GL_TEXTURE_2D_MULTISAMPLE: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage2DMultisample(target, n_samples, internal_format, width, height, GL_FALSE /* fixedsamplelocation */); GLU_EXPECT_NO_ERROR(gl.getError(), "TexImage2DMultisample"); break; case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage3DMultisample(target, n_samples, internal_format, width, height, depth, GL_FALSE /* fixedsamplelocation */); GLU_EXPECT_NO_ERROR(gl.getError(), "TexImage3DMultisample"); break; default: TCU_FAIL("Invalid enum"); break; } /* Clean binding point */ gl.bindTexture(target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); return name; } /** Generate and initialize texture for given target * * @param context Test context * @param internal_format Internal format of render buffer * * @return "name" of texture **/ GLuint Utils::prepareRenderBuffer(deqp::Context& context, GLenum internal_format) { const Functions& gl = context.getRenderContext().getFunctions(); static const GLuint height = 16; GLuint name = 0; static const GLuint width = 16; gl.genRenderbuffers(1, &name); GLU_EXPECT_NO_ERROR(gl.getError(), "GenRenderbuffers"); /* Initialize */ gl.bindRenderbuffer(GL_RENDERBUFFER, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindRenderbuffer"); gl.renderbufferStorage(GL_RENDERBUFFER, internal_format, width, height); GLU_EXPECT_NO_ERROR(gl.getError(), "RenderbufferStorage"); /* Clean binding point */ gl.bindRenderbuffer(GL_RENDERBUFFER, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindRenderbuffer"); return name; } /** Generate and initialize texture for given target * * @param context Test context * @param target GLenum representing target of texture that should be created * @param internal_format <internalformat> * @param format <format> * @param type <type> * @param out_buf_id ID of buffer that will be used for TEXTURE_BUFFER * * @return "name" of texture **/ GLuint Utils::prepareTex16x16x6(deqp::Context& context, GLenum target, GLenum internal_format, GLenum format, GLenum type, GLuint& out_buf_id) { static const GLuint depth = 6; static const GLuint height = 16; static const GLuint level = 0; GLuint name = 0; static const GLchar* pixels = 0; static const GLuint width = 16; name = generateTexture(context, target); prepareTexture(context, name, target, internal_format, format, type, level, width, height, depth, pixels, out_buf_id); return name; } /** Initialize texture * * @param context Test context * @param name Name of texture object * @param target GLenum representing target of texture that should be created * @param internal_format <internalformat> * @param format <format> * @param type <type> * @param level <level> * @param width <width> * @param height <height> * @param depth <depth> * @param pixels <pixels> * @param out_buf_id ID of buffer that will be used for TEXTURE_BUFFER * * @return "name" of texture **/ void Utils::prepareTexture(deqp::Context& context, GLuint name, GLenum target, GLenum internal_format, GLenum format, GLenum type, GLuint level, GLuint width, GLuint height, GLuint depth, const GLvoid* pixels, GLuint& out_buf_id) { static const GLint border = 0; GLenum error = 0; const GLchar* function_name = "unknown"; const Functions& gl = context.getRenderContext().getFunctions(); static const GLsizei samples = 1; /* Translate proxies into real targets */ target = transProxyToRealTarget(target); /* Initialize */ switch (target) { case GL_RENDERBUFFER: gl.bindRenderbuffer(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindRenderbuffer"); gl.renderbufferStorage(target, internal_format, width, height); GLU_EXPECT_NO_ERROR(gl.getError(), "RenderbufferStorage"); gl.bindRenderbuffer(target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindRenderbuffer"); break; case GL_TEXTURE_1D: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage1D(target, level, internal_format, width, border, format, type, pixels); error = gl.getError(); function_name = "TexImage1D"; break; case GL_TEXTURE_1D_ARRAY: case GL_TEXTURE_2D: case GL_TEXTURE_RECTANGLE: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage2D(target, level, internal_format, width, height, border, format, type, pixels); error = gl.getError(); function_name = "TexImage2D"; break; case GL_TEXTURE_2D_MULTISAMPLE: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage2DMultisample(target, samples, internal_format, width, height, GL_FALSE /* fixedsamplelocation */); error = gl.getError(); function_name = "TexImage2DMultisample"; break; case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage3DMultisample(target, samples, internal_format, width, height, depth, GL_FALSE /* fixedsamplelocation */); error = gl.getError(); function_name = "TexImage3DMultisample"; break; case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_3D: case GL_TEXTURE_CUBE_MAP_ARRAY: gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage3D(target, level, internal_format, width, height, depth, border, format, type, pixels); error = gl.getError(); function_name = "TexImage3D"; break; case GL_TEXTURE_BUFFER: gl.genBuffers(1, &out_buf_id); GLU_EXPECT_NO_ERROR(gl.getError(), "GenBuffers"); gl.bindBuffer(GL_TEXTURE_BUFFER, out_buf_id); GLU_EXPECT_NO_ERROR(gl.getError(), "BindBuffer"); { GLsizei size = 16; const GLvoid* data = 0; if (0 != pixels) { size = width; data = pixels; } gl.bufferData(GL_TEXTURE_BUFFER, size, data, GL_DYNAMIC_COPY); GLU_EXPECT_NO_ERROR(gl.getError(), "BufferData"); } gl.bindTexture(GL_TEXTURE_BUFFER, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texBuffer(GL_TEXTURE_BUFFER, internal_format, out_buf_id); GLU_EXPECT_NO_ERROR(gl.getError(), "TexBuffer"); break; case GL_TEXTURE_CUBE_MAP: case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: case GL_TEXTURE_CUBE_MAP_POSITIVE_X: case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: /* Change target to CUBE_MAP, it will be used later to change base and max level */ target = GL_TEXTURE_CUBE_MAP; gl.bindTexture(target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, level, internal_format, width, height, border, format, type, pixels); gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, level, internal_format, width, height, border, format, type, pixels); error = gl.getError(); function_name = "TexImage2D"; break; default: TCU_FAIL("Invalid enum"); break; } if (GL_NO_ERROR != error) { context.getTestContext().getLog() << tcu::TestLog::Message << "Error: " << glu::getErrorStr(error) << ". Function: " << function_name << ". Target: " << glu::getTextureTargetStr(target) << ". Format: " << glu::getInternalFormatParameterStr(internal_format) << ", " << glu::getTextureFormatName(format) << ", " << glu::getTypeStr(type) << tcu::TestLog::EndMessage; TCU_FAIL("Failed to create texture"); } if (GL_RENDERBUFFER != target) { /* Clean binding point */ gl.bindTexture(target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); } } /** Translate proxies into real targets * * @param target Target to be converted * * @return Converted target for proxies, <target> otherwise **/ GLenum Utils::transProxyToRealTarget(GLenum target) { switch (target) { case GL_PROXY_TEXTURE_1D: target = GL_TEXTURE_1D; break; case GL_PROXY_TEXTURE_1D_ARRAY: target = GL_TEXTURE_1D_ARRAY; break; case GL_PROXY_TEXTURE_2D: target = GL_TEXTURE_2D; break; case GL_PROXY_TEXTURE_2D_ARRAY: target = GL_TEXTURE_2D_ARRAY; break; case GL_PROXY_TEXTURE_2D_MULTISAMPLE: target = GL_TEXTURE_2D_MULTISAMPLE; break; case GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY: target = GL_TEXTURE_2D_MULTISAMPLE_ARRAY; break; case GL_PROXY_TEXTURE_3D: target = GL_TEXTURE_3D; break; case GL_PROXY_TEXTURE_CUBE_MAP: target = GL_TEXTURE_CUBE_MAP; break; case GL_PROXY_TEXTURE_CUBE_MAP_ARRAY: target = GL_TEXTURE_CUBE_MAP_ARRAY; break; case GL_PROXY_TEXTURE_RECTANGLE: target = GL_TEXTURE_RECTANGLE; break; default: break; } return target; } /** Translate real targets into binding targets * * @param target Target to be converted * * @return Converted target for cube map faces, <target> otherwise **/ GLenum Utils::transRealToBindTarget(GLenum target) { switch (target) { case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_X: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: target = GL_TEXTURE_CUBE_MAP; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: target = GL_TEXTURE_CUBE_MAP; break; default: break; } return target; } /** Read value of channel * * @tparam T Type used to store channel value * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ template <typename T> void readBaseTypeFromUnsignedChannel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { static const T max = -1; const GLdouble d_max = (GLdouble)max; const T* ptr = (T*)pixel; const T t_value = ptr[channel]; const GLdouble d_value = (GLdouble)t_value; out_value = d_value / d_max; } /** Read value of channel * * @tparam T Type used to store channel value * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ template <typename T> void readBaseTypeFromSignedChannel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { static const GLuint n_bytes = sizeof(T); static const GLuint n_bits = 8u * n_bytes; static const T max = (T)((1u << (n_bits - 1u)) - 1u); const GLdouble d_max = (GLdouble)max; const T* ptr = (T*)pixel; const T t_value = ptr[channel]; const GLdouble d_value = (GLdouble)t_value; out_value = d_value / d_max; } /** Read value of channel * * @tparam T Type used to store channel value * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ void readBaseTypeFromFloatChannel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { const GLfloat* ptr = (const GLfloat*)pixel; const GLfloat t_value = ptr[channel]; const GLdouble d_value = (GLdouble)t_value; out_value = d_value; } /** Read value of channel * * @tparam T Type used to store channel value * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ void readBaseTypeFromHalfFloatChannel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { const deUint16* ptr = (const deUint16*)pixel; const deUint16 bits = ptr[channel]; tcu::Float16 val(bits); const GLdouble d_value = val.asDouble(); out_value = d_value; } /** Read value of channel * * @tparam T Type used to store pixel * @tparam size_1 Size of channel in bits * @tparam size_2 Size of channel in bits * @tparam size_3 Size of channel in bits * @tparam off_1 Offset of channel in bits * @tparam off_2 Offset of channel in bits * @tparam off_3 Offset of channel in bits * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ template <typename T, unsigned int size_1, unsigned int size_2, unsigned int size_3, unsigned int off_1, unsigned int off_2, unsigned int off_3> void read3Channel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { T mask = 0; T max = 0; T off = 0; const T* ptr = (T*)pixel; T result = 0; const T t_value = ptr[0]; static const T max_1 = (1 << size_1) - 1; static const T max_2 = (1 << size_2) - 1; static const T max_3 = (1 << size_3) - 1; switch (channel) { case 0: mask = max_1; max = max_1; off = off_1; break; case 1: mask = max_2; max = max_2; off = off_2; break; case 2: mask = max_3; max = max_3; off = off_3; break; default: TCU_FAIL("Invalid channel"); break; } result = (T)((t_value >> off) & mask); const GLdouble d_max = (GLdouble)max; const GLdouble d_value = (GLdouble)result; out_value = d_value / d_max; } /** Read value of channel * * @tparam T Type used to store pixel * @tparam size_1 Size of channel in bits * @tparam size_2 Size of channel in bits * @tparam size_3 Size of channel in bits * @tparam size_4 Size of channel in bits * @tparam off_1 Offset of channel in bits * @tparam off_2 Offset of channel in bits * @tparam off_3 Offset of channel in bits * @tparam off_4 Offset of channel in bits * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ template <typename T, unsigned int size_1, unsigned int size_2, unsigned int size_3, unsigned int size_4, unsigned int off_1, unsigned int off_2, unsigned int off_3, unsigned int off_4> void read4Channel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { T mask = 0; T max = 0; T off = 0; const T* ptr = (T*)pixel; T result = 0; const T t_value = ptr[0]; static const T max_1 = (1 << size_1) - 1; static const T max_2 = (1 << size_2) - 1; static const T max_3 = (1 << size_3) - 1; static const T max_4 = (1 << size_4) - 1; switch (channel) { case 0: mask = max_1; max = max_1; off = off_1; break; case 1: mask = max_2; max = max_2; off = off_2; break; case 2: mask = max_3; max = max_3; off = off_3; break; case 3: mask = max_4; max = max_4; off = off_4; break; default: TCU_FAIL("Invalid channel"); break; } result = (T)((t_value >> off) & mask); const GLdouble d_max = (GLdouble)max; const GLdouble d_value = (GLdouble)result; out_value = d_value / d_max; } /** Read value of channel * * @param channel Channel index * @param pixel Pixel data * @param out_value Read value **/ void read11F_11F_10F_Channel(GLuint channel, const GLubyte* pixel, GLdouble& out_value) { const deUint32* ptr = (deUint32*)pixel; deUint32 val = *ptr; switch (channel) { case 0: { deUint32 bits = (val & 0x000007ff); tcu::Float<deUint32, 5, 6, 15, tcu::FLOAT_SUPPORT_DENORM> temp_val(bits); out_value = temp_val.asDouble(); } break; case 1: { deUint32 bits = ((val >> 11) & 0x000007ff); tcu::Float<deUint32, 5, 6, 15, tcu::FLOAT_SUPPORT_DENORM> temp_val(bits); out_value = temp_val.asDouble(); } break; case 2: { deUint32 bits = ((val >> 22) & 0x000003ff); tcu::Float<deUint32, 5, 5, 15, tcu::FLOAT_SUPPORT_DENORM> temp_val(bits); out_value = temp_val.asDouble(); } break; default: TCU_FAIL("Invalid channel"); break; } } /** Write value of channel * * @tparam T Type used to store pixel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ template <typename T> void writeBaseTypeToUnsignedChannel(GLuint channel, GLdouble value, GLubyte* pixel) { static const T max = -1; const GLdouble d_max = (GLdouble)max; const GLdouble d_value = value * d_max; const T t_value = (T)d_value; T* ptr = (T*)pixel; ptr[channel] = t_value; } /** Write value of channel * * @tparam T Type used to store pixel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ template <typename T> void writeBaseTypeToSignedChannel(GLuint channel, GLdouble value, GLubyte* pixel) { static const GLuint n_bytes = sizeof(T); static const GLuint n_bits = 8u * n_bytes; static const T max = (T)((1u << (n_bits - 1u)) - 1u); const GLdouble d_max = (GLdouble)max; const GLdouble d_value = value * d_max; const T t_value = (T)d_value; T* ptr = (T*)pixel; ptr[channel] = t_value; } /** Write value of channel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ void writeBaseTypeToFloatChannel(GLuint channel, GLdouble value, GLubyte* pixel) { const GLfloat t_value = (GLfloat)value; GLfloat* ptr = (GLfloat*)pixel; ptr[channel] = t_value; } /** Write value of channel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ void writeBaseTypeToHalfFloatChannel(GLuint channel, GLdouble value, GLubyte* pixel) { deUint16* ptr = (deUint16*)pixel; tcu::Float16 val(value); ptr[channel] = val.bits(); } /** Write value of channel * * @tparam T Type used to store pixel * @tparam size_1 Size of channel in bits * @tparam size_2 Size of channel in bits * @tparam size_3 Size of channel in bits * @tparam off_1 Offset of channel in bits * @tparam off_2 Offset of channel in bits * @tparam off_3 Offset of channel in bits * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ template <typename T, unsigned int size_1, unsigned int size_2, unsigned int size_3, unsigned int off_1, unsigned int off_2, unsigned int off_3> void write3Channel(GLuint channel, GLdouble value, GLubyte* pixel) { T mask = 0; T max = 0; T off = 0; T* ptr = (T*)pixel; T result = 0; static const T max_1 = (1 << size_1) - 1; static const T max_2 = (1 << size_2) - 1; static const T max_3 = (1 << size_3) - 1; switch (channel) { case 0: mask = max_1; max = max_1; off = off_1; break; case 1: mask = max_2; max = max_2; off = off_2; break; case 2: mask = max_3; max = max_3; off = off_3; break; default: TCU_FAIL("Invalid channel"); break; } const GLdouble d_max = (GLdouble)max; const GLdouble d_value = value * d_max; const T t_value = (T)d_value; result = (T)((t_value & mask) << off); *ptr |= result; } /** Write value of channel * * @tparam T Type used to store pixel * @tparam size_1 Size of channel in bits * @tparam size_2 Size of channel in bits * @tparam size_3 Size of channel in bits * @tparam size_4 Size of channel in bits * @tparam off_1 Offset of channel in bits * @tparam off_2 Offset of channel in bits * @tparam off_3 Offset of channel in bits * @tparam off_4 Offset of channel in bits * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ template <typename T, unsigned int size_1, unsigned int size_2, unsigned int size_3, unsigned int size_4, unsigned int off_1, unsigned int off_2, unsigned int off_3, unsigned int off_4> void write4Channel(GLuint channel, GLdouble value, GLubyte* pixel) { T mask = 0; T max = 0; T off = 0; T* ptr = (T*)pixel; T result = 0; static const T max_1 = (1 << size_1) - 1; static const T max_2 = (1 << size_2) - 1; static const T max_3 = (1 << size_3) - 1; static const T max_4 = (1 << size_4) - 1; switch (channel) { case 0: mask = max_1; max = max_1; off = off_1; break; case 1: mask = max_2; max = max_2; off = off_2; break; case 2: mask = max_3; max = max_3; off = off_3; break; case 3: mask = max_4; max = max_4; off = off_4; break; default: TCU_FAIL("Invalid channel"); break; } const GLdouble d_max = (GLdouble)max; const GLdouble d_value = value * d_max; const T t_value = (T)d_value; result = (T)((t_value & mask) << off); *ptr |= result; } /** Write value of channel * * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ void write11F_11F_10F_Channel(GLuint channel, GLdouble value, GLubyte* pixel) { deUint32* ptr = (deUint32*)pixel; switch (channel) { case 0: { tcu::Float<deUint32, 5, 6, 15, tcu::FLOAT_SUPPORT_DENORM> val(value); deUint32 bits = val.bits(); *ptr |= bits; } break; case 1: { tcu::Float<deUint32, 5, 6, 15, tcu::FLOAT_SUPPORT_DENORM> val(value); deUint32 bits = val.bits(); *ptr |= (bits << 11); } break; case 2: { tcu::Float<deUint32, 5, 5, 15, tcu::FLOAT_SUPPORT_DENORM> val(value); deUint32 bits = val.bits(); *ptr |= (bits << 22); } break; default: TCU_FAIL("Invalid channel"); break; } } /** Read value of channel * * @param type Type used by pixel * @param channel Channel index * @param pixel Pixel data * @param value Read value **/ void Utils::readChannel(GLenum type, GLuint channel, const GLubyte* pixel, GLdouble& value) { switch (type) { /* Base types */ case GL_UNSIGNED_BYTE: readBaseTypeFromUnsignedChannel<GLubyte>(channel, pixel, value); break; case GL_UNSIGNED_SHORT: readBaseTypeFromUnsignedChannel<GLushort>(channel, pixel, value); break; case GL_UNSIGNED_INT: readBaseTypeFromUnsignedChannel<GLuint>(channel, pixel, value); break; case GL_BYTE: readBaseTypeFromSignedChannel<GLbyte>(channel, pixel, value); break; case GL_SHORT: readBaseTypeFromSignedChannel<GLshort>(channel, pixel, value); break; case GL_INT: readBaseTypeFromSignedChannel<GLint>(channel, pixel, value); break; case GL_HALF_FLOAT: readBaseTypeFromHalfFloatChannel(channel, pixel, value); break; case GL_FLOAT: readBaseTypeFromFloatChannel(channel, pixel, value); break; /* Complicated */ /* 3 channles */ case GL_UNSIGNED_BYTE_3_3_2: read3Channel<GLubyte, 3, 3, 2, 5, 2, 0>(channel, pixel, value); break; case GL_UNSIGNED_SHORT_5_6_5: read3Channel<GLushort, 5, 6, 5, 11, 5, 0>(channel, pixel, value); break; /* 4 channels */ case GL_UNSIGNED_SHORT_4_4_4_4: read4Channel<GLushort, 4, 4, 4, 4, 12, 8, 4, 0>(channel, pixel, value); break; case GL_UNSIGNED_SHORT_5_5_5_1: read4Channel<GLushort, 5, 5, 5, 1, 11, 6, 1, 0>(channel, pixel, value); break; case GL_UNSIGNED_INT_2_10_10_10_REV: read4Channel<GLuint, 2, 10, 10, 10, 30, 20, 10, 0>(3 - channel, pixel, value); break; case GL_UNSIGNED_INT_5_9_9_9_REV: read4Channel<GLuint, 5, 9, 9, 9, 27, 18, 9, 0>(3 - channel, pixel, value); break; /* R11F_G11F_B10F - uber complicated */ case GL_UNSIGNED_INT_10F_11F_11F_REV: read11F_11F_10F_Channel(channel, pixel, value); break; default: TCU_FAIL("Invalid enum"); break; } } /** Write value of channel * * @param type Type used by pixel * @param channel Channel index * @param value Value to write * @param pixel Pixel data **/ void Utils::writeChannel(GLenum type, GLuint channel, GLdouble value, GLubyte* pixel) { switch (type) { /* Base types */ case GL_UNSIGNED_BYTE: writeBaseTypeToUnsignedChannel<GLubyte>(channel, value, pixel); break; case GL_UNSIGNED_SHORT: writeBaseTypeToUnsignedChannel<GLushort>(channel, value, pixel); break; case GL_UNSIGNED_INT: writeBaseTypeToUnsignedChannel<GLuint>(channel, value, pixel); break; case GL_BYTE: writeBaseTypeToSignedChannel<GLbyte>(channel, value, pixel); break; case GL_SHORT: writeBaseTypeToSignedChannel<GLshort>(channel, value, pixel); break; case GL_INT: writeBaseTypeToSignedChannel<GLint>(channel, value, pixel); break; case GL_HALF_FLOAT: writeBaseTypeToHalfFloatChannel(channel, value, pixel); break; case GL_FLOAT: writeBaseTypeToFloatChannel(channel, value, pixel); break; /* Complicated */ /* 3 channles */ case GL_UNSIGNED_BYTE_3_3_2: write3Channel<GLubyte, 3, 3, 2, 5, 2, 0>(channel, value, pixel); break; case GL_UNSIGNED_SHORT_5_6_5: write3Channel<GLushort, 5, 6, 5, 11, 5, 0>(channel, value, pixel); break; /* 4 channels */ case GL_UNSIGNED_SHORT_4_4_4_4: write4Channel<GLushort, 4, 4, 4, 4, 12, 8, 4, 0>(channel, value, pixel); break; case GL_UNSIGNED_SHORT_5_5_5_1: write4Channel<GLushort, 5, 5, 5, 1, 11, 6, 1, 0>(channel, value, pixel); break; case GL_UNSIGNED_INT_2_10_10_10_REV: write4Channel<GLuint, 2, 10, 10, 10, 30, 20, 10, 0>(3 - channel, value, pixel); break; case GL_UNSIGNED_INT_5_9_9_9_REV: write4Channel<GLuint, 5, 9, 9, 9, 27, 18, 9, 0>(3 - channel, value, pixel); break; /* R11F_G11F_B10F - uber complicated */ case GL_UNSIGNED_INT_10F_11F_11F_REV: write11F_11F_10F_Channel(channel, value, pixel); break; default: TCU_FAIL("Invalid enum"); break; } } /** Packs given channels to pixel * * @param internal_format Internal format of image * @param type Type used by image * @param red Red channel * @param green Green channel * @param blue Blue channel * @param alpha Alpha channel * @param out_pixel Pixel data **/ void Utils::packPixel(GLenum internal_format, GLenum type, GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha, GLubyte* out_pixel) { switch (internal_format) { case GL_R8: case GL_R8_SNORM: case GL_R16: case GL_R16F: case GL_R16_SNORM: case GL_R32F: case GL_R8I: case GL_R8UI: case GL_R16I: case GL_R16UI: case GL_R32I: case GL_R32UI: writeChannel(type, 0, red, out_pixel); break; case GL_RG8: case GL_RG8_SNORM: case GL_RG16: case GL_RG16F: case GL_RG16_SNORM: case GL_RG32F: case GL_RG8I: case GL_RG8UI: case GL_RG16I: case GL_RG16UI: case GL_RG32I: case GL_RG32UI: writeChannel(type, 0, red, out_pixel); writeChannel(type, 1, green, out_pixel); break; case GL_R3_G3_B2: case GL_RGB4: case GL_RGB5: case GL_RGB8: case GL_RGB8_SNORM: case GL_RGB10: case GL_R11F_G11F_B10F: case GL_RGB12: case GL_RGB16: case GL_RGB16F: case GL_RGB16_SNORM: case GL_RGB32F: case GL_RGB8I: case GL_RGB8UI: case GL_RGB16I: case GL_RGB16UI: case GL_RGB32I: case GL_RGB32UI: writeChannel(type, 0, red, out_pixel); writeChannel(type, 1, green, out_pixel); writeChannel(type, 2, blue, out_pixel); break; case GL_RGB9_E5: case GL_RGBA2: case GL_RGBA4: case GL_RGB5_A1: case GL_RGBA8: case GL_RGBA8_SNORM: case GL_RGB10_A2: case GL_RGBA12: case GL_RGBA16: case GL_RGBA16F: case GL_RGBA16_SNORM: case GL_RGBA32F: case GL_RGBA8I: case GL_RGBA8UI: case GL_RGB10_A2UI: case GL_RGBA16I: case GL_RGBA16UI: case GL_RGBA32I: case GL_RGBA32UI: writeChannel(type, 0, red, out_pixel); writeChannel(type, 1, green, out_pixel); writeChannel(type, 2, blue, out_pixel); writeChannel(type, 3, alpha, out_pixel); break; default: TCU_FAIL("Invalid enum"); break; } } /** Unpacks channels from pixel * * @param internal_format Internal format of image * @param type Type used by image * @param pixel Pixel data * @param red Red channel * @param green Green channel * @param blue Blue channel * @param alpha Alpha channel **/ void Utils::unpackPixel(GLenum format, GLenum type, const GLubyte* pixel, GLdouble& out_red, GLdouble& out_green, GLdouble& out_blue, GLdouble& out_alpha) { switch (format) { case GL_RED: case GL_RED_INTEGER: readChannel(type, 0, pixel, out_red); out_green = 1.0; out_blue = 1.0; out_alpha = 1.0; break; case GL_RG: case GL_RG_INTEGER: readChannel(type, 0, pixel, out_red); readChannel(type, 1, pixel, out_green); out_blue = 1.0; out_alpha = 1.0; break; case GL_RGB: case GL_RGB_INTEGER: switch (type) { case GL_UNSIGNED_INT_5_9_9_9_REV: readChannel(type, 0, pixel, out_red); readChannel(type, 1, pixel, out_green); readChannel(type, 2, pixel, out_blue); readChannel(type, 3, pixel, out_alpha); break; default: readChannel(type, 0, pixel, out_red); readChannel(type, 1, pixel, out_green); readChannel(type, 2, pixel, out_blue); out_alpha = 1.0; break; } break; case GL_RGBA: case GL_RGBA_INTEGER: readChannel(type, 0, pixel, out_red); readChannel(type, 1, pixel, out_green); readChannel(type, 2, pixel, out_blue); readChannel(type, 3, pixel, out_alpha); break; default: TCU_FAIL("Invalid enum"); break; } } inline bool Utils::roundComponent(GLenum internal_format, GLenum component, GLdouble& value) { int exponent = (internal_format == GL_RGB4 ? 4 : (internal_format == GL_RGB5 ? 5 : 0)); if (!exponent) return false; //Currently this only happens with GL_RGB4 and GL_RGB5 when stored as 565 type. int rounded_value = static_cast<int>(floor((pow(2, exponent) - 1) * value + 0.5)); int multiplier = (component == GL_GREEN ? 2 : 1); if (internal_format == GL_RGB4) { multiplier *= 2; } value = rounded_value * multiplier; return true; } /** Unpacks pixels and compars them * * @param left_format Format of left image * @param left_type Type of left image * @param left_internal_format Internal format of left image * @param left_pixel Data of left pixel * @param right_format Format of right image * @param right_type Type of right image * @param right_internal_format Internal format of right image * @param right_pixel Data of right pixel * * @return true if pixels match, false otherwise **/ bool Utils::unpackAndComaprePixels(GLenum left_format, GLenum left_type, GLenum left_internal_format, const GLubyte* left_pixel, GLenum right_format, GLenum right_type, GLenum right_internal_format, const GLubyte* right_pixel) { GLdouble left_red; GLdouble left_green; GLdouble left_blue; GLdouble left_alpha; GLdouble right_red; GLdouble right_green; GLdouble right_blue; GLdouble right_alpha; unpackPixel(left_format, left_type, left_pixel, left_red, left_green, left_blue, left_alpha); unpackPixel(right_format, right_type, right_pixel, right_red, right_green, right_blue, right_alpha); roundComponent(left_internal_format, GL_RED, left_red); roundComponent(left_internal_format, GL_GREEN, left_green); roundComponent(left_internal_format, GL_BLUE, left_blue); roundComponent(right_internal_format, GL_RED, right_red); roundComponent(right_internal_format, GL_GREEN, right_green); roundComponent(right_internal_format, GL_BLUE, right_blue); return comparePixels(left_internal_format, left_red, left_green, left_blue, left_alpha, right_internal_format, right_red, right_green, right_blue, right_alpha); } /* FunctionalTest */ #define FUNCTIONAL_TEST_N_LAYERS 12 #define FUNCTIONAL_TEST_N_LEVELS 3 /** Constructor * * @param context Text context **/ FunctionalTest::FunctionalTest(deqp::Context& context) : TestCase(context, "functional", "Test verifies CopySubImageData copy data as requested") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_rb_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { for (GLuint src_tgt_id = 0; src_tgt_id < s_n_valid_targets; ++src_tgt_id) { const GLenum src_target = s_valid_targets[src_tgt_id]; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS == 0 if ((GL_TEXTURE_1D == src_target) || (GL_TEXTURE_1D_ARRAY == src_target) || (GL_TEXTURE_2D == src_target) || (GL_TEXTURE_CUBE_MAP == src_target) || (GL_TEXTURE_CUBE_MAP_ARRAY == src_target)) { continue; } #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS == 0 */ for (GLuint dst_tgt_id = 0; dst_tgt_id < s_n_valid_targets; ++dst_tgt_id) { const GLenum dst_target = s_valid_targets[dst_tgt_id]; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS == 0 if ((GL_TEXTURE_1D == dst_target) || (GL_TEXTURE_1D_ARRAY == dst_target) || (GL_TEXTURE_2D == dst_target) || (GL_TEXTURE_CUBE_MAP == dst_target) || (GL_TEXTURE_CUBE_MAP_ARRAY == dst_target)) { continue; } #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_TARGETS == 0 */ /* Skip render buffer as destination */ if (GL_RENDERBUFFER == dst_target) { continue; } /* Skip multisampled */ if ((true == Utils::isTargetMultisampled(src_target)) || (true == Utils::isTargetMultisampled(dst_target))) { continue; } for (GLuint src_frmt_id = 0; src_frmt_id < s_n_internal_formats; ++src_frmt_id) { const GLenum src_format = s_internal_formats[src_frmt_id]; if (src_format == GL_RGB9_E5 && src_target == GL_RENDERBUFFER) { continue; } for (GLuint dst_frmt_id = 0; dst_frmt_id < s_n_internal_formats; ++dst_frmt_id) { const GLenum dst_format = s_internal_formats[dst_frmt_id]; /* Skip not compatible formats */ if (false == Utils::areFormatsCompatible(src_format, dst_format)) { continue; } prepareTestCases(dst_format, dst_target, src_format, src_target); } } } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult FunctionalTest::iterate() { GLubyte* dst_pixels[FUNCTIONAL_TEST_N_LEVELS] = { 0 }; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLubyte* src_pixels[FUNCTIONAL_TEST_N_LEVELS] = { 0 }; const testCase& test_case = m_test_cases[m_test_case_index]; gl.pixelStorei(GL_PACK_ALIGNMENT, 1); gl.pixelStorei(GL_UNPACK_ALIGNMENT, 1); GLU_EXPECT_NO_ERROR(gl.getError(), "PixelStorei"); try { /* Prepare pixels */ prepareDstPxls(test_case.m_dst, dst_pixels); prepareSrcPxls(test_case.m_src, test_case.m_dst.m_internal_format, src_pixels); /* Prepare textures */ m_dst_tex_name = prepareTexture(test_case.m_dst, (const GLubyte**)dst_pixels, m_dst_buf_name); if (GL_RENDERBUFFER == test_case.m_src.m_target) { targetDesc desc = test_case.m_src; desc.m_target = GL_TEXTURE_2D; m_rb_name = prepareTexture(test_case.m_src, (const GLubyte**)src_pixels, m_src_buf_name); m_src_tex_name = prepareTexture(desc, (const GLubyte**)src_pixels, m_src_buf_name); } else { m_src_tex_name = prepareTexture(test_case.m_src, (const GLubyte**)src_pixels, m_src_buf_name); } /* Copy images and verify results */ result = copyAndVerify(test_case, (const GLubyte**)dst_pixels, (const GLubyte**)src_pixels); } catch (tcu::Exception& exc) { clean(); cleanPixels((GLubyte**)dst_pixels); cleanPixels((GLubyte**)src_pixels); throw exc; } /* Free resources */ clean(); cleanPixels((GLubyte**)dst_pixels); cleanPixels((GLubyte**)src_pixels); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. " << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Calculate dimmensions of all levels based on size of specific level * * @param target Target of image * @param level Level index * @param width Width of image at <level> * @param height Height of image at <level> * @param out_widths Calcualted widths, array of FUNCTIONAL_TEST_N_LEVELS'th elements * @param out_heights Calculated heights, array of FUNCTIONAL_TEST_N_LEVELS'th elements * @param out_depths Calculated dephts, array of FUNCTIONAL_TEST_N_LEVELS'th elements **/ void FunctionalTest::calculateDimmensions(GLenum target, GLuint level, GLuint width, GLuint height, GLuint* out_widths, GLuint* out_heights, GLuint* out_depths) const { GLuint divide = 100; GLuint factors[FUNCTIONAL_TEST_N_LEVELS]; GLuint factor = divide; const bool is_multi_layer = Utils::isTargetMultilayer(target); const GLuint n_layers = (true == is_multi_layer) ? FUNCTIONAL_TEST_N_LAYERS : 1; for (GLint i = (GLint)level; i >= 0; --i) { factors[i] = factor; factor *= 2; } factor = divide / 2; for (GLuint i = level + 1; i < FUNCTIONAL_TEST_N_LEVELS; ++i) { factors[i] = factor; factor /= 2; } for (GLuint i = 0; i < FUNCTIONAL_TEST_N_LEVELS; ++i) { out_widths[i] = width * factors[i] / divide; out_heights[i] = height * factors[i] / divide; if (GL_TEXTURE_3D == target) { out_depths[i] = FUNCTIONAL_TEST_N_LAYERS * factors[i] / divide; } else { out_depths[i] = n_layers; } } } /** Execute copyImageSubData for given test case and verify results * * @param test_case Test case * @param dst_pixels Data of destination image * @param src_pixels Data of source image * * @return true if there is no error and results match expectations, false otherwise **/ bool FunctionalTest::copyAndVerify(const testCase& test_case, const GLubyte** dst_pixels, const GLubyte** src_pixels) { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); GLuint region_depth = 1; GLuint dst_layer_step = 0; const bool is_dst_multi_layer = Utils::isTargetMultilayer(test_case.m_dst.m_target); const bool is_src_multi_layer = Utils::isTargetMultilayer(test_case.m_src.m_target); bool result = false; GLuint src_layer_step = 0; GLuint n_layers = 1; /* Configure layers */ if ((true == is_dst_multi_layer) || (true == is_src_multi_layer)) { if (is_src_multi_layer == is_dst_multi_layer) { /* Both objects are multilayered, copy all layers at once, verify at once */ region_depth = FUNCTIONAL_TEST_N_LAYERS; } else if (true == is_dst_multi_layer) { /* Destination is multilayered, copy each layer separetly, verify at once */ n_layers = FUNCTIONAL_TEST_N_LAYERS; dst_layer_step = 1; } else { /* Destination is multilayered, copy and verify each layer separetly */ n_layers = FUNCTIONAL_TEST_N_LAYERS; src_layer_step = 1; } } /* Copy and verification */ { GLuint dst_layer = 0; GLuint src_layer = 0; /* For each layer */ for (GLuint layer = 0; layer < n_layers; ++layer) { if (0 == m_rb_name) { gl.copyImageSubData(m_src_tex_name, test_case.m_src.m_target, test_case.m_src.m_level, test_case.m_src_x, test_case.m_src_y, src_layer, m_dst_tex_name, test_case.m_dst.m_target, test_case.m_dst.m_level, test_case.m_dst_x, test_case.m_dst_y, dst_layer, test_case.m_width, test_case.m_height, region_depth); } else /* Copy from src to rb and from rb to dst */ { /* Src and rb shares differs only on target */ gl.copyImageSubData(m_src_tex_name, GL_TEXTURE_2D, test_case.m_src.m_level, test_case.m_src_x, test_case.m_src_y, src_layer, m_rb_name, test_case.m_src.m_target, test_case.m_src.m_level, test_case.m_src_x, test_case.m_src_y, src_layer, test_case.m_width, test_case.m_height, region_depth); gl.copyImageSubData(m_rb_name, test_case.m_src.m_target, test_case.m_src.m_level, test_case.m_src_x, test_case.m_src_y, src_layer, m_dst_tex_name, test_case.m_dst.m_target, test_case.m_dst.m_level, test_case.m_dst_x, test_case.m_dst_y, dst_layer, test_case.m_width, test_case.m_height, region_depth); } /* Verify generated error */ error = gl.getError(); if (GL_NO_ERROR == error) { /* Verify copy results */ result = verify(test_case, dst_layer, dst_pixels, src_layer, src_pixels, region_depth); } if ((GL_NO_ERROR != error) || (false == result)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Targets src: " << glu::getTextureTargetStr(test_case.m_src.m_target) << ", dst: " << glu::getTextureTargetStr(test_case.m_dst.m_target) << ". Levels src: " << test_case.m_src.m_level << ", dst: " << test_case.m_dst.m_level << ". Dimmensions src [" << test_case.m_src.m_width << ", " << test_case.m_src.m_height << "], dst [" << test_case.m_dst.m_width << ", " << test_case.m_dst.m_height << "]. Region [" << test_case.m_width << " x " << test_case.m_height << " x " << region_depth << "] from [" << test_case.m_src_x << ", " << test_case.m_src_y << ", " << src_layer << "] to [" << test_case.m_dst_x << ", " << test_case.m_dst_y << ", " << dst_layer << "]. Format src: " << glu::getInternalFormatParameterStr(test_case.m_src.m_internal_format) << ", dst: " << glu::getInternalFormatParameterStr(test_case.m_dst.m_internal_format) << tcu::TestLog::EndMessage; if (GL_NO_ERROR != error) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failed due to error: " << glu::getErrorStr(error) << tcu::TestLog::EndMessage; TCU_FAIL("Copy operation failed"); } return false; } /* Step one layer */ dst_layer += dst_layer_step; src_layer += src_layer_step; } } return true; } /** Cleans resources * **/ void FunctionalTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_rb_name) { gl.deleteRenderbuffers(1, &m_rb_name); m_rb_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /** Free memory allocated for images * * @param pixels Array of pointers to image data **/ void FunctionalTest::cleanPixels(GLubyte** pixels) const { for (GLuint i = 0; i < FUNCTIONAL_TEST_N_LEVELS; ++i) { if (0 != pixels[i]) { delete[] pixels[i]; pixels[i] = 0; } } } /** Compare two images * @param left_desc Descriptor of left image * @param left_data Data of left image * @param left_x X of left image * @param left_y Y of left image * @param left_layer Layer of left image * @param left_level Level of left image * @param right_desc Descriptor of right image * @param right_data Data of right image * @param right_x X of right image * @param right_y Y of right image * @param right_layer Layer of right image * @param right_level Level of right image * @param region_width Width of region to compare * @param region_height Height of region to compare * * @return true if images are considered idenctial, false otherwise **/ bool FunctionalTest::compareImages(const targetDesc& left_desc, const GLubyte* left_data, GLuint left_x, GLuint left_y, GLuint left_layer, GLuint left_level, const targetDesc& right_desc, const glw::GLubyte* right_data, GLuint right_x, GLuint right_y, GLuint right_layer, GLuint right_level, GLuint region_width, GLuint region_height) const { /* Get level dimmensions */ GLuint left_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint left_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint left_depths[FUNCTIONAL_TEST_N_LEVELS]; GLuint right_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint right_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint right_depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(left_desc.m_target, left_desc.m_level, left_desc.m_width, left_desc.m_height, left_widths, left_heights, left_depths); calculateDimmensions(right_desc.m_target, right_desc.m_level, right_desc.m_width, right_desc.m_height, right_widths, right_heights, right_depths); /* Constants */ /* Dimmensions */ const GLuint left_height = left_heights[left_level]; const GLuint left_width = left_widths[left_level]; const GLuint right_height = right_heights[right_level]; const GLuint right_width = right_widths[right_level]; /* Sizes */ const GLuint left_pixel_size = Utils::getPixelSizeForFormat(left_desc.m_internal_format); const GLuint left_line_size = left_pixel_size * left_width; const GLuint left_layer_size = left_line_size * left_height; const GLuint right_pixel_size = Utils::getPixelSizeForFormat(right_desc.m_internal_format); const GLuint right_line_size = right_pixel_size * right_width; const GLuint right_layer_size = right_line_size * right_height; /* Offsets */ const GLuint left_layer_offset = left_layer_size * left_layer; const GLuint left_reg_line_offset = left_line_size * left_y; const GLuint left_reg_pix_offset = left_pixel_size * left_x; const GLuint right_layer_offset = right_layer_size * right_layer; const GLuint right_reg_line_offset = right_line_size * right_y; const GLuint right_reg_pix_offset = right_pixel_size * right_x; /* Pointers */ const GLubyte* left_layer_data = left_data + left_layer_offset; const GLubyte* right_layer_data = right_data + right_layer_offset; /* For each line of region */ for (GLuint y = 0; y < region_height; ++y) { /* Offsets */ const GLuint left_line_offset = left_reg_line_offset + y * left_line_size; const GLuint right_line_offset = right_reg_line_offset + y * right_line_size; /* Pointers */ const GLubyte* left_line_data = left_layer_data + left_line_offset; const GLubyte* right_line_data = right_layer_data + right_line_offset; /* For each pixel of region */ for (GLuint x = 0; x < region_width; ++x) { /* Offsets */ const GLuint left_pixel_offset = left_reg_pix_offset + x * left_pixel_size; const GLuint right_pixel_offset = right_reg_pix_offset + x * right_pixel_size; /* Pointers */ const GLubyte* left_pixel_data = left_line_data + left_pixel_offset; const GLubyte* right_pixel_data = right_line_data + right_pixel_offset; /* Compare */ if (false == Utils::comparePixels(left_pixel_size, left_pixel_data, right_pixel_size, right_pixel_data, left_desc.m_internal_format)) { if (false == Utils::unpackAndComaprePixels(left_desc.m_format, left_desc.m_type, left_desc.m_internal_format, left_pixel_data, right_desc.m_format, right_desc.m_type, right_desc.m_internal_format, right_pixel_data)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Not matching pixels found. Left: [" << x + left_x << ", " << y + left_y << ", " << left_layer << "] lvl:" << left_level << ", off: " << left_pixel_data - left_data << ", data: " << Utils::getPixelString(left_desc.m_internal_format, left_pixel_data) << ". Right: [" << x + right_x << ", " << y + right_y << ", " << right_layer << "] lvl: " << right_level << ", off: " << right_pixel_data - right_data << ", data: " << Utils::getPixelString(right_desc.m_internal_format, right_pixel_data) << tcu::TestLog::EndMessage; return false; } } } } return true; } /** Prepare regions that should not be modified during test case * * @param test_case Test case descriptor * @param dst_level Level of destination image * @param out_regions Number of regions * @param out_n_regions Regions **/ void FunctionalTest::getCleanRegions(const testCase& test_case, GLuint dst_level, GLuint out_regions[4][4], GLuint& out_n_regions) const { GLuint dst_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_depths[FUNCTIONAL_TEST_N_LEVELS]; out_n_regions = 0; calculateDimmensions(test_case.m_dst.m_target, dst_level, test_case.m_dst.m_width, test_case.m_dst.m_height, dst_widths, dst_heights, dst_depths); /* Constants */ /* Copied region */ const GLuint reg_x = test_case.m_dst_x; const GLuint reg_y = test_case.m_dst_y; const GLuint reg_w = test_case.m_width; const GLuint reg_h = test_case.m_height; const GLuint reg_r = reg_x + reg_w; const GLuint reg_t = reg_y + reg_h; /* Image */ const GLuint img_w = dst_widths[dst_level]; const GLuint img_h = dst_heights[dst_level]; /* Bottom row */ if (0 != reg_y) { out_regions[out_n_regions][0] = 0; out_regions[out_n_regions][1] = 0; out_regions[out_n_regions][2] = img_w; out_regions[out_n_regions][3] = reg_y; out_n_regions += 1; } /* Left edge */ if (0 != reg_x) { out_regions[out_n_regions][0] = 0; out_regions[out_n_regions][1] = reg_y; out_regions[out_n_regions][2] = reg_x; out_regions[out_n_regions][3] = reg_h; out_n_regions += 1; } /* Right edge */ if (img_w != reg_r) { out_regions[out_n_regions][0] = reg_r; out_regions[out_n_regions][1] = reg_y; out_regions[out_n_regions][2] = img_w - reg_r; out_regions[out_n_regions][3] = reg_h; out_n_regions += 1; } /* Top row */ if (img_h != reg_t) { out_regions[out_n_regions][0] = 0; out_regions[out_n_regions][1] = reg_t; out_regions[out_n_regions][2] = img_w; out_regions[out_n_regions][3] = img_h - reg_t; out_n_regions += 1; } } /** Get pixel data for image * * @param name Name of image * @param desc Descriptor of image * @param level Level to capture * @param out_pixels Pixels **/ void FunctionalTest::getPixels(GLuint name, const targetDesc& desc, GLuint level, GLubyte* out_pixels) const { const Functions& gl = m_context.getRenderContext().getFunctions(); gl.bindTexture(desc.m_target, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.getTexImage(desc.m_target, level, desc.m_format, desc.m_type, out_pixels); GLU_EXPECT_NO_ERROR(gl.getError(), "GetTexImage"); gl.bindTexture(desc.m_target, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); } /** Prepare data for destination image * * @param desc Descriptor * @param out_pixels Array of pointer to image data **/ void FunctionalTest::prepareDstPxls(const FunctionalTest::targetDesc& desc, GLubyte** out_pixels) const { const GLenum internal_format = desc.m_internal_format; const bool is_multi_level = Utils::isTargetMultilevel(desc.m_target); GLuint n_levels = 1; const GLuint pixel_size = Utils::getPixelSizeForFormat(desc.m_internal_format); const GLenum type = desc.m_type; /* Configure levels */ if (true == is_multi_level) { n_levels = FUNCTIONAL_TEST_N_LEVELS; } /* Calculate dimmensions */ GLuint heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(desc.m_target, desc.m_level, desc.m_width, desc.m_height, widths, heights, depths); /* Prepare storage */ for (GLuint i = 0; i < n_levels; ++i) { const GLuint req_memory_per_layer = pixel_size * widths[i] * heights[i]; const GLuint req_memory_for_level = req_memory_per_layer * depths[i]; out_pixels[i] = new GLubyte[req_memory_for_level]; if (0 == out_pixels[i]) { TCU_FAIL("Memory allocation failed"); } memset(out_pixels[i], 0, req_memory_for_level); } /* Fill pixels */ for (GLuint i = 0; i < n_levels; ++i) { const GLuint n_layers = depths[i]; const GLuint n_pixels = widths[i] * heights[i]; GLubyte* ptr = (GLubyte*)out_pixels[i]; for (GLuint j = 0; j < n_pixels * n_layers; ++j) { GLubyte* pixel_data = ptr + j * pixel_size; Utils::packPixel(internal_format, type, 1.0, 1.0, 1.0, 1.0, pixel_data); } } } /** Prepare data for source image * * @param desc Descriptor * @param dst_internal_format Internal format of destination image * @param out_pixels Array of pointer to image data **/ void FunctionalTest::prepareSrcPxls(const FunctionalTest::targetDesc& desc, GLenum /* dst_internal_format */, GLubyte** out_pixels) const { const GLenum internal_format = desc.m_internal_format; const bool is_multi_level = Utils::isTargetMultilevel(desc.m_target); GLuint n_levels = 1; const GLuint pixel_size = Utils::getPixelSizeForFormat(desc.m_internal_format); const GLenum type = desc.m_type; /* Configure levels */ if (true == is_multi_level) { n_levels = FUNCTIONAL_TEST_N_LEVELS; } /* Calculate dimmensions */ GLuint heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(desc.m_target, desc.m_level, desc.m_width, desc.m_height, widths, heights, depths); /* Prepare storage */ for (GLuint i = 0; i < n_levels; ++i) { const GLuint req_memory_per_layer = pixel_size * widths[i] * heights[i]; const GLuint req_memory_for_level = req_memory_per_layer * depths[i]; out_pixels[i] = new GLubyte[req_memory_for_level]; if (0 == out_pixels[i]) { TCU_FAIL("Memory allocation failed"); } memset(out_pixels[i], 0, req_memory_for_level); } for (GLuint lvl = 0; lvl < n_levels; ++lvl) { const GLuint n_layers = depths[lvl]; const GLuint line_size = pixel_size * widths[lvl]; const GLuint req_memory_per_layer = line_size * heights[lvl]; GLubyte* level = (GLubyte*)out_pixels[lvl]; for (GLuint lay = 0; lay < n_layers; ++lay) { const GLuint layer_offset = lay * req_memory_per_layer; GLubyte* layer = ((GLubyte*)level) + layer_offset; for (GLuint y = 0; y < heights[lvl]; ++y) { const GLuint line_offset = line_size * y; GLubyte* line = layer + line_offset; for (GLuint x = 0; x < widths[lvl]; ++x) { const GLuint pixel_offset = x * pixel_size; GLubyte* pixel = line + pixel_offset; /* 255 is max ubyte. 1/15.9375 = 16/255 */ const GLdouble red = ((GLdouble)x) / 255.0 + (((GLdouble)y) / 15.9375); const GLdouble green = ((GLdouble)lay) / 255.0 + (((GLdouble)lvl) / 15.9375); const GLdouble blue = 0.125; const GLdouble alpha = 1.0; /* This value has special meaning for some internal_formats */ Utils::packPixel(internal_format, type, red, green, blue, alpha, pixel); } } } } } /** Prepare test cases for given targets and internal formats * * @param dst_internal_format Internal format of destination image * @param dst_target Target of destination image * @param src_internal_format Internal format of source image * @param src_target Target of source image **/ void FunctionalTest::prepareTestCases(GLenum dst_internal_format, GLenum dst_target, GLenum src_internal_format, GLenum src_target) { static const GLuint image_dimmensions[] = { 7, #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_IMG_DIM 8, 9, 10, 11, 12, 13, 14, #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_IMG_DIM */ 15 }; static const GLuint region_dimmensions[] = { 1, #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_DIM 2, 3, 4, 5, 6, #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_DIM */ 7 }; static const GLuint n_image_dimmensions = sizeof(image_dimmensions) / sizeof(image_dimmensions[0]); static const GLuint n_region_dimmensions = sizeof(region_dimmensions) / sizeof(region_dimmensions[0]); const bool is_dst_multi_level = Utils::isTargetMultilevel(dst_target); const bool is_src_multi_level = Utils::isTargetMultilevel(src_target); const GLenum dst_format = Utils::getFormat(dst_internal_format); const GLuint dst_n_levels = (true == is_dst_multi_level) ? FUNCTIONAL_TEST_N_LEVELS : 1; const GLenum dst_type = Utils::getType(dst_internal_format); const GLenum src_format = Utils::getFormat(src_internal_format); const GLuint src_n_levels = (true == is_src_multi_level) ? FUNCTIONAL_TEST_N_LEVELS : 1; const GLenum src_type = Utils::getType(src_internal_format); for (GLuint src_level = 0; src_level < src_n_levels; ++src_level) { for (GLuint dst_level = 0; dst_level < dst_n_levels; ++dst_level) { for (GLuint src_img_dim_id = 0; src_img_dim_id < n_image_dimmensions; ++src_img_dim_id) { const GLuint src_image_dimmension = image_dimmensions[src_img_dim_id]; for (GLuint dst_img_dim_id = 0; dst_img_dim_id < n_image_dimmensions; ++dst_img_dim_id) { const GLuint dst_image_dimmension = image_dimmensions[dst_img_dim_id]; for (GLuint reg_dim_id = 0; reg_dim_id < n_region_dimmensions; ++reg_dim_id) { const GLuint region_dimmension = region_dimmensions[reg_dim_id]; GLuint dst_coord[3] = { 0, 0, 0 }; const GLuint dst_dim_diff = dst_image_dimmension - region_dimmension; GLuint n_dst_coords = 1; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS GLuint n_src_coords = 1; #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ GLuint src_coord[3] = { 0, 0, 0 }; const GLuint src_dim_diff = src_image_dimmension - region_dimmension; /* Calculate coords */ if (1 == dst_dim_diff) { dst_coord[1] = 1; n_dst_coords = 2; } else if (1 < dst_dim_diff) { dst_coord[1] = dst_dim_diff / 2; dst_coord[2] = dst_dim_diff; n_dst_coords = 3; } if (1 == src_dim_diff) { src_coord[1] = 1; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS n_src_coords = 2; #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ } else if (1 < src_dim_diff) { src_coord[1] = src_dim_diff / 2; src_coord[2] = src_dim_diff; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS n_src_coords = 3; #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ } testCase test_case = { { /* m_dst */ dst_target, dst_image_dimmension, /* width */ dst_image_dimmension, /* height */ dst_level, dst_internal_format, dst_format, dst_type }, 0, /* dst_x */ 0, /* dst_y */ { /* m_src */ src_target, src_image_dimmension, /* width */ src_image_dimmension, /* height */ src_level, src_internal_format, src_format, src_type }, 0, /* src_x */ 0, /* src_y */ region_dimmension, /* width */ region_dimmension, /* height */ }; #if COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS for (GLuint src_x = 0; src_x < n_src_coords; ++src_x) { for (GLuint src_y = 0; src_y < n_src_coords; ++src_y) { for (GLuint dst_x = 0; dst_x < n_dst_coords; ++dst_x) { for (GLuint dst_y = 0; dst_y < n_dst_coords; ++dst_y) { test_case.m_dst_x = dst_coord[dst_x]; test_case.m_dst_y = dst_coord[dst_y]; test_case.m_src_x = src_coord[src_x]; test_case.m_src_y = src_coord[src_y]; m_test_cases.push_back(test_case); } } } } #else /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ test_case.m_dst_x = dst_coord[n_dst_coords - 1]; test_case.m_dst_y = dst_coord[n_dst_coords - 1]; test_case.m_src_x = src_coord[0]; test_case.m_src_y = src_coord[0]; m_test_cases.push_back(test_case); #endif /* COPY_IMAGE_FUNCTIONAL_TEST_ENABLE_ALL_REG_POS */ /* Whole image, for non 7x7 */ if ((dst_image_dimmension == src_image_dimmension) && (image_dimmensions[0] != dst_image_dimmension)) { test_case.m_dst_x = 0; test_case.m_dst_y = 0; test_case.m_src_x = 0; test_case.m_src_y = 0; test_case.m_width = dst_image_dimmension; test_case.m_height = dst_image_dimmension; m_test_cases.push_back(test_case); } } } } } } } /** Prepare texture * * @param desc Descriptor * @param pixels Image data * @param out_buf_id Id of buffer used by texture buffer * * @return Name of iamge **/ GLuint FunctionalTest::prepareTexture(const targetDesc& desc, const GLubyte** pixels, GLuint& out_buf_id) { GLuint name = Utils::generateTexture(m_context, desc.m_target); if (false == Utils::isTargetMultilevel(desc.m_target)) { Utils::prepareTexture(m_context, name, desc.m_target, desc.m_internal_format, desc.m_format, desc.m_type, 0 /* level */, desc.m_width, desc.m_height, FUNCTIONAL_TEST_N_LAYERS /* depth - 12 for multilayered, 1D and 2D will ignore that */, pixels[0], out_buf_id); Utils::makeTextureComplete(m_context, desc.m_target, name, 0 /* base */, 0 /* max */); } else { /* Calculate dimmensions */ GLuint heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(desc.m_target, desc.m_level, desc.m_width, desc.m_height, widths, heights, depths); for (GLuint level = 0; level < FUNCTIONAL_TEST_N_LEVELS; ++level) { Utils::prepareTexture(m_context, name, desc.m_target, desc.m_internal_format, desc.m_format, desc.m_type, level, widths[level], heights[level], depths[level], pixels[level], out_buf_id); Utils::makeTextureComplete(m_context, desc.m_target, name, 0 /* base */, 2 /* max */); } } return name; } /** Verify copy operation * * @param test_case Test case * @param dst_layer First layer modified by copy * @param dst_pixels Origiranl data of destination image * @param src_layer First layer read by copy * @param src_pixels Original data of source image * @param depth Number of copied layers * * @return true if everything is as expected, false otherwise **/ bool FunctionalTest::verify(const testCase& test_case, GLuint dst_layer, const GLubyte** dst_pixels, GLuint src_layer, const GLubyte** src_pixels, GLuint depth) { const bool is_dst_multi_level = Utils::isTargetMultilevel(test_case.m_dst.m_target); const bool is_src_multi_level = Utils::isTargetMultilevel(test_case.m_src.m_target); const GLuint dst_level = test_case.m_dst.m_level; std::vector<GLubyte> dst_level_data; const GLuint dst_pixel_size = Utils::getPixelSizeForFormat(test_case.m_dst.m_internal_format); targetDesc src_desc = test_case.m_src; const GLuint src_level = src_desc.m_level; std::vector<GLubyte> src_level_data; const GLuint src_pixel_size = Utils::getPixelSizeForFormat(src_desc.m_internal_format); if (0 != m_rb_name) { src_desc.m_target = GL_TEXTURE_2D; } /* Calculate storage requirements */ GLuint dst_req_mem_per_layer[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint dst_depths[FUNCTIONAL_TEST_N_LEVELS]; GLuint src_req_mem_per_layer[FUNCTIONAL_TEST_N_LEVELS]; GLuint src_heights[FUNCTIONAL_TEST_N_LEVELS]; GLuint src_widths[FUNCTIONAL_TEST_N_LEVELS]; GLuint src_depths[FUNCTIONAL_TEST_N_LEVELS]; calculateDimmensions(test_case.m_dst.m_target, dst_level, test_case.m_dst.m_width, test_case.m_dst.m_height, dst_widths, dst_heights, dst_depths); calculateDimmensions(src_desc.m_target, src_level, src_desc.m_width, src_desc.m_height, src_widths, src_heights, src_depths); for (GLuint i = 0; i < FUNCTIONAL_TEST_N_LEVELS; ++i) { dst_req_mem_per_layer[i] = dst_widths[i] * dst_heights[i] * dst_pixel_size; src_req_mem_per_layer[i] = src_widths[i] * src_heights[i] * src_pixel_size; } /* Prepare storage, use 0 level as it is the biggest one */ dst_level_data.resize(dst_req_mem_per_layer[0] * dst_depths[0]); src_level_data.resize(src_req_mem_per_layer[0] * src_depths[0]); /* Verification of contents * - source image - expect no modification * - destination image, mipmap before and after dst_level - expect no modification * - destination image, mipmap at dst_level: * * layers after dst_layer + depth - expect no modification * * layers <0, dst_layer + depth> - expect that contents at selected region were copied */ /* Check if source image was not modified */ { const GLuint n_levels = (true == is_src_multi_level) ? FUNCTIONAL_TEST_N_LEVELS : 1; for (GLuint level = 0; level < n_levels; ++level) { getPixels(m_src_tex_name, src_desc, level, &src_level_data[0]); for (GLuint layer = 0; layer < src_depths[level]; ++layer) { if (false == compareImages(src_desc, src_pixels[level], 0, 0, layer, level, src_desc, &src_level_data[0], 0, 0, layer, level, src_widths[level], src_heights[level])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents of source image. Original data: left." << tcu::TestLog::EndMessage; return false; } } } } /* Check if contents of destination at levels != dst_level were not modified */ { const GLuint n_levels = (true == is_dst_multi_level) ? FUNCTIONAL_TEST_N_LEVELS : 1; for (GLuint level = 0; level < n_levels; ++level) { if (dst_level == level) { continue; } getPixels(m_dst_tex_name, test_case.m_dst, level, &dst_level_data[0]); for (GLuint layer = 0; layer < dst_depths[level]; ++layer) { if (false == compareImages(test_case.m_dst, dst_pixels[level], 0, 0, layer, level, test_case.m_dst, &dst_level_data[0], 0, 0, layer, level, dst_widths[level], dst_heights[level])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents of wrong mipmap level. Original data: left." << tcu::TestLog::EndMessage; return false; } } } } /* Check contents of modified level */ { getPixels(m_dst_tex_name, test_case.m_dst, dst_level, &dst_level_data[0]); /* Check anything after dst_layer + depth */ { for (GLuint layer = dst_layer + depth; layer < dst_depths[dst_level]; ++layer) { if (false == compareImages(test_case.m_dst, dst_pixels[dst_level], 0, 0, layer, dst_level, test_case.m_dst, &dst_level_data[0], 0, 0, layer, dst_level, dst_widths[dst_level], dst_heights[dst_level])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents of wrong layer. Original data: left." << tcu::TestLog::EndMessage; return false; } } } /* Check modified layers */ for (GLuint layer = 0; layer < depth; ++layer) { /* Check contents outside of copied region */ { GLuint n_regions = 0; GLuint regions[4][4] = { { 0 } }; getCleanRegions(test_case, dst_level, regions, n_regions); for (GLuint region = 0; region < n_regions; ++region) { const GLuint x = regions[region][0]; const GLuint y = regions[region][1]; const GLuint w = regions[region][2]; const GLuint h = regions[region][3]; if (false == compareImages(test_case.m_dst, dst_pixels[dst_level], x, y, layer + dst_layer, dst_level, test_case.m_dst, &dst_level_data[0], x, y, layer + dst_layer, dst_level, w, h)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents outside of copied region. Original data: left." << tcu::TestLog::EndMessage; return false; } } } /* Check contents of copied region */ if (false == compareImages(test_case.m_dst, &dst_level_data[0], test_case.m_dst_x, test_case.m_dst_y, layer + dst_layer, dst_level, src_desc, src_pixels[src_level], test_case.m_src_x, test_case.m_src_y, layer + src_layer, src_level, test_case.m_width, test_case.m_height)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData stored invalid data in copied region. Destination data: left." << tcu::TestLog::EndMessage; return false; } } } return true; } /* SmokeTest */ /* Constants */ const GLuint SmokeTest::m_width = 16; const GLuint SmokeTest::m_height = 16; const GLuint SmokeTest::m_depth = 1; /** Constructor * * @param context Text context **/ SmokeTest::SmokeTest(deqp::Context& context) : TestCase(context, "smoke_test", "Test tries all formats and targets") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_rb_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* Iterate over valid targets */ for (GLuint tgt_id = 0; tgt_id < s_n_valid_targets; ++tgt_id) { const GLenum target = s_valid_targets[tgt_id]; if (true == Utils::isTargetMultisampled(target)) { continue; } const testCase test_case = { target, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT }; m_test_cases.push_back(test_case); } /* Iterate over internal formats */ for (GLuint fmt_id = 0; fmt_id < s_n_internal_formats; ++fmt_id) { const GLenum internal_format = s_internal_formats[fmt_id]; const GLenum format = Utils::getFormat(internal_format); const GLenum type = Utils::getType(internal_format); const testCase test_case = { GL_TEXTURE_2D, internal_format, format, type }; m_test_cases.push_back(test_case); } } /** Cleans resources * **/ void SmokeTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_rb_name) { gl.deleteRenderbuffers(1, &m_rb_name); m_rb_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /** Free memory allocated for images * * @param pixels Pointers to image data **/ void SmokeTest::cleanPixels(GLubyte*& pixels) const { if (0 == pixels) { return; } delete[] pixels; pixels = 0; } /** Compare two images * @param test_case Test case descriptor * @param left_data Data of left image * @param right_data Data of right image * * @return true if images are considered idenctial, false otherwise **/ bool SmokeTest::compareImages(const testCase& test_case, const GLubyte* left_data, const GLubyte* right_data) const { /* Constants */ /* Sizes */ const GLuint pixel_size = Utils::getPixelSizeForFormat(test_case.m_internal_format); const GLuint line_size = pixel_size * m_width; GLuint height = m_height; if ((GL_TEXTURE_1D == test_case.m_target) || (GL_TEXTURE_1D_ARRAY == test_case.m_target)) { height = 1; } /* For each line */ for (GLuint y = 0; y < height; ++y) { /* Offsets */ const GLuint line_offset = y * line_size; /* Pointers */ const GLubyte* left_line_data = left_data + line_offset; const GLubyte* right_line_data = right_data + line_offset; /* For each pixel of region */ for (GLuint x = 0; x < m_width; ++x) { /* Offsets */ const GLuint pixel_offset = x * pixel_size; /* Pointers */ const GLubyte* left_pixel_data = left_line_data + pixel_offset; const GLubyte* right_pixel_data = right_line_data + pixel_offset; /* Compare */ if (false == Utils::comparePixels(pixel_size, left_pixel_data, pixel_size, right_pixel_data, test_case.m_internal_format)) { if (false == Utils::unpackAndComaprePixels( test_case.m_format, test_case.m_type, test_case.m_internal_format, left_pixel_data, test_case.m_format, test_case.m_type, test_case.m_internal_format, right_pixel_data)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Not matching pixels found. " << "[" << x << ", " << y << "], off: " << left_pixel_data - left_data << ". Data left: " << Utils::getPixelString(test_case.m_internal_format, left_pixel_data) << ", right: " << Utils::getPixelString(test_case.m_internal_format, right_pixel_data) << tcu::TestLog::EndMessage; return false; } } } } return true; } /** Execute copyImageSubData for given test case and verify results * * @param test_case Test case * @param src_pixels Data of source image * * @return true if there is no error and results match expectations, false otherwise **/ bool SmokeTest::copyAndVerify(const testCase& test_case, const GLubyte* src_pixels) { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); bool result = false; /* Copy and verification */ { if (0 == m_rb_name) { GLuint height = m_height; if ((GL_TEXTURE_1D == test_case.m_target) || (GL_TEXTURE_1D_ARRAY == test_case.m_target)) { height = 1; } gl.copyImageSubData(m_src_tex_name, test_case.m_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, m_width, height, m_depth); } else /* Copy from src to rb and from rb to dst */ { /* Src and rb shares differs only on target */ gl.copyImageSubData(m_src_tex_name, GL_TEXTURE_2D, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_rb_name, test_case.m_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, m_width, m_height, m_depth); gl.copyImageSubData(m_rb_name, test_case.m_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, m_dst_tex_name, GL_TEXTURE_2D, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, m_width, m_height, m_depth); } /* Verify generated error */ error = gl.getError(); if (GL_NO_ERROR == error) { /* Verify copy results */ result = verify(test_case, src_pixels); } if ((GL_NO_ERROR != error) || (false == result)) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Target: " << glu::getTextureTargetStr(test_case.m_target) << ". Format: " << glu::getInternalFormatParameterStr(test_case.m_internal_format) << tcu::TestLog::EndMessage; if (GL_NO_ERROR != error) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failed due to error: " << glu::getErrorStr(error) << tcu::TestLog::EndMessage; TCU_FAIL("Copy operation failed"); } return false; } } return true; } /** Get pixel data for image * * @param name Name of image * @param test_case Test case descriptor * @param out_pixels Pixels **/ void SmokeTest::getPixels(GLuint name, const SmokeTest::testCase& test_case, GLubyte* out_pixels) const { const Functions& gl = m_context.getRenderContext().getFunctions(); GLenum tgt_bind = test_case.m_target; GLenum tgt_get = test_case.m_target; if (GL_RENDERBUFFER == test_case.m_target) { tgt_bind = GL_TEXTURE_2D; tgt_get = GL_TEXTURE_2D; } else if (GL_TEXTURE_CUBE_MAP == test_case.m_target) { tgt_get = GL_TEXTURE_CUBE_MAP_POSITIVE_X; } gl.bindTexture(tgt_bind, name); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); gl.getTexImage(tgt_get, 0 /* level */, test_case.m_format, test_case.m_type, out_pixels); GLU_EXPECT_NO_ERROR(gl.getError(), "GetTexImage"); gl.bindTexture(tgt_bind, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "BindTexture"); } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult SmokeTest::iterate() { GLubyte* dst_pixels = 0; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLubyte* src_pixels = 0; const testCase& test_case = m_test_cases[m_test_case_index]; gl.pixelStorei(GL_PACK_ALIGNMENT, 1); gl.pixelStorei(GL_UNPACK_ALIGNMENT, 1); GLU_EXPECT_NO_ERROR(gl.getError(), "PixelStorei"); try { /* Prepare pixels */ prepareDstPxls(test_case, dst_pixels); prepareSrcPxls(test_case, src_pixels); /* Prepare textures */ if (GL_RENDERBUFFER == test_case.m_target) { testCase desc = test_case; GLuint ignored = 0; desc.m_target = GL_TEXTURE_2D; m_rb_name = prepareTexture(test_case, 0 /* pixels */, ignored /* buffer name */); m_dst_tex_name = prepareTexture(desc, dst_pixels, m_dst_buf_name); m_src_tex_name = prepareTexture(desc, src_pixels, m_src_buf_name); } else { m_dst_tex_name = prepareTexture(test_case, dst_pixels, m_dst_buf_name); m_src_tex_name = prepareTexture(test_case, src_pixels, m_src_buf_name); } /* Copy images and verify results */ result = copyAndVerify(test_case, src_pixels); } catch (tcu::Exception& exc) { clean(); cleanPixels(dst_pixels); cleanPixels(src_pixels); throw exc; } /* Free resources */ clean(); cleanPixels(dst_pixels); cleanPixels(src_pixels); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. " << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Prepare data for destination image * * @param test_case Test case descriptor * @param out_pixels Pointer to image data **/ void SmokeTest::prepareDstPxls(const SmokeTest::testCase& test_case, GLubyte*& out_pixels) const { static const GLuint n_pixels_per_layer = m_width * m_height; const GLenum internal_format = test_case.m_internal_format; const GLuint n_layers = (GL_TEXTURE_CUBE_MAP_ARRAY != test_case.m_target) ? m_depth : 6; const GLuint n_pixels = n_pixels_per_layer * n_layers; const GLuint pixel_size = Utils::getPixelSizeForFormat(internal_format); const GLuint req_memory = pixel_size * n_pixels; const GLenum type = test_case.m_type; /* Prepare storage */ out_pixels = new GLubyte[req_memory]; if (0 == out_pixels) { TCU_FAIL("Memory allocation failed"); } memset(out_pixels, 0, req_memory); /* Fill pixels */ for (GLuint j = 0; j < n_pixels; ++j) { GLubyte* pixel_data = out_pixels + j * pixel_size; Utils::packPixel(internal_format, type, 1.0, 1.0, 1.0, 1.0, pixel_data); } } /** Prepare data for source image * * @param test_case Test case descriptor * @param out_pixels Pointer to image data **/ void SmokeTest::prepareSrcPxls(const SmokeTest::testCase& test_case, GLubyte*& out_pixels) const { static const GLuint n_pixels_per_layer = m_width * m_height; const GLenum internal_format = test_case.m_internal_format; const GLuint n_layers = (GL_TEXTURE_CUBE_MAP_ARRAY != test_case.m_target) ? m_depth : 6; const GLuint n_pixels = n_pixels_per_layer * n_layers; const GLuint pixel_size = Utils::getPixelSizeForFormat(internal_format); const GLuint layer_size = pixel_size * n_pixels_per_layer; const GLuint line_size = pixel_size * m_width; const GLuint req_memory = pixel_size * n_pixels; const GLenum type = test_case.m_type; /* Prepare storage */ out_pixels = new GLubyte[req_memory]; if (0 == out_pixels) { TCU_FAIL("Memory allocation failed"); } memset(out_pixels, 0, req_memory); /* Fill pixels */ for (GLuint layer = 0; layer < n_layers; ++layer) { const GLuint layer_offset = layer * layer_size; GLubyte* layer_data = out_pixels + layer_offset; for (GLuint y = 0; y < m_height; ++y) { const GLuint line_offset = line_size * y; GLubyte* line_data = layer_data + line_offset; for (GLuint x = 0; x < m_width; ++x) { const GLuint pixel_offset = x * pixel_size; GLubyte* pixel_data = line_data + pixel_offset; /* 255 is max ubyte. 1/15.9375 = 16/255 */ const GLdouble red = ((GLdouble)x) / 255.0 + (((GLdouble)y) / 15.9375); const GLdouble green = ((GLdouble)layer) / 255.0 + (1.0 / 15.9375); const GLdouble blue = 0.125; const GLdouble alpha = 1.0; /* This value has special meaning for some internal_formats */ Utils::packPixel(internal_format, type, red, green, blue, alpha, pixel_data); } } } } /** Prepare texture * * @param desc Descriptor * @param pixels Image data * @param out_buf_id Id of buffer used by texture buffer * * @return Name of iamge **/ GLuint SmokeTest::prepareTexture(const testCase& test_case, const GLubyte* pixels, GLuint& out_buf_id) { const GLuint n_layers = (GL_TEXTURE_CUBE_MAP_ARRAY != test_case.m_target) ? m_depth : 6; GLuint name = Utils::generateTexture(m_context, test_case.m_target); Utils::prepareTexture(m_context, name, test_case.m_target, test_case.m_internal_format, test_case.m_format, test_case.m_type, 0 /* level */, m_width, m_height, n_layers, pixels, out_buf_id); Utils::makeTextureComplete(m_context, test_case.m_target, name, 0 /* base */, 0 /* max */); return name; } /** Verify copy operation * * @param test_case Test case * @param src_pixels Original data of source image * * @return true if everything is as expected, false otherwise **/ bool SmokeTest::verify(const testCase& test_case, const GLubyte* src_pixels) { std::vector<GLubyte> dst_data; const GLuint n_layers = (GL_TEXTURE_CUBE_MAP_ARRAY != test_case.m_target) ? m_depth : 6; const GLuint pixel_size = Utils::getPixelSizeForFormat(test_case.m_internal_format); const GLuint line_size = pixel_size * m_width; const GLuint req_memory = line_size * m_height * n_layers; std::vector<GLubyte> src_data; /* Prepare storage */ dst_data.resize(req_memory); src_data.resize(req_memory); /* Check if source image was not modified */ { getPixels(m_src_tex_name, test_case, &src_data[0]); if (false == compareImages(test_case, src_pixels, &src_data[0])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData modified contents of source image. Original data: left." << tcu::TestLog::EndMessage; return false; } } /* Check contents of destination image */ { getPixels(m_dst_tex_name, test_case, &dst_data[0]); if (false == compareImages(test_case, src_pixels, &dst_data[0])) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "CopyImageSubData stored invalid contents in destination image. Source data: left." << tcu::TestLog::EndMessage; return false; } } return true; } /* InvalidTargetTest */ /** Constructor * * @param context Text context **/ InvalidTargetTest::InvalidTargetTest(deqp::Context& context) : TestCase(context, "invalid_target", "Test verifies if INVALID_ENUM is generated when invalid target is provided to CopySubImageData") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* Valid source, valid dst */ for (GLuint src = 0; src < s_n_valid_targets; ++src) { for (GLuint dst = 0; dst < s_n_valid_targets; ++dst) { const GLenum src_target = s_valid_targets[src]; const GLenum dst_target = s_valid_targets[dst]; testCase test_case = { src_target, dst_target, GL_NO_ERROR }; if (Utils::isTargetMultisampled(dst_target) != Utils::isTargetMultisampled(src_target)) { test_case.m_expected_result = GL_INVALID_OPERATION; } m_test_cases.push_back(test_case); } } /* Invalid source, invalid dst */ for (GLuint src = 0; src < s_n_invalid_targets; ++src) { for (GLuint dst = 0; dst < s_n_invalid_targets; ++dst) { const GLenum src_target = s_invalid_targets[src]; const GLenum dst_target = s_invalid_targets[dst]; const testCase test_case = { src_target, dst_target, GL_INVALID_ENUM }; m_test_cases.push_back(test_case); } } /* Invalid source, valid dst */ for (GLuint src = 0; src < s_n_invalid_targets; ++src) { for (GLuint dst = 0; dst < s_n_valid_targets; ++dst) { const GLenum src_target = s_invalid_targets[src]; const GLenum dst_target = s_valid_targets[dst]; const testCase test_case = { src_target, dst_target, GL_INVALID_ENUM }; m_test_cases.push_back(test_case); } } /* Valid source, invalid dst */ for (GLuint src = 0; src < s_n_valid_targets; ++src) { for (GLuint dst = 0; dst < s_n_invalid_targets; ++dst) { const GLenum src_target = s_valid_targets[src]; const GLenum dst_target = s_invalid_targets[dst]; const testCase test_case = { src_target, dst_target, GL_INVALID_ENUM }; m_test_cases.push_back(test_case); } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult InvalidTargetTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_dst_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_dst_buf_name); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_src_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_src_buf_name); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_dst_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_src_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_src_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_dst_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Source target: " << glu::getTextureTargetStr(test_case.m_src_target) << ", destination target: " << glu::getTextureTargetStr(test_case.m_dst_target) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void InvalidTargetTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); const testCase& test_case = m_test_cases[m_test_case_index]; /* Clean textures and buffers. Errors ignored */ Utils::deleteTexture(m_context, test_case.m_dst_target, m_dst_tex_name); Utils::deleteTexture(m_context, test_case.m_src_target, m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /* TargetMissMatchTest */ /** Constructor * * @param context Text context **/ TargetMissMatchTest::TargetMissMatchTest(deqp::Context& context) : TestCase( context, "target_miss_match", "Test verifies if INVALID_ENUM is generated when target provided to CopySubImageData does not match texture") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* Wrong dst target */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { for (GLuint dst = 0; dst < s_n_valid_targets; ++dst) { const GLenum dst_target = s_valid_targets[dst]; const GLenum src_target = s_valid_targets[target]; const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, src_target, dst_target, GL_INVALID_ENUM }; /* Skip renderbuffers */ if ((GL_RENDERBUFFER == tex_target) || (GL_RENDERBUFFER == dst_target) || (GL_RENDERBUFFER == src_target)) { continue; } /* Valid case */ if (dst_target == tex_target) { test_case.m_expected_result = GL_NO_ERROR; } /* Skip cases with multisampling conflict */ if (Utils::isTargetMultisampled(dst_target) != Utils::isTargetMultisampled(src_target)) { continue; } m_test_cases.push_back(test_case); } } /* Wrong src target */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { for (GLuint src = 0; src < s_n_valid_targets; ++src) { const GLenum dst_target = s_valid_targets[target]; const GLenum src_target = s_valid_targets[src]; const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, src_target, dst_target, GL_INVALID_ENUM }; /* Skip renderbuffers */ if ((GL_RENDERBUFFER == tex_target) || (GL_RENDERBUFFER == dst_target) || (GL_RENDERBUFFER == src_target)) { continue; } /* Valid case */ if (src_target == tex_target) { test_case.m_expected_result = GL_NO_ERROR; } /* Skip cases with multisampling conflict */ if (Utils::isTargetMultisampled(dst_target) != Utils::isTargetMultisampled(src_target)) { continue; } m_test_cases.push_back(test_case); } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult TargetMissMatchTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_dst_buf_name); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_src_buf_name); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_src_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_dst_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ". Source target: " << glu::getTextureTargetStr(test_case.m_src_target) << ", destination target: " << glu::getTextureTargetStr(test_case.m_dst_target) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void TargetMissMatchTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /* TargetMissMatchTest */ /** Constructor * * @param context Text context **/ IncompleteTexTest::IncompleteTexTest(deqp::Context& context) : TestCase( context, "incomplete_tex", "Test verifies if INVALID_OPERATION is generated when texture provided to CopySubImageData is incomplete") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, false, false, GL_INVALID_OPERATION }; /* Skip targets that are not multi level */ if (false == Utils::isTargetMultilevel(tex_target)) { continue; } m_test_cases.push_back(test_case); test_case.m_is_dst_complete = true; test_case.m_is_src_complete = false; m_test_cases.push_back(test_case); test_case.m_is_dst_complete = false; test_case.m_is_src_complete = true; m_test_cases.push_back(test_case); test_case.m_is_dst_complete = true; test_case.m_is_src_complete = true; test_case.m_expected_result = GL_NO_ERROR; m_test_cases.push_back(test_case); } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult IncompleteTexTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_dst_buf_name); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, m_src_buf_name); /* Make textures complete */ if (true == test_case.m_is_dst_complete) { Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); } if (true == test_case.m_is_src_complete) { Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_tex_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ". Is source complete: " << test_case.m_is_src_complete << ", is destination complete: " << test_case.m_is_dst_complete << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void IncompleteTexTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /* IncompatibleFormatsTest */ /** Constructor * * @param context Text context **/ IncompatibleFormatsTest::IncompatibleFormatsTest(deqp::Context& context) : TestCase( context, "incompatible_formats", "Test verifies if INVALID_OPERATION is generated when textures provided to CopySubImageData are incompatible") , m_dst_buf_name(0) , m_dst_tex_name(0) , m_src_buf_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* RGBA8UI vs RGBA16UI */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_INVALID_OPERATION }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } /* RGBA8UI vs RGBA32UI */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_INVALID_OPERATION }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } /* RGBA16UI vs RG16UI */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT, GL_INVALID_OPERATION }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } /* RGBA32UI vs RGBA32F */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_RGBA32F, GL_RGBA, GL_FLOAT, GL_NO_ERROR }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } /* RGBA8 vs RGBA32F */ for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA32F, GL_RGBA, GL_FLOAT, GL_INVALID_OPERATION }; /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } m_test_cases.push_back(test_case); } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult IncompatibleFormatsTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, test_case.m_dst_internal_format, test_case.m_dst_format, test_case.m_dst_type, m_dst_buf_name); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, test_case.m_src_internal_format, test_case.m_src_format, test_case.m_src_type, m_src_buf_name); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_tex_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ". Source format: " << glu::getInternalFormatParameterStr(test_case.m_src_internal_format) << ". Destination format: " << glu::getInternalFormatParameterStr(test_case.m_dst_internal_format) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void IncompatibleFormatsTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); const testCase& test_case = m_test_cases[m_test_case_index]; /* Clean textures and buffers. Errors ignored */ Utils::deleteTexture(m_context, test_case.m_tex_target, m_dst_tex_name); Utils::deleteTexture(m_context, test_case.m_tex_target, m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; if (0 != m_dst_buf_name) { gl.deleteBuffers(1, &m_dst_buf_name); m_dst_buf_name = 0; } if (0 != m_src_buf_name) { gl.deleteBuffers(1, &m_src_buf_name); m_src_buf_name = 0; } } /* InvalidTargetTest */ /** Constructor * * @param context Text context **/ SamplesMissMatchTest::SamplesMissMatchTest(deqp::Context& context) : TestCase(context, "samples_missmatch", "Test verifies if INVALID_OPERATION is generated when textures provided " "to CopySubImageData have different number of samples") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { testCase test_case; static const GLsizei n_samples[2] = { 1, 4 }; static const GLenum targets[2] = { GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_2D_MULTISAMPLE_ARRAY }; for (GLuint src_sample = 0; src_sample < 2; ++src_sample) { for (GLuint dst_sample = 0; dst_sample < 2; ++dst_sample) { for (GLuint src_target = 0; src_target < 2; ++src_target) { for (GLuint dst_target = 0; dst_target < 2; ++dst_target) { test_case.m_src_target = targets[src_target]; test_case.m_src_n_samples = n_samples[src_sample]; test_case.m_dst_target = targets[dst_target]; test_case.m_dst_n_samples = n_samples[dst_sample]; if (test_case.m_src_n_samples == test_case.m_dst_n_samples) { test_case.m_expected_result = GL_NO_ERROR; } else { test_case.m_expected_result = GL_INVALID_OPERATION; } m_test_cases.push_back(test_case); } } } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult SamplesMissMatchTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareMultisampleTex(m_context, test_case.m_dst_target, test_case.m_dst_n_samples); m_src_tex_name = Utils::prepareMultisampleTex(m_context, test_case.m_src_target, test_case.m_src_n_samples); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_src_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_dst_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Source target: " << glu::getTextureTargetStr(test_case.m_src_target) << " samples: " << test_case.m_src_n_samples << ", destination target: " << glu::getTextureTargetStr(test_case.m_dst_target) << " samples: " << test_case.m_dst_n_samples << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void SamplesMissMatchTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures . Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } /* IncompatibleFormatsCompressionTest */ /** Constructor * * @param context Text context **/ IncompatibleFormatsCompressionTest::IncompatibleFormatsCompressionTest(deqp::Context& context) : TestCase(context, "incompatible_formats_compression", "Test verifies if INVALID_OPERATION is generated when " "textures provided to CopySubImageData are incompatible, " "one of formats is compressed") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; /* Skip 1D targets, not supported */ if ((GL_TEXTURE_1D == tex_target) || (GL_TEXTURE_1D_ARRAY == tex_target) || (GL_TEXTURE_3D == tex_target) || (GL_TEXTURE_RECTANGLE == tex_target) || (GL_RENDERBUFFER == tex_target) || (GL_TEXTURE_CUBE_MAP_ARRAY == tex_target)) { continue; } /* Skip multisampled and rectangle targets */ if (true == Utils::isTargetMultisampled(tex_target)) { continue; } /* Compressed 128bit vs RGBA32UI */ { testCase test_case = { tex_target, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, GL_NO_ERROR }; m_test_cases.push_back(test_case); } /* Compressed 128bit vs RGBA16UI */ { testCase test_case = { tex_target, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, GL_INVALID_OPERATION }; m_test_cases.push_back(test_case); } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult IncompatibleFormatsCompressionTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, test_case.m_dst_internal_format, test_case.m_dst_format, test_case.m_dst_type, temp); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, test_case.m_src_internal_format, test_case.m_src_format, test_case.m_src_type, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_tex_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 4 /* srcWidth */, 4 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ". Source format: " << glu::getInternalFormatParameterStr(test_case.m_src_internal_format) << ". Destination format: " << glu::getInternalFormatParameterStr(test_case.m_dst_internal_format) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void IncompatibleFormatsCompressionTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } /* MissMatchObjectTest */ /** Constructor * * @param context Text context **/ MissMatchObjectTest::MissMatchObjectTest(deqp::Context& context) : TestCase( context, "missmatch_object", "Test verifies if INVALID_VALUE is generated when object & target provided to CopySubImageData do not match") , m_dst_name(0) , m_src_name(0) , m_test_case_index(0) { static const testCase test_cases[] = { { GL_TEXTURE_2D, GL_TEXTURE_2D, GL_TEXTURE_2D, GL_NO_ERROR }, { GL_TEXTURE_2D, GL_RENDERBUFFER, GL_TEXTURE_2D, GL_INVALID_VALUE }, { GL_TEXTURE_2D, GL_TEXTURE_2D, GL_RENDERBUFFER, GL_INVALID_VALUE }, { GL_TEXTURE_2D, GL_RENDERBUFFER, GL_RENDERBUFFER, GL_INVALID_VALUE }, { GL_RENDERBUFFER, GL_TEXTURE_2D, GL_TEXTURE_2D, GL_INVALID_VALUE }, { GL_RENDERBUFFER, GL_RENDERBUFFER, GL_TEXTURE_2D, GL_INVALID_VALUE }, { GL_RENDERBUFFER, GL_TEXTURE_2D, GL_RENDERBUFFER, GL_INVALID_VALUE }, { GL_RENDERBUFFER, GL_RENDERBUFFER, GL_RENDERBUFFER, GL_NO_ERROR } }; static const GLuint n_test_cases = sizeof(test_cases) / sizeof(testCase); for (GLuint i = 0; i < n_test_cases; ++i) { const testCase& test_case = test_cases[i]; m_test_cases.push_back(test_case); } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult MissMatchObjectTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare objects */ if (GL_RENDERBUFFER == test_case.m_obj_target) { m_dst_name = Utils::prepareRenderBuffer(m_context, GL_RGBA8); m_src_name = Utils::prepareRenderBuffer(m_context, GL_RGBA8); } else { m_dst_name = Utils::prepareTex16x16x6(m_context, test_case.m_obj_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); m_src_name = Utils::prepareTex16x16x6(m_context, test_case.m_obj_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_obj_target, m_dst_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_obj_target, m_src_name, 0 /* base */, 0 /* max */); } } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_name, test_case.m_src_target, 0 /* srcLevel */, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_name, test_case.m_dst_target, 0 /* dstLevel */, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Remove resources */ clean(); if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Object target: " << glu::getTextureTargetStr(test_case.m_obj_target) << ". Source target: " << glu::getTextureTargetStr(test_case.m_src_target) << ". Destination target: " << glu::getTextureTargetStr(test_case.m_dst_target) << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void MissMatchObjectTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); const testCase& test_case = m_test_cases[m_test_case_index]; /* Clean textures or renderbuffers. Errors ignored */ if (GL_RENDERBUFFER == test_case.m_obj_target) { gl.deleteRenderbuffers(1, &m_dst_name); gl.deleteRenderbuffers(1, &m_src_name); } else { gl.deleteTextures(1, &m_dst_name); gl.deleteTextures(1, &m_src_name); } m_dst_name = 0; m_src_name = 0; } /* NonExistentMipMapTest */ /** Constructor * * @param context Text context **/ NonExistentMipMapTest::NonExistentMipMapTest(deqp::Context& context) : TestCase(context, "non_existent_mipmap", "Test verifies if INVALID_VALUE is generated when CopySubImageData is " "executed for mipmap that does not exist") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; testCase test_case = { tex_target, 0, 0, GL_NO_ERROR }; if (GL_RENDERBUFFER == tex_target) { continue; } m_test_cases.push_back(test_case); /* Rest of cases is invalid */ test_case.m_expected_result = GL_INVALID_VALUE; test_case.m_dst_level = 1; test_case.m_src_level = 0; m_test_cases.push_back(test_case); test_case.m_dst_level = 0; test_case.m_src_level = 1; m_test_cases.push_back(test_case); test_case.m_dst_level = 1; test_case.m_src_level = 1; m_test_cases.push_back(test_case); } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult NonExistentMipMapTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, test_case.m_src_level, 0 /* srcX */, 0 /* srcY */, 0 /* srcZ */, m_dst_tex_name, test_case.m_tex_target, test_case.m_dst_level, 0 /* dstX */, 0 /* dstY */, 0 /* dstZ */, 1 /* srcWidth */, 1 /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ", source level: " << test_case.m_src_level << ", destination level: " << test_case.m_dst_level << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void NonExistentMipMapTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } /* ExceedingBoundariesTest */ const glw::GLuint ExceedingBoundariesTest::m_region_depth = 4; const glw::GLuint ExceedingBoundariesTest::m_region_height = 4; const glw::GLuint ExceedingBoundariesTest::m_region_width = 4; /** Constructor * * @param context Text context **/ ExceedingBoundariesTest::ExceedingBoundariesTest(deqp::Context& context) : TestCase(context, "exceeding_boundaries", "Test verifies if INVALID_VALUE is generated when CopySubImageData is " "executed for regions exceeding image boundaries") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* 16x16x6 are values used by prepareTex16x16x6 */ static const GLuint invalid_x = 16 - (m_region_width / 2); static const GLuint invalid_y = 16 - (m_region_height / 2); static const GLuint invalid_z = 6 - (m_region_depth / 2); static const GLuint x_vals[] = { 0, invalid_x }; static const GLuint y_vals[] = { 0, invalid_y }; static const GLuint z_vals[] = { 0, invalid_z }; static const GLuint n_x_vals = sizeof(x_vals) / sizeof(x_vals[0]); static const GLuint n_y_vals = sizeof(y_vals) / sizeof(y_vals[0]); static const GLuint n_z_vals = sizeof(z_vals) / sizeof(z_vals[0]); for (GLuint target = 0; target < s_n_valid_targets; ++target) { const GLenum tex_target = s_valid_targets[target]; GLuint height = m_region_height; if (GL_TEXTURE_BUFFER == tex_target) { continue; } if ((GL_TEXTURE_1D == tex_target) || (GL_TEXTURE_1D_ARRAY == tex_target)) { height = 1; } for (GLuint x = 0; x < n_x_vals; ++x) { for (GLuint y = 0; y < n_y_vals; ++y) { for (GLuint z = 0; z < n_z_vals; ++z) { const GLuint x_val = x_vals[x]; const GLuint y_val = y_vals[y]; const GLuint z_val = z_vals[z]; const GLenum res = ((0 == x_val) && (0 == y_val) && (0 == z_val)) ? GL_NO_ERROR : GL_INVALID_VALUE; GLuint depth = 1; if (0 != z_val) { if ((GL_TEXTURE_2D_ARRAY != tex_target) || (GL_TEXTURE_2D_MULTISAMPLE_ARRAY != tex_target) || (GL_TEXTURE_3D != tex_target) || (GL_TEXTURE_CUBE_MAP_ARRAY != tex_target)) { /* Skip z != 0 for 2d textures */ continue; } else { /* Set depth so as to exceed boundary */ depth = m_region_depth; } } testCase src_test_case = { tex_target, depth, height, x_val, y_val, z_val, 0, 0, 0, res }; testCase dst_test_case = { tex_target, depth, height, 0, 0, 0, x_val, y_val, z_val, res }; m_test_cases.push_back(src_test_case); m_test_cases.push_back(dst_test_case); } } } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult ExceedingBoundariesTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); m_src_tex_name = Utils::prepareTex16x16x6(m_context, test_case.m_tex_target, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, test_case.m_tex_target, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, test_case.m_tex_target, 0 /* level */, test_case.m_src_x /* srcX */, test_case.m_src_y /* srcY */, test_case.m_src_z /* srcZ */, m_dst_tex_name, test_case.m_tex_target, 0 /* level */, test_case.m_dst_x /* dstX */, test_case.m_dst_y /* dstY */, test_case.m_dst_z /* dstZ */, m_region_width /* srcWidth */, test_case.m_height /* srcHeight */, test_case.m_depth /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". Texture target: " << glu::getTextureTargetStr(test_case.m_tex_target) << ", source: [" << test_case.m_src_x << ", " << test_case.m_src_y << ", " << test_case.m_src_z << "], destination: [" << test_case.m_src_x << ", " << test_case.m_src_y << ", " << test_case.m_src_z << "], depth: " << test_case.m_depth << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void ExceedingBoundariesTest::clean() { const testCase& test_case = m_test_cases[m_test_case_index]; /* Clean textures and buffers. Errors ignored */ Utils::deleteTexture(m_context, test_case.m_tex_target, m_dst_tex_name); Utils::deleteTexture(m_context, test_case.m_tex_target, m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } /* InvalidAlignmentTest */ /** Constructor * * @param context Text context **/ InvalidAlignmentTest::InvalidAlignmentTest(deqp::Context& context) : TestCase(context, "invalid_alignment", "Test verifies if INVALID_VALUE is generated when CopySubImageData is " "executed for regions with invalid alignment") , m_dst_tex_name(0) , m_src_tex_name(0) , m_test_case_index(0) { /* 16x16x6 are values used by prepareTex16x16x6 */ static const GLuint invalid_h = 2; static const GLuint invalid_w = 2; static const GLuint invalid_x = 2; static const GLuint invalid_y = 2; static const GLuint valid_h = 4; static const GLuint valid_w = 4; static const GLuint h_vals[] = { valid_h, invalid_h }; static const GLuint w_vals[] = { valid_w, invalid_w }; static const GLuint x_vals[] = { 0, invalid_x }; static const GLuint y_vals[] = { 0, invalid_y }; static const GLuint n_h_vals = sizeof(h_vals) / sizeof(h_vals[0]); static const GLuint n_w_vals = sizeof(w_vals) / sizeof(w_vals[0]); static const GLuint n_x_vals = sizeof(x_vals) / sizeof(x_vals[0]); static const GLuint n_y_vals = sizeof(y_vals) / sizeof(y_vals[0]); for (GLuint x = 0; x < n_x_vals; ++x) { for (GLuint y = 0; y < n_y_vals; ++y) { for (GLuint h = 0; h < n_h_vals; ++h) { for (GLuint w = 0; w < n_w_vals; ++w) { const GLuint h_val = h_vals[h]; const GLuint w_val = w_vals[w]; const GLuint x_val = x_vals[x]; const GLuint y_val = y_vals[y]; const GLenum res = ((valid_h == h_val) && (valid_w == w_val) && (0 == x_val) && (0 == y_val)) ? GL_NO_ERROR : GL_INVALID_VALUE; testCase dst_test_case = { h_val, w_val, 0, 0, x_val, y_val, res }; testCase src_test_case = { h_val, w_val, x_val, y_val, 0, 0, res }; m_test_cases.push_back(dst_test_case); m_test_cases.push_back(src_test_case); } } } } } /** Execute test * * @return CONTINUE as long there are more test case, STOP otherwise **/ tcu::TestNode::IterateResult InvalidAlignmentTest::iterate() { GLenum error = GL_NO_ERROR; const Functions& gl = m_context.getRenderContext().getFunctions(); tcu::TestNode::IterateResult it_result = tcu::TestNode::STOP; bool result = false; GLuint temp = 0; const testCase& test_case = m_test_cases[m_test_case_index]; try { /* Prepare textures */ m_dst_tex_name = Utils::prepareTex16x16x6(m_context, GL_TEXTURE_2D, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, temp); m_src_tex_name = Utils::prepareTex16x16x6(m_context, GL_TEXTURE_2D, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, temp); /* Make textures complete */ Utils::makeTextureComplete(m_context, GL_TEXTURE_2D, m_dst_tex_name, 0 /* base */, 0 /* max */); Utils::makeTextureComplete(m_context, GL_TEXTURE_2D, m_src_tex_name, 0 /* base */, 0 /* max */); } catch (tcu::Exception& exc) { clean(); throw exc; } /* Execute CopyImageSubData */ gl.copyImageSubData(m_src_tex_name, GL_TEXTURE_2D, 0 /* level */, test_case.m_src_x /* srcX */, test_case.m_src_y /* srcY */, 0 /* srcZ */, m_dst_tex_name, GL_TEXTURE_2D, 0 /* level */, test_case.m_dst_x /* dstX */, test_case.m_dst_y /* dstY */, 0 /* dstZ */, test_case.m_width /* srcWidth */, test_case.m_height /* srcHeight */, 1 /* srcDepth */); /* Verify generated error */ error = gl.getError(); result = (test_case.m_expected_result == error); /* Free resources */ clean(); /* Set result */ if (true == result) { m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass"); /* Increase index */ m_test_case_index += 1; /* Are there any test cases left */ if (m_test_cases.size() > m_test_case_index) { it_result = tcu::TestNode::CONTINUE; } } else { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Failure. Expected result: " << glu::getErrorStr(test_case.m_expected_result) << " got: " << glu::getErrorStr(error) << ". source: [" << test_case.m_src_x << ", " << test_case.m_src_y << "], destination: [" << test_case.m_src_x << ", " << test_case.m_src_y << "], size: " << test_case.m_width << " x " << test_case.m_height << tcu::TestLog::EndMessage; m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } /* Done */ return it_result; } /** Cleans resources * **/ void InvalidAlignmentTest::clean() { const Functions& gl = m_context.getRenderContext().getFunctions(); /* Clean textures and buffers. Errors ignored */ gl.deleteTextures(1, &m_dst_tex_name); gl.deleteTextures(1, &m_src_tex_name); m_dst_tex_name = 0; m_src_tex_name = 0; } } /* namespace CopyImage */ CopyImageTests::CopyImageTests(deqp::Context& context) : TestCaseGroup(context, "copy_image", "") { } CopyImageTests::~CopyImageTests(void) { } void CopyImageTests::init() { addChild(new CopyImage::FunctionalTest(m_context)); addChild(new CopyImage::IncompleteTexTest(m_context)); addChild(new CopyImage::MissMatchObjectTest(m_context)); addChild(new CopyImage::SmokeTest(m_context)); addChild(new CopyImage::InvalidTargetTest(m_context)); addChild(new CopyImage::TargetMissMatchTest(m_context)); addChild(new CopyImage::IncompatibleFormatsTest(m_context)); addChild(new CopyImage::SamplesMissMatchTest(m_context)); addChild(new CopyImage::IncompatibleFormatsCompressionTest(m_context)); addChild(new CopyImage::NonExistentMipMapTest(m_context)); addChild(new CopyImage::ExceedingBoundariesTest(m_context)); addChild(new CopyImage::InvalidAlignmentTest(m_context)); } } /* namespace gl4cts */
/* * opencog/xml/NMXmlParser.cc * * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * Written by Thiago Maia <thiago@vettatech.com> * Andre Senna <senna@vettalabs.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <stack> #include <string> #include <math.h> #include <expat.h> #include <opencog/util/platform.h> #include <opencog/atomspace/Link.h> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/util/Logger.h> #include <opencog/xml/FileXMLBufferReader.h> #include <opencog/xml/NMXmlDefinitions.h> #include <opencog/xml/NMXmlParser.h> /* * XXX To be fixed: remove all of the uses of "throw" in this code, * to be replaced by a gentler error mechanism. The problem is two-fold: * the "throws" are made from within routines that are called by the * external libxmlparser library, which is written in C, not C++. * Thus, these errors can't ever actually be caught, since they never * get through the parser. As a result, any minor mistake in an XML * will cause the entire server to crash, which is just plain ugly. * Yuck! * NOTE: Any time information (including Timestamps) are represented using Atoms as follows: * AtTimeLink(TimeNode:<temporalStringValue>, Atom1 [, Atom2 [... , AtomN]]) */ using namespace opencog; std::tr1::unordered_map<const std::string, Handle, hash<std::string>, std::equal_to<std::string> > NMXmlParser::hypHandles; bool NMXmlParser::fresh = true; bool NMXmlParser::freshLinks = false; // If unspecified, the default truth value is "true", with confidence of 0.5 const TruthValue& NMXmlParser::DEFAULT_TV() { static SimpleTruthValue* instance = NULL; if (instance == NULL) { instance = new SimpleTruthValue(1.0f, 1.0f); instance->setConfidence(0.5); } return *instance; } // const int TYPE_LENGTH = (int) log10((double)NUMBER_OF_CLASSES) + 1; typedef struct { unsigned enabled: 1; unsigned ignoring: 1; unsigned processNodes: 1; unsigned processRelationships: 1; } Status; typedef std::stack<void*> ParserStack; // TODO: CREATE AN ABSTRACT CLASS "Stackable" for check for subclasses // when poping elements from stack. typedef struct { AtomSpace* atomSpace; //AtomTable* atomTable; ParserStack stack; Handle lastInsertedHandle; Status status; XML_Parser parser; } UserData; static void push(ParserStack& ps, void* p) { ps.push(p); } static void* top(ParserStack& ps) { if (!ps.size()) return NULL; return ps.top(); } static void* pop(ParserStack& ps) { if (!ps.size()) return NULL; void* ret = ps.top(); ps.pop(); return ret; } /** * Return the type corresponding to the type name */ static Type getTypeFromString(const char *name, bool onlyClassName) { if (!name) return NOTYPE; Type result = classserver().getType(name); if (result != NOTYPE) { return result; } if (strcmp(name, POLYGON_CORNER_TOKEN) != 0 && (onlyClassName || strcmp(name, ELEMENT_TOKEN) != 0)) { logger().error("Warning: null type for name returned! (%s)\n", name); } return 0; } #ifdef NOT_USED_RIGHT_NOW static char *nativeBuildLinkKey(Atom *link) { char key[1<<16]; char aux[1 << 16]; key[0] = '\0'; sprintf(aux, "%d ", link->getType()); strcat(key, aux); for (int i = 0; i < link->getArity(); i++) { sprintf(aux, "%p ", TLB::getHandle(link->getOutgoingAtom(i))); strcat(key, aux); } return strdup(key); } #endif /* NOT_USED_RIGHT_NOW */ //#include <sys/time.h> //unsigned long int cumulativeParseNodesStart = 0; //unsigned long int cumulativeParseLinksStart = 0; //unsigned long int cumulativeParseEnd = 0; //unsigned long int cumulativeParseEnd1 = 0; //unsigned long int cumulativeParseEnd2 = 0; /** * Handle attributes that are common to both Nodes and Links. * In other words, handle "confidence" and "strength" attributes. */ static const char ** scan_common_attrs (Atom *r, const char **atts) { float buffer; if (strcmp(*atts, CONFIDENCE_TOKEN) == 0) { atts++; sscanf(*atts, "%f", &buffer); SimpleTruthValue newTv((const SimpleTruthValue&)r->getTruthValue()); newTv.setConfidence(buffer); r->setTruthValue(newTv); } else if (strcmp(*atts, STRENGTH_TOKEN) == 0) { atts++; sscanf(*atts, "%f", &buffer); SimpleTruthValue newTv((const SimpleTruthValue&)r->getTruthValue()); newTv.setMean(buffer); r->setTruthValue(newTv); } return atts; } static void nativeStartElement(void *userData, const char *name, const char **atts) throw (RuntimeException, InconsistenceException) { Atom* r = NULL; Type typeFound; UserData* ud = (UserData*) userData; // processes head tags (list, tagdescription, etc) if (strcmp(name, LIST_TOKEN) == 0) { ud->status.enabled = 1; return; } else if (strcmp(name, TAG_DESCRIPTION_TOKEN) == 0) { ud->status.ignoring = 1; return; } // abandons element if necessary if ((!ud->status.enabled) || ud->status.ignoring) return; typeFound = getTypeFromString(name, false); if (NOTYPE == typeFound) return; // processes nodes if (ud->status.processNodes) { // timeval s; // gettimeofday(&s, NULL); if (classserver().isA(typeFound, NODE)) { //cprintf(5,"Processing Node: %d (%s)\n", typeFound, name); r = (Atom*) new Node(typeFound, "", NMXmlParser::DEFAULT_TV()); logger().fine("Pushing r = %p", r); push(ud->stack, r); const TruthValue& t = r->getTruthValue(); if (typeid(t) != typeid(SimpleTruthValue)) { throw InconsistenceException(TRACE_INFO, "DefaultTruthValue is not SimpleTruthValue."); } while (*atts != NULL) { if (strcmp(*atts, NAME_TOKEN) == 0) { atts++; NMXmlParser::setNodeName((Node*) r, *atts); } else { const char **natts = scan_common_attrs(r, atts); if (atts == natts) { logger().error("unrecognized Node token: %s\n", *atts); } atts = natts; } atts++; } } // timeval e; // gettimeofday(&e, NULL); // unsigned long spentTime = (e.tv_sec - s.tv_sec)*1000000+(e.tv_usec - s.tv_usec); // cumulativeParseNodesStart += spentTime; } // processes relationships if (ud->status.processRelationships) { // inheritance links may be declared inside lexical category node // tags. this information is ignored once it is redundant with source // and target data contained in the inheritance link declaration if (classserver().isA(typeFound, LINK)) { // timeval s; // gettimeofday(&s, NULL); printf("Processing Link: %d (%s)\n", typeFound, name); r = (Atom*) new Link(typeFound, std::vector<Handle>(), NMXmlParser::DEFAULT_TV()); const TruthValue& t = r->getTruthValue(); if (typeid(t) != typeid(SimpleTruthValue)) { throw InconsistenceException(TRACE_INFO, "DefaultTruthValue is not SimpleTruthValue"); } while (*atts != NULL) { const char **natts = scan_common_attrs(r, atts); if (atts == natts) { logger().error("unrecognized Link token: %s\n", *atts); } atts = natts; atts++; } Atom* currentAtom = (Atom*) top(ud->stack); if (currentAtom != NULL) { logger().fine("Getting link element inside currentAtom = %p", currentAtom); Link *link = dynamic_cast<Link *>(currentAtom); if (link) { if (r != NULL) { NMXmlParser::addOutgoingAtom(link, Handle::UNDEFINED); } else { throw RuntimeException(TRACE_INFO, "fatal error: NULL inner link"); } } } logger().fine("Pushing r = %p", r); push(ud->stack, r); // timeval e; // gettimeofday(&e, NULL); // unsigned long spentTime = (e.tv_sec - s.tv_sec)*1000000+(e.tv_usec - s.tv_usec); // cumulativeParseLinksStart += spentTime; } else if (strcmp(name, ELEMENT_TOKEN) == 0) { // processes elements of other relationships, and inserts them in // the link previously defined; Atom* currentAtom = (Atom*) top(ud->stack); if (currentAtom == NULL) { logger().error("error: this token (%s) is expected to be nested\n", name); return; } logger().fine("Getting node element inside currentAtom = %p", currentAtom); const char *n = NULL, *t = NULL; while (*atts != NULL) { if (strcmp(*atts, NAME_TOKEN) == 0) { atts++; n = *atts; } else if (strcmp(*atts, CLASS_TOKEN) == 0) { atts++; t = *atts; } else { logger().error("unrecognized token: %s\n", *atts); } atts++; } Handle h; //r = getRelationshipByNameAndType(n, getTypeFromString(t, true)); logger().fine("Getting existing node (%s,%s)", n, t); //h = ud->atomTable->getHandle(n, getTypeFromString(t, true)); h = ud->atomSpace->getHandle(getTypeFromString(t, true), n); logger().fine(" => h = %p", h.value()); if (TLB::isValidHandle(h)) { logger().fine(TLB::getAtom(h)->toString().c_str()); Link *link = dynamic_cast<Link *>(currentAtom); if (link) { logger().fine("adding atom %s to link %s", TLB::getAtom(h)->toShortString().c_str(), link->toShortString().c_str()); NMXmlParser::addOutgoingAtom(link, h); } } else { #ifdef THROW_EXCEPTIONS throw RuntimeException(TRACE_INFO, "fatal error: unable to find atom named %s, type %s", n, t); #else /* Don't just core dump on bad XML format. * (since exceptions can't be thrown past the C library * of the parser, a core dump is inevitable). */ fprintf (stderr, "Fatal error: unable to find atom named %s, type %s\n", n, t); logger().error( "fatal error: unable to find atom named %s, type %s\n", n, t); #endif } } } } static void nativeEndElement(void *userData, const char *name) throw (InconsistenceException) { UserData* ud = (UserData*) userData; if (strcmp(name, LIST_TOKEN) == 0) { ud->status.enabled = 0; } else if (strcmp(name, TAG_DESCRIPTION_TOKEN) == 0) { ud->status.ignoring = 0; } else { void* object = top(ud->stack); Atom* currentAtom = (Atom*) object; if (currentAtom != NULL) { //timeval s; //gettimeofday(&s, NULL); Type type = getTypeFromString(name, false); if ((classserver().isA(type, NODE) && ud->status.processNodes) || (classserver().isA(type, LINK) && ud->status.processRelationships)) { if (currentAtom->getType() == type) { if (classserver().isA(type, LINK)) { pop(ud->stack); logger().fine("(1) Pushing currentAtom = %p", currentAtom); push(ud->stack, currentAtom); } if (classserver().isA(type, UNORDERED_LINK)) { // Forces the sorting of outgoing by calling setOutgoingSet // TODO: implement a sortOutgoingSet for doing the same thing more efficiently... Link *link = dynamic_cast<Link *>(currentAtom); if (link) { std::vector<Handle> outgoing = link->getOutgoingSet(); NMXmlParser::setOutgoingSet(link, outgoing); } } Handle oldHandle = NMXmlParser::holdsHandle(currentAtom); //timeval s1; //gettimeofday(&s1, NULL); logger().fine("currentAtom => %s", currentAtom->toString().c_str()); //Handle newHandle = ud->atomTable->add(currentAtom); Handle newHandle = ud->atomSpace->addRealAtom(*currentAtom); //timeval e1; //gettimeofday(&e1, NULL); //signed long spentTime1 = (e1.tv_sec - s1.tv_sec)*1000000+(e1.tv_usec - s1.tv_usec); //unsigned long spentTime1 = (e1.tv_sec - s.tv_sec)*1000000+(e1.tv_usec - s.tv_usec); //cumulativeParseEnd1 += spentTime1; // Updates last inserted/merged atom handle ud->lastInsertedHandle = newHandle; if (CoreUtils::handleCompare(&oldHandle, &newHandle)) { // already existed delete currentAtom; logger().fine("Already existed"); currentAtom = TLB::getAtom(newHandle); pop(ud->stack); logger().fine("(2) Pushing currentAtom = %p", currentAtom); push(ud->stack, currentAtom); } // XXX FIXME: // would be better if this was replaced by // if (NULL != dynamic_cast<Link *>(currentAtom)) // and also a few lines down. if (classserver().isA(currentAtom->getType(), LINK)) { //KMI -- find out if this is a nested link pop(ud->stack); Atom* nextUd = (Atom*) top(ud->stack); logger().fine("Getting link element inside nextUd = %p", nextUd); logger().fine("(3) Pushing currentAtom = %p", currentAtom); push(ud->stack, currentAtom); Link *nextlink = dynamic_cast<Link *>(nextUd); if (nextlink != NULL) { int arity = nextlink->getArity(); std::vector<Handle> outgoingSet = nextlink->getOutgoingSet(); for (int i = 0; i < arity; i++) { if (TLB::isInvalidHandle(outgoingSet[i])) { outgoingSet[i] = newHandle; break; } } NMXmlParser::setOutgoingSet(nextlink, outgoingSet); } } } else { char buff[300]; snprintf(buff, 300, "XML parse error: relationship type mismatch at line %d.\n" "\txml type=%s(%d) current atom type=%d %s", (int) XML_GetCurrentLineNumber(ud->parser), name, type, currentAtom->getType(), currentAtom->toString().c_str()); throw InconsistenceException(TRACE_INFO, buff); } pop(ud->stack); } //timeval e; //gettimeofday(&e, NULL); //unsigned long spentTime = (e.tv_sec - s.tv_sec)*1000000+(e.tv_usec - s.tv_usec); //cumulativeParseEnd += spentTime; else { logger().fine("WARNING: Got NULL Atom* from the parser stack!"); } } } } NMXmlParser::NMXmlParser(AtomSpace* atomSpace, bool fresh, bool freshLinks) { this->atomSpace = atomSpace; this->fresh = fresh; this->freshLinks = freshLinks; } NMXmlParser::~NMXmlParser() { } void NMXmlParser::setNodeName(Node* node, const char* name) { node->setName(name); } void NMXmlParser::addOutgoingAtom(Link * link, Handle h) { link->addOutgoingAtom(h); } void NMXmlParser::setOutgoingSet(Link * link, const std::vector<Handle>& outgoing) { link->setOutgoingSet(outgoing); } HandleEntry* NMXmlParser::loadXML(const std::vector<XMLBufferReader*>& xmlReaders, AtomSpace * atomSpace, bool fresh, bool freshLinks) { logger().fine("NMXmlParser::loadXML"); cassert(TRACE_INFO, atomSpace != NULL, "loadXML - atomSpace should pointer should not be NULL."); HandleEntry* result = NULL; if (xmlReaders.size() <= 0) return result; NMXmlParser parser(atomSpace, fresh, freshLinks); // time_t start = time(NULL); // timeval s; // gettimeofday(&s, NULL); // Only nodes are processed in the first pass for (unsigned int i = 0; i < xmlReaders.size(); i++) { if (typeid(*xmlReaders[i]) == typeid(FileXMLBufferReader)) { logger().fine("First pass: processing file %s\n", ((FileXMLBufferReader*) xmlReaders[i])->getFilename()); } // please don't log -- this will spew millions of messages when // there are millions of files to be loaded, as would be the // case when the xml is auto-generated and piped over from // another process. // logger().warn("Loading XML: %d%% done.\r", (int) (100 * ((float) i / (xmlReaders.size() * 2)))); parser.parse(xmlReaders[i], PARSE_NODES); } //timeval e; //gettimeofday(&e, NULL); //unsigned long spentTime = (e.tv_sec*1000 + e.tv_usec/1000) - (s.tv_sec*1000 + s.tv_usec/1000); //printf("PARSE NODES time = %lu\n", spentTime); //s = e; // only links are processed in the second pass for (unsigned int i = 0; i < xmlReaders.size(); i++) { if (typeid(*xmlReaders[i]) == typeid(FileXMLBufferReader)) { logger().fine("Second pass: processing file %s\n", ((FileXMLBufferReader*) xmlReaders[i])->getFilename()); } // logger().warn("Loading XML: %d%% done.\r", (int) (100 * ((float) (i + xmlReaders.size()) / (xmlReaders.size() * 2)))); Handle lastInsertedLinkHandle = parser.parse(xmlReaders[i], PARSE_LINKS); Handle uh(Handle::UNDEFINED); if (CoreUtils::handleCompare(&lastInsertedLinkHandle, &uh)) { result = HandleEntry::concatenation(result, new HandleEntry(lastInsertedLinkHandle)); } } // finally, null names of unnamed nodes for (HandleEntry *e = result; e; e = e->next) { Atom *a = TLB::getAtom(e->handle); if (classserver().isNode(a->getType())) { Node *n = (Node*)a; if (n->getName()[0] == '#') n->setName(""); } } //time_t duration = time(NULL) - start; //timeval e; //gettimeofday(&e, NULL); //unsigned long spentTime = (e.tv_sec-s.tv_sec)*1000000 + (e.tv_usec-s.tv_usec); //printf("PARSE XML time = %lu\n", spentTime); //logger().warn("Loading XML contents: 100%% done (in %d second%c).\n", (int) duration, duration == 1 ? '\0' : 's'); //cprintf(NORMAL, "Number of timestamp entries: %d\n", stackTimeFlag); return result; } Handle NMXmlParser::parse_pass(XMLBufferReader* xmlReader, NMXmlParseType pass) { char buf[BUFSIZ]; int done; UserData userData; userData.lastInsertedHandle = Handle::UNDEFINED; //userData.atomTable = atomSpace->getAtomTable(); userData.atomSpace = atomSpace; userData.status.enabled = 0; userData.status.ignoring = 0; if (pass == PARSE_NODES) { userData.status.processNodes = 1; userData.status.processRelationships = 0; } else { userData.status.processNodes = 0; userData.status.processRelationships = 1; } XML_Parser parser = XML_ParserCreate(NULL); userData.parser = parser; XML_SetUserData(parser, &userData); XML_SetElementHandler(parser, nativeStartElement, nativeEndElement); xmlReader->open(); do { size_t len = xmlReader->read(buf, 1, sizeof(buf)); done = len < sizeof(buf); if (!XML_Parse(parser, buf, len, done)) { fprintf(stderr, "%s at line %d\n", XML_ErrorString(XML_GetErrorCode(parser)), (int) XML_GetCurrentLineNumber(parser)); fprintf(stderr, "\tBuffer was:\n"); fflush(stderr); fwrite(buf, 1, len, stderr); fflush(stderr); fprintf(stderr, "\n"); fflush(stderr); userData.lastInsertedHandle = Handle::UNDEFINED; break; } } while (!done); xmlReader->close(); XML_ParserFree(parser); return userData.lastInsertedHandle; } Handle NMXmlParser::parse(XMLBufferReader* xmlReader, NMXmlParseType pass) { Handle h = Handle::UNDEFINED; if (pass == PARSE_NODES) { logger().fine("Parsing nodes...\n"); // FIRST PASS - creates relationships with arity == 0 (nodes) h = parse_pass(xmlReader, pass); if (h == Handle::UNDEFINED) return Handle::UNDEFINED; } else if (pass == PARSE_LINKS) { logger().fine("Parsing links...\n"); // SECOND PASS - creates other relationships // second pass must be avoided once subgraph insertion and/or lazy // insertion is implemented h = parse_pass(xmlReader, pass); } return h; } Replace printf with logger /* * opencog/xml/NMXmlParser.cc * * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * Written by Thiago Maia <thiago@vettatech.com> * Andre Senna <senna@vettalabs.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <stack> #include <string> #include <math.h> #include <expat.h> #include <opencog/util/platform.h> #include <opencog/atomspace/Link.h> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/util/Logger.h> #include <opencog/xml/FileXMLBufferReader.h> #include <opencog/xml/NMXmlDefinitions.h> #include <opencog/xml/NMXmlParser.h> /* * XXX To be fixed: remove all of the uses of "throw" in this code, * to be replaced by a gentler error mechanism. The problem is two-fold: * the "throws" are made from within routines that are called by the * external libxmlparser library, which is written in C, not C++. * Thus, these errors can't ever actually be caught, since they never * get through the parser. As a result, any minor mistake in an XML * will cause the entire server to crash, which is just plain ugly. * Yuck! * NOTE: Any time information (including Timestamps) are represented using Atoms as follows: * AtTimeLink(TimeNode:<temporalStringValue>, Atom1 [, Atom2 [... , AtomN]]) */ using namespace opencog; std::tr1::unordered_map<const std::string, Handle, hash<std::string>, std::equal_to<std::string> > NMXmlParser::hypHandles; bool NMXmlParser::fresh = true; bool NMXmlParser::freshLinks = false; // If unspecified, the default truth value is "true", with confidence of 0.5 const TruthValue& NMXmlParser::DEFAULT_TV() { static SimpleTruthValue* instance = NULL; if (instance == NULL) { instance = new SimpleTruthValue(1.0f, 1.0f); instance->setConfidence(0.5); } return *instance; } // const int TYPE_LENGTH = (int) log10((double)NUMBER_OF_CLASSES) + 1; typedef struct { unsigned enabled: 1; unsigned ignoring: 1; unsigned processNodes: 1; unsigned processRelationships: 1; } Status; typedef std::stack<void*> ParserStack; // TODO: CREATE AN ABSTRACT CLASS "Stackable" for check for subclasses // when poping elements from stack. typedef struct { AtomSpace* atomSpace; //AtomTable* atomTable; ParserStack stack; Handle lastInsertedHandle; Status status; XML_Parser parser; } UserData; static void push(ParserStack& ps, void* p) { ps.push(p); } static void* top(ParserStack& ps) { if (!ps.size()) return NULL; return ps.top(); } static void* pop(ParserStack& ps) { if (!ps.size()) return NULL; void* ret = ps.top(); ps.pop(); return ret; } /** * Return the type corresponding to the type name */ static Type getTypeFromString(const char *name, bool onlyClassName) { if (!name) return NOTYPE; Type result = classserver().getType(name); if (result != NOTYPE) { return result; } if (strcmp(name, POLYGON_CORNER_TOKEN) != 0 && (onlyClassName || strcmp(name, ELEMENT_TOKEN) != 0)) { logger().error("Warning: null type for name returned! (%s)\n", name); } return 0; } #ifdef NOT_USED_RIGHT_NOW static char *nativeBuildLinkKey(Atom *link) { char key[1<<16]; char aux[1 << 16]; key[0] = '\0'; sprintf(aux, "%d ", link->getType()); strcat(key, aux); for (int i = 0; i < link->getArity(); i++) { sprintf(aux, "%p ", TLB::getHandle(link->getOutgoingAtom(i))); strcat(key, aux); } return strdup(key); } #endif /* NOT_USED_RIGHT_NOW */ //#include <sys/time.h> //unsigned long int cumulativeParseNodesStart = 0; //unsigned long int cumulativeParseLinksStart = 0; //unsigned long int cumulativeParseEnd = 0; //unsigned long int cumulativeParseEnd1 = 0; //unsigned long int cumulativeParseEnd2 = 0; /** * Handle attributes that are common to both Nodes and Links. * In other words, handle "confidence" and "strength" attributes. */ static const char ** scan_common_attrs (Atom *r, const char **atts) { float buffer; if (strcmp(*atts, CONFIDENCE_TOKEN) == 0) { atts++; sscanf(*atts, "%f", &buffer); SimpleTruthValue newTv((const SimpleTruthValue&)r->getTruthValue()); newTv.setConfidence(buffer); r->setTruthValue(newTv); } else if (strcmp(*atts, STRENGTH_TOKEN) == 0) { atts++; sscanf(*atts, "%f", &buffer); SimpleTruthValue newTv((const SimpleTruthValue&)r->getTruthValue()); newTv.setMean(buffer); r->setTruthValue(newTv); } return atts; } static void nativeStartElement(void *userData, const char *name, const char **atts) throw (RuntimeException, InconsistenceException) { Atom* r = NULL; Type typeFound; UserData* ud = (UserData*) userData; // processes head tags (list, tagdescription, etc) if (strcmp(name, LIST_TOKEN) == 0) { ud->status.enabled = 1; return; } else if (strcmp(name, TAG_DESCRIPTION_TOKEN) == 0) { ud->status.ignoring = 1; return; } // abandons element if necessary if ((!ud->status.enabled) || ud->status.ignoring) return; typeFound = getTypeFromString(name, false); if (NOTYPE == typeFound) return; // processes nodes if (ud->status.processNodes) { // timeval s; // gettimeofday(&s, NULL); if (classserver().isA(typeFound, NODE)) { //cprintf(5,"Processing Node: %d (%s)\n", typeFound, name); r = (Atom*) new Node(typeFound, "", NMXmlParser::DEFAULT_TV()); logger().fine("Pushing r = %p", r); push(ud->stack, r); const TruthValue& t = r->getTruthValue(); if (typeid(t) != typeid(SimpleTruthValue)) { throw InconsistenceException(TRACE_INFO, "DefaultTruthValue is not SimpleTruthValue."); } while (*atts != NULL) { if (strcmp(*atts, NAME_TOKEN) == 0) { atts++; NMXmlParser::setNodeName((Node*) r, *atts); } else { const char **natts = scan_common_attrs(r, atts); if (atts == natts) { logger().error("unrecognized Node token: %s\n", *atts); } atts = natts; } atts++; } } // timeval e; // gettimeofday(&e, NULL); // unsigned long spentTime = (e.tv_sec - s.tv_sec)*1000000+(e.tv_usec - s.tv_usec); // cumulativeParseNodesStart += spentTime; } // processes relationships if (ud->status.processRelationships) { // inheritance links may be declared inside lexical category node // tags. this information is ignored once it is redundant with source // and target data contained in the inheritance link declaration if (classserver().isA(typeFound, LINK)) { // timeval s; // gettimeofday(&s, NULL); logger().fine("Processing Link: %d (%s)\n", typeFound, name); r = (Atom*) new Link(typeFound, std::vector<Handle>(), NMXmlParser::DEFAULT_TV()); const TruthValue& t = r->getTruthValue(); if (typeid(t) != typeid(SimpleTruthValue)) { throw InconsistenceException(TRACE_INFO, "DefaultTruthValue is not SimpleTruthValue"); } while (*atts != NULL) { const char **natts = scan_common_attrs(r, atts); if (atts == natts) { logger().error("unrecognized Link token: %s\n", *atts); } atts = natts; atts++; } Atom* currentAtom = (Atom*) top(ud->stack); if (currentAtom != NULL) { logger().fine("Getting link element inside currentAtom = %p", currentAtom); Link *link = dynamic_cast<Link *>(currentAtom); if (link) { if (r != NULL) { NMXmlParser::addOutgoingAtom(link, Handle::UNDEFINED); } else { throw RuntimeException(TRACE_INFO, "fatal error: NULL inner link"); } } } logger().fine("Pushing r = %p", r); push(ud->stack, r); // timeval e; // gettimeofday(&e, NULL); // unsigned long spentTime = (e.tv_sec - s.tv_sec)*1000000+(e.tv_usec - s.tv_usec); // cumulativeParseLinksStart += spentTime; } else if (strcmp(name, ELEMENT_TOKEN) == 0) { // processes elements of other relationships, and inserts them in // the link previously defined; Atom* currentAtom = (Atom*) top(ud->stack); if (currentAtom == NULL) { logger().error("error: this token (%s) is expected to be nested\n", name); return; } logger().fine("Getting node element inside currentAtom = %p", currentAtom); const char *n = NULL, *t = NULL; while (*atts != NULL) { if (strcmp(*atts, NAME_TOKEN) == 0) { atts++; n = *atts; } else if (strcmp(*atts, CLASS_TOKEN) == 0) { atts++; t = *atts; } else { logger().error("unrecognized token: %s\n", *atts); } atts++; } Handle h; //r = getRelationshipByNameAndType(n, getTypeFromString(t, true)); logger().fine("Getting existing node (%s,%s)", n, t); //h = ud->atomTable->getHandle(n, getTypeFromString(t, true)); h = ud->atomSpace->getHandle(getTypeFromString(t, true), n); logger().fine(" => h = %p", h.value()); if (TLB::isValidHandle(h)) { logger().fine(TLB::getAtom(h)->toString().c_str()); Link *link = dynamic_cast<Link *>(currentAtom); if (link) { logger().fine("adding atom %s to link %s", TLB::getAtom(h)->toShortString().c_str(), link->toShortString().c_str()); NMXmlParser::addOutgoingAtom(link, h); } } else { #ifdef THROW_EXCEPTIONS throw RuntimeException(TRACE_INFO, "fatal error: unable to find atom named %s, type %s", n, t); #else /* Don't just core dump on bad XML format. * (since exceptions can't be thrown past the C library * of the parser, a core dump is inevitable). */ fprintf (stderr, "Fatal error: unable to find atom named %s, type %s\n", n, t); logger().error( "fatal error: unable to find atom named %s, type %s\n", n, t); #endif } } } } static void nativeEndElement(void *userData, const char *name) throw (InconsistenceException) { UserData* ud = (UserData*) userData; if (strcmp(name, LIST_TOKEN) == 0) { ud->status.enabled = 0; } else if (strcmp(name, TAG_DESCRIPTION_TOKEN) == 0) { ud->status.ignoring = 0; } else { void* object = top(ud->stack); Atom* currentAtom = (Atom*) object; if (currentAtom != NULL) { //timeval s; //gettimeofday(&s, NULL); Type type = getTypeFromString(name, false); if ((classserver().isA(type, NODE) && ud->status.processNodes) || (classserver().isA(type, LINK) && ud->status.processRelationships)) { if (currentAtom->getType() == type) { if (classserver().isA(type, LINK)) { pop(ud->stack); logger().fine("(1) Pushing currentAtom = %p", currentAtom); push(ud->stack, currentAtom); } if (classserver().isA(type, UNORDERED_LINK)) { // Forces the sorting of outgoing by calling setOutgoingSet // TODO: implement a sortOutgoingSet for doing the same thing more efficiently... Link *link = dynamic_cast<Link *>(currentAtom); if (link) { std::vector<Handle> outgoing = link->getOutgoingSet(); NMXmlParser::setOutgoingSet(link, outgoing); } } Handle oldHandle = NMXmlParser::holdsHandle(currentAtom); //timeval s1; //gettimeofday(&s1, NULL); logger().fine("currentAtom => %s", currentAtom->toString().c_str()); //Handle newHandle = ud->atomTable->add(currentAtom); Handle newHandle = ud->atomSpace->addRealAtom(*currentAtom); //timeval e1; //gettimeofday(&e1, NULL); //signed long spentTime1 = (e1.tv_sec - s1.tv_sec)*1000000+(e1.tv_usec - s1.tv_usec); //unsigned long spentTime1 = (e1.tv_sec - s.tv_sec)*1000000+(e1.tv_usec - s.tv_usec); //cumulativeParseEnd1 += spentTime1; // Updates last inserted/merged atom handle ud->lastInsertedHandle = newHandle; if (CoreUtils::handleCompare(&oldHandle, &newHandle)) { // already existed delete currentAtom; logger().fine("Already existed"); currentAtom = TLB::getAtom(newHandle); pop(ud->stack); logger().fine("(2) Pushing currentAtom = %p", currentAtom); push(ud->stack, currentAtom); } // XXX FIXME: // would be better if this was replaced by // if (NULL != dynamic_cast<Link *>(currentAtom)) // and also a few lines down. if (classserver().isA(currentAtom->getType(), LINK)) { //KMI -- find out if this is a nested link pop(ud->stack); Atom* nextUd = (Atom*) top(ud->stack); logger().fine("Getting link element inside nextUd = %p", nextUd); logger().fine("(3) Pushing currentAtom = %p", currentAtom); push(ud->stack, currentAtom); Link *nextlink = dynamic_cast<Link *>(nextUd); if (nextlink != NULL) { int arity = nextlink->getArity(); std::vector<Handle> outgoingSet = nextlink->getOutgoingSet(); for (int i = 0; i < arity; i++) { if (TLB::isInvalidHandle(outgoingSet[i])) { outgoingSet[i] = newHandle; break; } } NMXmlParser::setOutgoingSet(nextlink, outgoingSet); } } } else { char buff[300]; snprintf(buff, 300, "XML parse error: relationship type mismatch at line %d.\n" "\txml type=%s(%d) current atom type=%d %s", (int) XML_GetCurrentLineNumber(ud->parser), name, type, currentAtom->getType(), currentAtom->toString().c_str()); throw InconsistenceException(TRACE_INFO, buff); } pop(ud->stack); } //timeval e; //gettimeofday(&e, NULL); //unsigned long spentTime = (e.tv_sec - s.tv_sec)*1000000+(e.tv_usec - s.tv_usec); //cumulativeParseEnd += spentTime; else { logger().fine("WARNING: Got NULL Atom* from the parser stack!"); } } } } NMXmlParser::NMXmlParser(AtomSpace* atomSpace, bool fresh, bool freshLinks) { this->atomSpace = atomSpace; this->fresh = fresh; this->freshLinks = freshLinks; } NMXmlParser::~NMXmlParser() { } void NMXmlParser::setNodeName(Node* node, const char* name) { node->setName(name); } void NMXmlParser::addOutgoingAtom(Link * link, Handle h) { link->addOutgoingAtom(h); } void NMXmlParser::setOutgoingSet(Link * link, const std::vector<Handle>& outgoing) { link->setOutgoingSet(outgoing); } HandleEntry* NMXmlParser::loadXML(const std::vector<XMLBufferReader*>& xmlReaders, AtomSpace * atomSpace, bool fresh, bool freshLinks) { logger().fine("NMXmlParser::loadXML"); cassert(TRACE_INFO, atomSpace != NULL, "loadXML - atomSpace should pointer should not be NULL."); HandleEntry* result = NULL; if (xmlReaders.size() <= 0) return result; NMXmlParser parser(atomSpace, fresh, freshLinks); // time_t start = time(NULL); // timeval s; // gettimeofday(&s, NULL); // Only nodes are processed in the first pass for (unsigned int i = 0; i < xmlReaders.size(); i++) { if (typeid(*xmlReaders[i]) == typeid(FileXMLBufferReader)) { logger().fine("First pass: processing file %s\n", ((FileXMLBufferReader*) xmlReaders[i])->getFilename()); } // please don't log -- this will spew millions of messages when // there are millions of files to be loaded, as would be the // case when the xml is auto-generated and piped over from // another process. // logger().warn("Loading XML: %d%% done.\r", (int) (100 * ((float) i / (xmlReaders.size() * 2)))); parser.parse(xmlReaders[i], PARSE_NODES); } //timeval e; //gettimeofday(&e, NULL); //unsigned long spentTime = (e.tv_sec*1000 + e.tv_usec/1000) - (s.tv_sec*1000 + s.tv_usec/1000); //printf("PARSE NODES time = %lu\n", spentTime); //s = e; // only links are processed in the second pass for (unsigned int i = 0; i < xmlReaders.size(); i++) { if (typeid(*xmlReaders[i]) == typeid(FileXMLBufferReader)) { logger().fine("Second pass: processing file %s\n", ((FileXMLBufferReader*) xmlReaders[i])->getFilename()); } // logger().warn("Loading XML: %d%% done.\r", (int) (100 * ((float) (i + xmlReaders.size()) / (xmlReaders.size() * 2)))); Handle lastInsertedLinkHandle = parser.parse(xmlReaders[i], PARSE_LINKS); Handle uh(Handle::UNDEFINED); if (CoreUtils::handleCompare(&lastInsertedLinkHandle, &uh)) { result = HandleEntry::concatenation(result, new HandleEntry(lastInsertedLinkHandle)); } } // finally, null names of unnamed nodes for (HandleEntry *e = result; e; e = e->next) { Atom *a = TLB::getAtom(e->handle); if (classserver().isNode(a->getType())) { Node *n = (Node*)a; if (n->getName()[0] == '#') n->setName(""); } } //time_t duration = time(NULL) - start; //timeval e; //gettimeofday(&e, NULL); //unsigned long spentTime = (e.tv_sec-s.tv_sec)*1000000 + (e.tv_usec-s.tv_usec); //printf("PARSE XML time = %lu\n", spentTime); //logger().warn("Loading XML contents: 100%% done (in %d second%c).\n", (int) duration, duration == 1 ? '\0' : 's'); //cprintf(NORMAL, "Number of timestamp entries: %d\n", stackTimeFlag); return result; } Handle NMXmlParser::parse_pass(XMLBufferReader* xmlReader, NMXmlParseType pass) { char buf[BUFSIZ]; int done; UserData userData; userData.lastInsertedHandle = Handle::UNDEFINED; //userData.atomTable = atomSpace->getAtomTable(); userData.atomSpace = atomSpace; userData.status.enabled = 0; userData.status.ignoring = 0; if (pass == PARSE_NODES) { userData.status.processNodes = 1; userData.status.processRelationships = 0; } else { userData.status.processNodes = 0; userData.status.processRelationships = 1; } XML_Parser parser = XML_ParserCreate(NULL); userData.parser = parser; XML_SetUserData(parser, &userData); XML_SetElementHandler(parser, nativeStartElement, nativeEndElement); xmlReader->open(); do { size_t len = xmlReader->read(buf, 1, sizeof(buf)); done = len < sizeof(buf); if (!XML_Parse(parser, buf, len, done)) { fprintf(stderr, "%s at line %d\n", XML_ErrorString(XML_GetErrorCode(parser)), (int) XML_GetCurrentLineNumber(parser)); fprintf(stderr, "\tBuffer was:\n"); fflush(stderr); fwrite(buf, 1, len, stderr); fflush(stderr); fprintf(stderr, "\n"); fflush(stderr); userData.lastInsertedHandle = Handle::UNDEFINED; break; } } while (!done); xmlReader->close(); XML_ParserFree(parser); return userData.lastInsertedHandle; } Handle NMXmlParser::parse(XMLBufferReader* xmlReader, NMXmlParseType pass) { Handle h = Handle::UNDEFINED; if (pass == PARSE_NODES) { logger().fine("Parsing nodes...\n"); // FIRST PASS - creates relationships with arity == 0 (nodes) h = parse_pass(xmlReader, pass); if (h == Handle::UNDEFINED) return Handle::UNDEFINED; } else if (pass == PARSE_LINKS) { logger().fine("Parsing links...\n"); // SECOND PASS - creates other relationships // second pass must be avoided once subgraph insertion and/or lazy // insertion is implemented h = parse_pass(xmlReader, pass); } return h; }
/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <concepts> #include <boost/range/algorithm/copy.hpp> #include <boost/range/algorithm/for_each.hpp> #include "bytes.hh" enum class mutable_view { no, yes, }; /// Fragmented buffer /// /// Concept `FragmentedBuffer` is satisfied by any class that is a range of /// fragments and provides a method `size_bytes()` which returns the total /// size of the buffer. The interfaces accepting `FragmentedBuffer` will attempt /// to avoid unnecessary linearisation. template<typename T> concept FragmentRange = requires (T range) { typename T::fragment_type; requires std::is_same_v<typename T::fragment_type, bytes_view> || std::is_same_v<typename T::fragment_type, bytes_mutable_view>; { *range.begin() } -> std::convertible_to<const typename T::fragment_type&>; { *range.end() } -> std::convertible_to<const typename T::fragment_type&>; { range.size_bytes() } -> std::convertible_to<size_t>; { range.empty() } -> std::same_as<bool>; // returns true iff size_bytes() == 0. }; template<typename T, typename = void> struct is_fragment_range : std::false_type { }; template<typename T> struct is_fragment_range<T, std::void_t<typename T::fragment_type>> : std::true_type { }; template<typename T> static constexpr bool is_fragment_range_v = is_fragment_range<T>::value; /// A non-mutable view of a FragmentRange /// /// Provide a trivially copyable and movable, non-mutable view on a /// fragment range. This allows uniform ownership semantics across /// multi-fragment ranges and the single fragment and empty fragment /// adaptors below, i.e. it allows treating all fragment ranges /// uniformly as views. template <typename T> requires FragmentRange<T> class fragment_range_view { const T* _range; public: using fragment_type = typename T::fragment_type; using iterator = typename T::const_iterator; using const_iterator = typename T::const_iterator; public: explicit fragment_range_view(const T& range) : _range(&range) { } const_iterator begin() const { return _range->begin(); } const_iterator end() const { return _range->end(); } size_t size_bytes() const { return _range->size_bytes(); } bool empty() const { return _range->empty(); } }; /// Single-element fragment range /// /// This is a helper that allows converting a bytes_view into a FragmentRange. template<mutable_view is_mutable> class single_fragment_range { public: using fragment_type = std::conditional_t<is_mutable == mutable_view::no, bytes_view, bytes_mutable_view>; private: fragment_type _view; public: using iterator = const fragment_type*; using const_iterator = const fragment_type*; explicit single_fragment_range(fragment_type f) : _view { f } { } const_iterator begin() const { return &_view; } const_iterator end() const { return &_view + 1; } size_t size_bytes() const { return _view.size(); } bool empty() const { return _view.empty(); } }; single_fragment_range(bytes_view) -> single_fragment_range<mutable_view::no>; single_fragment_range(bytes_mutable_view) -> single_fragment_range<mutable_view::yes>; /// Empty fragment range. struct empty_fragment_range { using fragment_type = bytes_view; using iterator = bytes_view*; using const_iterator = bytes_view*; iterator begin() const { return nullptr; } iterator end() const { return nullptr; } size_t size_bytes() const { return 0; } bool empty() const { return true; } }; static_assert(FragmentRange<empty_fragment_range>); static_assert(FragmentRange<single_fragment_range<mutable_view::no>>); static_assert(FragmentRange<single_fragment_range<mutable_view::yes>>); template<typename FragmentedBuffer> requires FragmentRange<FragmentedBuffer> bytes linearized(const FragmentedBuffer& buffer) { bytes b(bytes::initialized_later(), buffer.size_bytes()); auto dst = b.begin(); using boost::range::for_each; for_each(buffer, [&] (bytes_view fragment) { dst = boost::copy(fragment, dst); }); return b; } template<typename FragmentedBuffer, typename Function> requires FragmentRange<FragmentedBuffer> && requires (Function fn, bytes_view bv) { fn(bv); } decltype(auto) with_linearized(const FragmentedBuffer& buffer, Function&& fn) { bytes b; bytes_view bv; if (__builtin_expect(!buffer.empty() && std::next(buffer.begin()) == buffer.end(), true)) { bv = *buffer.begin(); } else if (!buffer.empty()) { b = linearized(buffer); bv = b; } return fn(bv); } template<typename T> concept FragmentedView = requires (T view, size_t n) { typename T::fragment_type; requires std::is_same_v<typename T::fragment_type, bytes_view> || std::is_same_v<typename T::fragment_type, bytes_mutable_view>; // No preconditions. { view.current_fragment() } -> std::convertible_to<const typename T::fragment_type&>; // No preconditions. { view.size_bytes() } -> std::convertible_to<size_t>; // Precondition: n <= size_bytes() { view.prefix(n) } -> std::same_as<T>; // Precondition: n <= size_bytes() view.remove_prefix(n); // Precondition: size_bytes() > 0 view.remove_current(); }; template<typename T> concept FragmentedMutableView = requires (T view) { requires FragmentedView<T>; requires std::is_same_v<typename T::fragment_type, bytes_mutable_view>; }; template<FragmentedView View> requires (!FragmentRange<View>) bytes linearized(View v) { bytes b(bytes::initialized_later(), v.size_bytes()); auto out = b.begin(); while (v.size_bytes()) { out = std::copy(v.current_fragment().begin(), v.current_fragment().end(), out); v.remove_current(); } return b; } template<FragmentedView View, typename Function> requires (!FragmentRange<View>) && std::invocable<Function, bytes_view> decltype(auto) with_linearized(const View& v, Function&& fn) { if (v.size_bytes() == v.current_fragment().size()) [[likely]] { return fn(v.current_fragment()); } else { return fn(linearized(v)); } } class single_fragmented_view { bytes_view _view; public: using fragment_type = bytes_view; explicit single_fragmented_view(bytes_view bv) : _view(bv) {} size_t size_bytes() const { return _view.size(); } void remove_prefix(size_t n) { _view.remove_prefix(n); } void remove_current() { _view = bytes_view(); } bytes_view current_fragment() const { return _view; } single_fragmented_view prefix(size_t n) { return single_fragmented_view(_view.substr(0, n)); } }; static_assert(FragmentedView<single_fragmented_view>); utils: fragment_range: use range-based for loop instead of boost::for_each We want to pass bytes_ostream to this loop in later commits. bytes_ostream does not conform to some boost concepts required by boost::for_each, so let's just use C++'s native loop. /* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <concepts> #include <boost/range/algorithm/copy.hpp> #include <boost/range/algorithm/for_each.hpp> #include "bytes.hh" enum class mutable_view { no, yes, }; /// Fragmented buffer /// /// Concept `FragmentedBuffer` is satisfied by any class that is a range of /// fragments and provides a method `size_bytes()` which returns the total /// size of the buffer. The interfaces accepting `FragmentedBuffer` will attempt /// to avoid unnecessary linearisation. template<typename T> concept FragmentRange = requires (T range) { typename T::fragment_type; requires std::is_same_v<typename T::fragment_type, bytes_view> || std::is_same_v<typename T::fragment_type, bytes_mutable_view>; { *range.begin() } -> std::convertible_to<const typename T::fragment_type&>; { *range.end() } -> std::convertible_to<const typename T::fragment_type&>; { range.size_bytes() } -> std::convertible_to<size_t>; { range.empty() } -> std::same_as<bool>; // returns true iff size_bytes() == 0. }; template<typename T, typename = void> struct is_fragment_range : std::false_type { }; template<typename T> struct is_fragment_range<T, std::void_t<typename T::fragment_type>> : std::true_type { }; template<typename T> static constexpr bool is_fragment_range_v = is_fragment_range<T>::value; /// A non-mutable view of a FragmentRange /// /// Provide a trivially copyable and movable, non-mutable view on a /// fragment range. This allows uniform ownership semantics across /// multi-fragment ranges and the single fragment and empty fragment /// adaptors below, i.e. it allows treating all fragment ranges /// uniformly as views. template <typename T> requires FragmentRange<T> class fragment_range_view { const T* _range; public: using fragment_type = typename T::fragment_type; using iterator = typename T::const_iterator; using const_iterator = typename T::const_iterator; public: explicit fragment_range_view(const T& range) : _range(&range) { } const_iterator begin() const { return _range->begin(); } const_iterator end() const { return _range->end(); } size_t size_bytes() const { return _range->size_bytes(); } bool empty() const { return _range->empty(); } }; /// Single-element fragment range /// /// This is a helper that allows converting a bytes_view into a FragmentRange. template<mutable_view is_mutable> class single_fragment_range { public: using fragment_type = std::conditional_t<is_mutable == mutable_view::no, bytes_view, bytes_mutable_view>; private: fragment_type _view; public: using iterator = const fragment_type*; using const_iterator = const fragment_type*; explicit single_fragment_range(fragment_type f) : _view { f } { } const_iterator begin() const { return &_view; } const_iterator end() const { return &_view + 1; } size_t size_bytes() const { return _view.size(); } bool empty() const { return _view.empty(); } }; single_fragment_range(bytes_view) -> single_fragment_range<mutable_view::no>; single_fragment_range(bytes_mutable_view) -> single_fragment_range<mutable_view::yes>; /// Empty fragment range. struct empty_fragment_range { using fragment_type = bytes_view; using iterator = bytes_view*; using const_iterator = bytes_view*; iterator begin() const { return nullptr; } iterator end() const { return nullptr; } size_t size_bytes() const { return 0; } bool empty() const { return true; } }; static_assert(FragmentRange<empty_fragment_range>); static_assert(FragmentRange<single_fragment_range<mutable_view::no>>); static_assert(FragmentRange<single_fragment_range<mutable_view::yes>>); template<typename FragmentedBuffer> requires FragmentRange<FragmentedBuffer> bytes linearized(const FragmentedBuffer& buffer) { bytes b(bytes::initialized_later(), buffer.size_bytes()); auto dst = b.begin(); for (bytes_view fragment : buffer) { dst = boost::copy(fragment, dst); } return b; } template<typename FragmentedBuffer, typename Function> requires FragmentRange<FragmentedBuffer> && requires (Function fn, bytes_view bv) { fn(bv); } decltype(auto) with_linearized(const FragmentedBuffer& buffer, Function&& fn) { bytes b; bytes_view bv; if (__builtin_expect(!buffer.empty() && std::next(buffer.begin()) == buffer.end(), true)) { bv = *buffer.begin(); } else if (!buffer.empty()) { b = linearized(buffer); bv = b; } return fn(bv); } template<typename T> concept FragmentedView = requires (T view, size_t n) { typename T::fragment_type; requires std::is_same_v<typename T::fragment_type, bytes_view> || std::is_same_v<typename T::fragment_type, bytes_mutable_view>; // No preconditions. { view.current_fragment() } -> std::convertible_to<const typename T::fragment_type&>; // No preconditions. { view.size_bytes() } -> std::convertible_to<size_t>; // Precondition: n <= size_bytes() { view.prefix(n) } -> std::same_as<T>; // Precondition: n <= size_bytes() view.remove_prefix(n); // Precondition: size_bytes() > 0 view.remove_current(); }; template<typename T> concept FragmentedMutableView = requires (T view) { requires FragmentedView<T>; requires std::is_same_v<typename T::fragment_type, bytes_mutable_view>; }; template<FragmentedView View> requires (!FragmentRange<View>) bytes linearized(View v) { bytes b(bytes::initialized_later(), v.size_bytes()); auto out = b.begin(); while (v.size_bytes()) { out = std::copy(v.current_fragment().begin(), v.current_fragment().end(), out); v.remove_current(); } return b; } template<FragmentedView View, typename Function> requires (!FragmentRange<View>) && std::invocable<Function, bytes_view> decltype(auto) with_linearized(const View& v, Function&& fn) { if (v.size_bytes() == v.current_fragment().size()) [[likely]] { return fn(v.current_fragment()); } else { return fn(linearized(v)); } } class single_fragmented_view { bytes_view _view; public: using fragment_type = bytes_view; explicit single_fragmented_view(bytes_view bv) : _view(bv) {} size_t size_bytes() const { return _view.size(); } void remove_prefix(size_t n) { _view.remove_prefix(n); } void remove_current() { _view = bytes_view(); } bytes_view current_fragment() const { return _view; } single_fragmented_view prefix(size_t n) { return single_fragmented_view(_view.substr(0, n)); } }; static_assert(FragmentedView<single_fragmented_view>);
/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include <array> #include <type_traits> #include "utils/allocation_strategy.hh" template<typename T, unsigned InternalSize = 0, typename SizeType = size_t> class managed_vector { static_assert(std::is_nothrow_move_constructible<T>::value, "objects stored in managed_vector need to be nothrow move-constructible"); public: using value_type = T; using size_type = SizeType; using iterator = T*; using const_iterator = const T*; private: struct external { managed_vector* _backref; T _data[]; external(external&& other) noexcept : _backref(other._backref) { for (unsigned i = 0; i < _backref->size(); i++) { new (_data + i) T(std::move(other._data[i])); other._data[i].~T(); } _backref->_data = _data; } }; union maybe_constructed { constexpr maybe_constructed() { } ~maybe_constructed() { } T object; }; private: std::array<maybe_constructed, InternalSize> _internal; size_type _size = 0; size_type _capacity = InternalSize; T* _data = reinterpret_cast<T*>(_internal.data()); private: bool is_external() const { return _data != reinterpret_cast<const T*>(_internal.data()); } external* get_external() { auto ptr = reinterpret_cast<char*>(_data) - offsetof(external, _data); return reinterpret_cast<external*>(ptr); } void maybe_grow(size_type new_size) { if (new_size <= _capacity) { return; } auto new_capacity = std::max({ _capacity + std::min(_capacity, size_type(1024)), new_size, size_type(InternalSize + 8) }); reserve(new_capacity); } public: managed_vector() = default; managed_vector(const managed_vector& other) { reserve(other._size); for (const auto& v : other) { push_back(v); } } managed_vector(managed_vector&& other) noexcept : _size(other._size), _capacity(other._capacity) { if (other.is_external()) { _data = other._data; other._data = reinterpret_cast<T*>(other._internal.data()); get_external()->_backref = this; } else { for (unsigned i = 0; i < _size; i++) { new (_data + i) T(std::move(other._data[i])); other._data[i].~T(); } } other._size = 0; other._capacity = InternalSize; } managed_vector& operator=(const managed_vector& other) { // FIXME: not exception safe if (this != &other) { this->~managed_vector(); new (this) managed_vector(other); } return *this; } managed_vector& operator=(managed_vector&& other) noexcept { if (this != &other) { this->~managed_vector(); new (this) managed_vector(std::move(other)); } return *this; } ~managed_vector() { clear(); if (is_external()) { current_allocator().free(get_external()); } } T& at(size_type pos) { if (pos >= _size) { throw std::out_of_range("out of range"); } return operator[](pos); } const T& at(size_type pos) const { if (pos >= _size) { throw std::out_of_range("out of range"); } return operator[](pos); } T& operator[](size_type pos) noexcept { return _data[pos]; } const T& operator[](size_type pos) const noexcept { return _data[pos]; } T& front() noexcept { return *_data; } const T& front() const noexcept { return *_data; } T& back() noexcept { return _data[_size - 1]; } const T& back() const noexcept { return _data[_size - 1]; } T* data() noexcept { return _data; } const T* data() const noexcept { return _data; } iterator begin() noexcept { return _data; } const_iterator begin() const noexcept { return _data; } const_iterator cbegin() const noexcept { return _data; } iterator end() noexcept { return _data + _size; } const_iterator end() const noexcept { return _data + _size; } const_iterator cend() const noexcept { return _data + _size; } bool empty() const noexcept { return !_size; } size_type size() const noexcept { return _size; } size_type capacity() const noexcept { return _capacity; } void clear() { while (_size) { pop_back(); } } void reserve(size_type new_capacity) { if (new_capacity <= _capacity) { return; } auto ptr = current_allocator().alloc(standard_migrator<external>, sizeof(external) + sizeof(T) * new_capacity, alignof(external)); auto ext = static_cast<external*>(ptr); ext->_backref = this; T* data_ptr = ext->_data; for (unsigned i = 0; i < _size; i++) { new (data_ptr + i) T(std::move(_data[i])); _data[i].~T(); } if (is_external()) { current_allocator().free(get_external()); } _data = data_ptr; _capacity = new_capacity; } iterator erase(iterator it) { std::move(it + 1, end(), it); _data[_size - 1].~T(); _size--; return it; } void push_back(const T& value) { emplace_back(value); } void push_back(T&& value) { emplace_back(std::move(value)); } template<typename... Args> void emplace_back(Args&&... args) { maybe_grow(_size + 1); new (_data + _size) T(std::forward<Args>(args)...); _size++; } void pop_back() { _data[_size - 1].~T(); _size--; } void resize(size_type new_size) { maybe_grow(new_size); while (_size > new_size) { pop_back(); } while (_size < new_size) { emplace_back(); } } void resize(size_type new_size, const T& value) { maybe_grow(new_size); while (_size > new_size) { pop_back(); } while (_size < new_size) { push_back(value); } } }; utils: managed_vector: Make copy constructor exception-safe Copying values may throw (std::bad_alloc for example), which will result in a leak because destructor will not be called when constructor throws. May manifest as the following assertion failure: utils/logalloc.cc:672: virtual logalloc::region_impl::~region_impl(): Assertion `_active->is_empty()' failed. /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include <array> #include <type_traits> #include "utils/allocation_strategy.hh" template<typename T, unsigned InternalSize = 0, typename SizeType = size_t> class managed_vector { static_assert(std::is_nothrow_move_constructible<T>::value, "objects stored in managed_vector need to be nothrow move-constructible"); public: using value_type = T; using size_type = SizeType; using iterator = T*; using const_iterator = const T*; private: struct external { managed_vector* _backref; T _data[]; external(external&& other) noexcept : _backref(other._backref) { for (unsigned i = 0; i < _backref->size(); i++) { new (_data + i) T(std::move(other._data[i])); other._data[i].~T(); } _backref->_data = _data; } }; union maybe_constructed { constexpr maybe_constructed() { } ~maybe_constructed() { } T object; }; private: std::array<maybe_constructed, InternalSize> _internal; size_type _size = 0; size_type _capacity = InternalSize; T* _data = reinterpret_cast<T*>(_internal.data()); private: bool is_external() const { return _data != reinterpret_cast<const T*>(_internal.data()); } external* get_external() { auto ptr = reinterpret_cast<char*>(_data) - offsetof(external, _data); return reinterpret_cast<external*>(ptr); } void maybe_grow(size_type new_size) { if (new_size <= _capacity) { return; } auto new_capacity = std::max({ _capacity + std::min(_capacity, size_type(1024)), new_size, size_type(InternalSize + 8) }); reserve(new_capacity); } void clear_and_release() noexcept { clear(); if (is_external()) { current_allocator().free(get_external()); } } public: managed_vector() = default; managed_vector(const managed_vector& other) { reserve(other._size); try { for (const auto& v : other) { push_back(v); } } catch (...) { clear_and_release(); throw; } } managed_vector(managed_vector&& other) noexcept : _size(other._size), _capacity(other._capacity) { if (other.is_external()) { _data = other._data; other._data = reinterpret_cast<T*>(other._internal.data()); get_external()->_backref = this; } else { for (unsigned i = 0; i < _size; i++) { new (_data + i) T(std::move(other._data[i])); other._data[i].~T(); } } other._size = 0; other._capacity = InternalSize; } managed_vector& operator=(const managed_vector& other) { // FIXME: not exception safe if (this != &other) { this->~managed_vector(); new (this) managed_vector(other); } return *this; } managed_vector& operator=(managed_vector&& other) noexcept { if (this != &other) { this->~managed_vector(); new (this) managed_vector(std::move(other)); } return *this; } ~managed_vector() { clear_and_release(); } T& at(size_type pos) { if (pos >= _size) { throw std::out_of_range("out of range"); } return operator[](pos); } const T& at(size_type pos) const { if (pos >= _size) { throw std::out_of_range("out of range"); } return operator[](pos); } T& operator[](size_type pos) noexcept { return _data[pos]; } const T& operator[](size_type pos) const noexcept { return _data[pos]; } T& front() noexcept { return *_data; } const T& front() const noexcept { return *_data; } T& back() noexcept { return _data[_size - 1]; } const T& back() const noexcept { return _data[_size - 1]; } T* data() noexcept { return _data; } const T* data() const noexcept { return _data; } iterator begin() noexcept { return _data; } const_iterator begin() const noexcept { return _data; } const_iterator cbegin() const noexcept { return _data; } iterator end() noexcept { return _data + _size; } const_iterator end() const noexcept { return _data + _size; } const_iterator cend() const noexcept { return _data + _size; } bool empty() const noexcept { return !_size; } size_type size() const noexcept { return _size; } size_type capacity() const noexcept { return _capacity; } void clear() { while (_size) { pop_back(); } } void reserve(size_type new_capacity) { if (new_capacity <= _capacity) { return; } auto ptr = current_allocator().alloc(standard_migrator<external>, sizeof(external) + sizeof(T) * new_capacity, alignof(external)); auto ext = static_cast<external*>(ptr); ext->_backref = this; T* data_ptr = ext->_data; for (unsigned i = 0; i < _size; i++) { new (data_ptr + i) T(std::move(_data[i])); _data[i].~T(); } if (is_external()) { current_allocator().free(get_external()); } _data = data_ptr; _capacity = new_capacity; } iterator erase(iterator it) { std::move(it + 1, end(), it); _data[_size - 1].~T(); _size--; return it; } void push_back(const T& value) { emplace_back(value); } void push_back(T&& value) { emplace_back(std::move(value)); } template<typename... Args> void emplace_back(Args&&... args) { maybe_grow(_size + 1); new (_data + _size) T(std::forward<Args>(args)...); _size++; } void pop_back() { _data[_size - 1].~T(); _size--; } void resize(size_type new_size) { maybe_grow(new_size); while (_size > new_size) { pop_back(); } while (_size < new_size) { emplace_back(); } } void resize(size_type new_size, const T& value) { maybe_grow(new_size); while (_size > new_size) { pop_back(); } while (_size < new_size) { push_back(value); } } };
/* * Copyright 2017 Stanislav Pidhorskyi. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ /* * This example demonstrates: * - Usage of Perez sky model [1] to render a dynamic sky. * - Rendering a mesh with a lightmap, shading of which is driven by the same parameters as the sky. * * Typically, the sky is rendered using cubemaps or other environment maps. * This approach can provide a high-quality sky, but the downside is that the * image is static. To achieve daytime changes in sky appearance, there is a need * in a dynamic model. * * Perez "An All-Weather Model for Sky Luminance Distribution" is a simple, * but good enough model which is, in essence, a function that * interpolates a sky color. As input, it requires several turbidity * coefficients, a color at zenith and direction to the sun. * Turbidity coefficients are taken from [2], which are computed using more * complex physically based models. Color at zenith depends on daytime and can * vary depending on many factors. * * In the code below, there are two tables that contain sky and sun luminance * which were computed using code from [3]. Luminance in those tables * represents actual scale of light energy that comes from sun compared to * the sky. * * The sky is driven by luminance of the sky, while the material of the * landscape is driven by both, the luminance of the sky and the sun. The * lightening model is very simple and consists of two parts: directional * light and hemisphere light. The first is used for the sun while the second * is used for the sky. Additionally, the second part is modulated by a * lightmap to achieve ambient occlusion effect. * * * References * ========== * [1] R. Perez, R. Seals, and J. Michalsky."An All-Weather Model for Sky Luminance Distribution". * Solar Energy, Volume 50, Number 3 (March 1993), pp. 235–245. * [2] A. J. Preetham, Peter Shirley, and Brian Smits. "A Practical Analytic Model for Daylight", * Proceedings of the 26th Annual Conference on Computer Graphics and Interactive Techniques, 1999, pp. 91–100. * [3] E. Lengyel, Game Engine Gems, Volume One. Jones & Bartlett Learning, 2010. pp. 219 - 234 * */ #include "common.h" #include "bgfx_utils.h" #include "imgui/imgui.h" #include "camera.h" #include "bounds.h" #include <map> namespace { // Represents color. Color-space depends on context. // In the code below, used to represent color in XYZ, and RGB color-space union Color { struct { float X; float Y; float Z; }; struct { float r; float g; float b; }; float data[3]; }; // HDTV rec. 709 matrix. static float M_XYZ2RGB[] = { 3.240479f, -0.969256f, 0.055648f, -1.53715f, 1.875991f, -0.204043f, -0.49853f, 0.041556f, 1.057311f }; // Converts color repesentation from CIE XYZ to RGB color-space. Color XYZToRGB(const Color& xyz) { Color rgb; rgb.r = M_XYZ2RGB[0] * xyz.X + M_XYZ2RGB[3] * xyz.Y + M_XYZ2RGB[6] * xyz.Z; rgb.g = M_XYZ2RGB[1] * xyz.X + M_XYZ2RGB[4] * xyz.Y + M_XYZ2RGB[7] * xyz.Z; rgb.b = M_XYZ2RGB[2] * xyz.X + M_XYZ2RGB[5] * xyz.Y + M_XYZ2RGB[8] * xyz.Z; return rgb; }; // Precomputed luminance of sunlight in XYZ colorspace. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model. // This table is used for piecewise linear interpolation. Transitions from and to 0.0 at sunset and sunrise are highly inaccurate static std::map<float, Color> sunLuminanceXYZTable = { { 5.0f, {{ 0.000000f, 0.000000f, 0.000000f }} }, { 7.0f, {{ 12.703322f, 12.989393f, 9.100411f }} }, { 8.0f, {{ 13.202644f, 13.597814f, 11.524929f }} }, { 9.0f, {{ 13.192974f, 13.597458f, 12.264488f }} }, { 10.0f, {{ 13.132943f, 13.535914f, 12.560032f }} }, { 11.0f, {{ 13.088722f, 13.489535f, 12.692996f }} }, { 12.0f, {{ 13.067827f, 13.467483f, 12.745179f }} }, { 13.0f, {{ 13.069653f, 13.469413f, 12.740822f }} }, { 14.0f, {{ 13.094319f, 13.495428f, 12.678066f }} }, { 15.0f, {{ 13.142133f, 13.545483f, 12.526785f }} }, { 16.0f, {{ 13.201734f, 13.606017f, 12.188001f }} }, { 17.0f, {{ 13.182774f, 13.572725f, 11.311157f }} }, { 18.0f, {{ 12.448635f, 12.672520f, 8.267771f }} }, { 20.0f, {{ 0.000000f, 0.000000f, 0.000000f }} } }; // Precomputed luminance of sky in the zenith point in XYZ colorspace. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model. // This table is used for piecewise linear interpolation. Day/night transitions are highly inaccurate. // The scale of luminance change in Day/night transitions is not preserved. // Luminance at night was increased to eliminate need the of HDR render. static std::map<float, Color> skyLuminanceXYZTable = { { 0.0f, {{ 0.308f, 0.308f, 0.411f }} }, { 1.0f, {{ 0.308f, 0.308f, 0.410f }} }, { 2.0f, {{ 0.301f, 0.301f, 0.402f }} }, { 3.0f, {{ 0.287f, 0.287f, 0.382f }} }, { 4.0f, {{ 0.258f, 0.258f, 0.344f }} }, { 5.0f, {{ 0.258f, 0.258f, 0.344f }} }, { 7.0f, {{ 0.962851f, 1.000000f, 1.747835f }} }, { 8.0f, {{ 0.967787f, 1.000000f, 1.776762f }} }, { 9.0f, {{ 0.970173f, 1.000000f, 1.788413f }} }, { 10.0f, {{ 0.971431f, 1.000000f, 1.794102f }} }, { 11.0f, {{ 0.972099f, 1.000000f, 1.797096f }} }, { 12.0f, {{ 0.972385f, 1.000000f, 1.798389f }} }, { 13.0f, {{ 0.972361f, 1.000000f, 1.798278f }} }, { 14.0f, {{ 0.972020f, 1.000000f, 1.796740f }} }, { 15.0f, {{ 0.971275f, 1.000000f, 1.793407f }} }, { 16.0f, {{ 0.969885f, 1.000000f, 1.787078f }} }, { 17.0f, {{ 0.967216f, 1.000000f, 1.773758f }} }, { 18.0f, {{ 0.961668f, 1.000000f, 1.739891f }} }, { 20.0f, {{ 0.264f, 0.264f, 0.352f }} }, { 21.0f, {{ 0.264f, 0.264f, 0.352f }} }, { 22.0f, {{ 0.290f, 0.290f, 0.386f }} }, { 23.0f, {{ 0.303f, 0.303f, 0.404f }} } }; // Turbidity tables. Taken from: // A. J. Preetham, P. Shirley, and B. Smits. A Practical Analytic Model for Daylight. SIGGRAPH ’99 // Coefficients correspond to xyY colorspace. static Color ABCDE[] = { {{ -0.2592f, -0.2608f, -1.4630f }}, {{ 0.0008f, 0.0092f, 0.4275f }}, {{ 0.2125f, 0.2102f, 5.3251f }}, {{ -0.8989f, -1.6537f, -2.5771f }}, {{ 0.0452f, 0.0529f, 0.3703f }} }; static Color ABCDE_t[] = { {{ -0.0193f, -0.0167f, 0.1787f }}, {{ -0.0665f, -0.0950f, -0.3554f }}, {{ -0.0004f, -0.0079f, -0.0227f }}, {{ -0.0641f, -0.0441f, 0.1206f }}, {{ -0.0033f, -0.0109f, -0.0670f }} }; // Performs piecewise linear interpolation of a Color parameter. class DynamicValueController { typedef Color ValueType; typedef std::map<float, ValueType> KeyMap; public: DynamicValueController() {}; ~DynamicValueController() {}; void SetMap(const KeyMap& keymap) { m_keyMap = keymap; } ValueType GetValue(float time) const { typename KeyMap::const_iterator itUpper = m_keyMap.upper_bound(time + 1e-6f); typename KeyMap::const_iterator itLower = itUpper; --itLower; if (itLower == m_keyMap.end()) { return itUpper->second; } if (itUpper == m_keyMap.end()) { return itLower->second; } float lowerTime = itLower->first; const ValueType& lowerVal = itLower->second; float upperTime = itUpper->first; const ValueType& upperVal = itUpper->second; if (lowerTime == upperTime) { return lowerVal; } return interpolate(lowerTime, lowerVal, upperTime, upperVal, time); }; void Clear() { m_keyMap.clear(); }; private: const ValueType interpolate(float lowerTime, const ValueType& lowerVal, float upperTime, const ValueType& upperVal, float time) const { float x = (time - lowerTime) / (upperTime - lowerTime); ValueType result; bx::vec3Lerp(result.data, lowerVal.data, upperVal.data, x); return result; }; KeyMap m_keyMap; }; // Controls sun position according to time, month, and observer's latitude. // Sun position computation based on Earth's orbital elements: https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html class SunController { public: enum Month : int { January = 0, February, March, April, May, June, July, August, September, October, November, December }; SunController(): m_latitude(50.0f), m_month(June), m_eclipticObliquity(bx::toRad(23.4f)), m_delta(0.0f) { m_northDirection[0] = 1.0; m_northDirection[1] = 0.0; m_northDirection[2] = 0.0; m_upvector[0] = 0.0f; m_upvector[1] = 1.0f; m_upvector[2] = 0.0f; } void Update(float time) { CalculateSunOrbit(); UpdateSunPosition(time - 12.0f); } float m_northDirection[3]; float m_sunDirection[4]; float m_upvector[3]; float m_latitude; Month m_month; private: void CalculateSunOrbit() { float day = 30.0f * m_month + 15.0f; float lambda = 280.46f + 0.9856474f * day; lambda = bx::toRad(lambda); m_delta = bx::fasin(bx::fsin(m_eclipticObliquity) * bx::fsin(lambda)); } void UpdateSunPosition(float hour) { float latitude = bx::toRad(m_latitude); float h = hour * bx::kPi / 12.0f; float azimuth = bx::fatan2( bx::fsin(h), bx::fcos(h) * bx::fsin(latitude) - bx::ftan(m_delta) * bx::fcos(latitude) ); float altitude = bx::fasin( bx::fsin(latitude) * bx::fsin(m_delta) + bx::fcos(latitude) * bx::fcos(m_delta) * bx::fcos(h) ); float rotation[4]; bx::quatRotateAxis(rotation, m_upvector, -azimuth); float direction[3]; bx::vec3MulQuat(direction, m_northDirection, rotation); float v[3]; bx::vec3Cross(v, m_upvector, direction); bx::quatRotateAxis(rotation, v, altitude); bx::vec3MulQuat(m_sunDirection, direction, rotation); } float m_eclipticObliquity; float m_delta; }; struct ScreenPosVertex { float m_x; float m_y; static void init() { ms_decl .begin() .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float) .end(); } static bgfx::VertexDecl ms_decl; }; bgfx::VertexDecl ScreenPosVertex::ms_decl; // Renders a screen-space grid of triangles. // Because of performance reasons, and because sky color is smooth, sky color is computed in vertex shader. // 32x32 is a reasonable size for the grid to have smooth enough colors. struct ProceduralSky { void init(int verticalCount, int horizontalCount) { // Create vertex stream declaration. ScreenPosVertex::init(); m_skyProgram = loadProgram("vs_sky", "fs_sky"); m_skyProgram_colorBandingFix = loadProgram("vs_sky", "fs_sky_color_banding_fix"); m_preventBanding = true; bx::AllocatorI* allocator = entry::getAllocator(); ScreenPosVertex* vertices = (ScreenPosVertex*)BX_ALLOC(allocator , verticalCount * horizontalCount * sizeof(ScreenPosVertex) ); for (int i = 0; i < verticalCount; i++) { for (int j = 0; j < horizontalCount; j++) { ScreenPosVertex& v = vertices[i * verticalCount + j]; v.m_x = float(j) / (horizontalCount - 1) * 2.0f - 1.0f; v.m_y = float(i) / (verticalCount - 1) * 2.0f - 1.0f; } } uint16_t* indices = (uint16_t*)BX_ALLOC(allocator , (verticalCount - 1) * (horizontalCount - 1) * 6 * sizeof(uint16_t) ); int k = 0; for (int i = 0; i < verticalCount - 1; i++) { for (int j = 0; j < horizontalCount - 1; j++) { indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 0)); indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0)); indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1)); indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0)); indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 1)); indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1)); } } m_vbh = bgfx::createVertexBuffer(bgfx::copy(vertices, sizeof(ScreenPosVertex) * verticalCount * horizontalCount), ScreenPosVertex::ms_decl); m_ibh = bgfx::createIndexBuffer(bgfx::copy(indices, sizeof(uint16_t) * k)); BX_FREE(allocator, indices); BX_FREE(allocator, vertices); } void shutdown() { bgfx::destroy(m_ibh); bgfx::destroy(m_vbh); bgfx::destroy(m_skyProgram); bgfx::destroy(m_skyProgram_colorBandingFix); } void draw() { bgfx::setState(BGFX_STATE_RGB_WRITE | BGFX_STATE_DEPTH_TEST_EQUAL); bgfx::setIndexBuffer(m_ibh); bgfx::setVertexBuffer(0, m_vbh); bgfx::submit(0, m_preventBanding ? m_skyProgram_colorBandingFix : m_skyProgram); } bgfx::VertexBufferHandle m_vbh; bgfx::IndexBufferHandle m_ibh; bgfx::ProgramHandle m_skyProgram; bgfx::ProgramHandle m_skyProgram_colorBandingFix; bool m_preventBanding; }; class ExampleProceduralSky : public entry::AppI { public: ExampleProceduralSky(const char* _name, const char* _description): entry::AppI(_name, _description) {} void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_NONE; m_reset = BGFX_RESET_VSYNC; bgfx::init(args.m_type, args.m_pciId); bgfx::reset(m_width, m_height, m_reset); // Enable m_debug text. bgfx::setDebug(m_debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH , 0x000000ff , 1.0f , 0 ); m_sunLuminanceXYZ.SetMap(sunLuminanceXYZTable); m_skyLuminanceXYZ.SetMap(skyLuminanceXYZTable); m_mesh = meshLoad("meshes/test_scene.bin"); m_lightmapTexture = loadTexture("textures/lightmap.ktx"); // Imgui. imguiCreate(); m_timeOffset = bx::getHPCounter(); m_time = 0.0f; s_texLightmap = bgfx::createUniform("s_texLightmap", bgfx::UniformType::Int1); u_sunLuminance = bgfx::createUniform("u_sunLuminance", bgfx::UniformType::Vec4); u_skyLuminanceXYZ = bgfx::createUniform("u_skyLuminanceXYZ", bgfx::UniformType::Vec4); u_skyLuminance = bgfx::createUniform("u_skyLuminance", bgfx::UniformType::Vec4); u_sunDirection = bgfx::createUniform("u_sunDirection", bgfx::UniformType::Vec4); u_parameters = bgfx::createUniform("u_parameters", bgfx::UniformType::Vec4); u_perezCoeff = bgfx::createUniform("u_perezCoeff", bgfx::UniformType::Vec4, 5); m_landscapeProgram = loadProgram("vs_sky_landscape", "fs_sky_landscape"); m_sky.init(32, 32); m_sun.Update(0); cameraCreate(); const float initialPos[3] = { 5.0f, 3.0, 0.0f }; cameraSetPosition(initialPos); cameraSetVerticalAngle(bx::kPi / 8.0f); cameraSetHorizontalAngle(-bx::kPi / 3.0f); m_turbidity = 2.15f; } virtual int shutdown() override { // Cleanup. cameraDestroy(); imguiDestroy(); meshUnload(m_mesh); m_sky.shutdown(); bgfx::destroy(s_texLightmap); bgfx::destroy(u_sunLuminance); bgfx::destroy(u_skyLuminanceXYZ); bgfx::destroy(u_skyLuminance); bgfx::destroy(u_sunDirection); bgfx::destroy(u_parameters); bgfx::destroy(u_perezCoeff); bgfx::destroy(m_lightmapTexture); bgfx::destroy(m_landscapeProgram); bgfx::frame(); // Shutdown bgfx. bgfx::shutdown(); return 0; } void imgui() { ImGui::Begin("ProceduralSky"); ImGui::SetWindowSize(ImVec2(350, 200)); ImGui::SliderFloat("Time", &m_time, 0.0f, 24.0f); ImGui::SliderFloat("Latitude", &m_sun.m_latitude, -90.0f, 90.0f); ImGui::SliderFloat("Turbidity", &m_turbidity, 1.9f, 10.0f); ImGui::Checkbox("Prevent color banding", &m_sky.m_preventBanding); const char* items[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; ImGui::Combo("Month", (int*)&m_sun.m_month, items, 12); ImGui::End(); } bool update() override { if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState)) { int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency()); const float deltaTime = float(frameTime / freq); m_time += deltaTime; m_time = bx::fmod(m_time, 24.0f); m_sun.Update(m_time); imguiBeginFrame(m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this); ImGui::SetNextWindowPos( ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f) , ImGuiSetCond_FirstUseEver ); imgui(); imguiEndFrame(); if (!ImGui::MouseOverArea()) { // Update camera. cameraUpdate(deltaTime, m_mouseState); } // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height)); float view[16]; cameraGetViewMtx(view); float proj[16]; bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 2000.0f, bgfx::getCaps()->homogeneousDepth); bgfx::setViewTransform(0, view, proj); Color sunLuminanceXYZ = m_sunLuminanceXYZ.GetValue(m_time); Color sunLuminanceRGB = XYZToRGB(sunLuminanceXYZ); Color skyLuminanceXYZ = m_skyLuminanceXYZ.GetValue(m_time); Color skyLuminanceRGB = XYZToRGB(skyLuminanceXYZ); bgfx::setUniform(u_sunLuminance, sunLuminanceRGB.data); bgfx::setUniform(u_skyLuminanceXYZ, skyLuminanceXYZ.data); bgfx::setUniform(u_skyLuminance, skyLuminanceRGB.data); bgfx::setUniform(u_sunDirection, m_sun.m_sunDirection); float exposition[4] = { 0.02f, 3.0f, 0.1f, m_time }; bgfx::setUniform(u_parameters, exposition); float perezCoeff[4 * 5]; computePerezCoeff(m_turbidity, perezCoeff); bgfx::setUniform(u_perezCoeff, perezCoeff, 5); bgfx::setTexture(0, s_texLightmap, m_lightmapTexture); meshSubmit(m_mesh, 0, m_landscapeProgram, NULL); m_sky.draw(); bgfx::frame(); return true; } return false; } void computePerezCoeff(float turbidity, float* perezCoeff) { for (int i = 0; i < 5; ++i) { Color tmp; bx::vec3Mul(tmp.data, ABCDE_t[i].data, turbidity); bx::vec3Add(perezCoeff + 4 * i, tmp.data, ABCDE[i].data); perezCoeff[4 * i + 3] = 0.0f; } } bgfx::ProgramHandle m_landscapeProgram; bgfx::UniformHandle s_texLightmap; bgfx::TextureHandle m_lightmapTexture; bgfx::UniformHandle u_sunLuminance; bgfx::UniformHandle u_skyLuminanceXYZ; bgfx::UniformHandle u_skyLuminance; bgfx::UniformHandle u_sunDirection; bgfx::UniformHandle u_parameters; bgfx::UniformHandle u_perezCoeff; ProceduralSky m_sky; SunController m_sun; DynamicValueController m_sunLuminanceXYZ; DynamicValueController m_skyLuminanceXYZ; uint32_t m_width; uint32_t m_height; uint32_t m_debug; uint32_t m_reset; Mesh* m_mesh; entry::MouseState m_mouseState; float m_time; int64_t m_timeOffset; float m_turbidity; }; } // namespace ENTRY_IMPLEMENT_MAIN(ExampleProceduralSky, "36-sky", "Perez dynamic sky model."); 36-sky: Added time scale. /* * Copyright 2017 Stanislav Pidhorskyi. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ /* * This example demonstrates: * - Usage of Perez sky model [1] to render a dynamic sky. * - Rendering a mesh with a lightmap, shading of which is driven by the same parameters as the sky. * * Typically, the sky is rendered using cubemaps or other environment maps. * This approach can provide a high-quality sky, but the downside is that the * image is static. To achieve daytime changes in sky appearance, there is a need * in a dynamic model. * * Perez "An All-Weather Model for Sky Luminance Distribution" is a simple, * but good enough model which is, in essence, a function that * interpolates a sky color. As input, it requires several turbidity * coefficients, a color at zenith and direction to the sun. * Turbidity coefficients are taken from [2], which are computed using more * complex physically based models. Color at zenith depends on daytime and can * vary depending on many factors. * * In the code below, there are two tables that contain sky and sun luminance * which were computed using code from [3]. Luminance in those tables * represents actual scale of light energy that comes from sun compared to * the sky. * * The sky is driven by luminance of the sky, while the material of the * landscape is driven by both, the luminance of the sky and the sun. The * lightening model is very simple and consists of two parts: directional * light and hemisphere light. The first is used for the sun while the second * is used for the sky. Additionally, the second part is modulated by a * lightmap to achieve ambient occlusion effect. * * * References * ========== * [1] R. Perez, R. Seals, and J. Michalsky."An All-Weather Model for Sky Luminance Distribution". * Solar Energy, Volume 50, Number 3 (March 1993), pp. 235–245. * [2] A. J. Preetham, Peter Shirley, and Brian Smits. "A Practical Analytic Model for Daylight", * Proceedings of the 26th Annual Conference on Computer Graphics and Interactive Techniques, 1999, pp. 91–100. * [3] E. Lengyel, Game Engine Gems, Volume One. Jones & Bartlett Learning, 2010. pp. 219 - 234 * */ #include "common.h" #include "bgfx_utils.h" #include "imgui/imgui.h" #include "camera.h" #include "bounds.h" #include <map> namespace { // Represents color. Color-space depends on context. // In the code below, used to represent color in XYZ, and RGB color-space union Color { struct { float X; float Y; float Z; }; struct { float r; float g; float b; }; float data[3]; }; // HDTV rec. 709 matrix. static float M_XYZ2RGB[] = { 3.240479f, -0.969256f, 0.055648f, -1.53715f, 1.875991f, -0.204043f, -0.49853f, 0.041556f, 1.057311f }; // Converts color repesentation from CIE XYZ to RGB color-space. Color XYZToRGB(const Color& xyz) { Color rgb; rgb.r = M_XYZ2RGB[0] * xyz.X + M_XYZ2RGB[3] * xyz.Y + M_XYZ2RGB[6] * xyz.Z; rgb.g = M_XYZ2RGB[1] * xyz.X + M_XYZ2RGB[4] * xyz.Y + M_XYZ2RGB[7] * xyz.Z; rgb.b = M_XYZ2RGB[2] * xyz.X + M_XYZ2RGB[5] * xyz.Y + M_XYZ2RGB[8] * xyz.Z; return rgb; }; // Precomputed luminance of sunlight in XYZ colorspace. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model. // This table is used for piecewise linear interpolation. Transitions from and to 0.0 at sunset and sunrise are highly inaccurate static std::map<float, Color> sunLuminanceXYZTable = { { 5.0f, {{ 0.000000f, 0.000000f, 0.000000f }} }, { 7.0f, {{ 12.703322f, 12.989393f, 9.100411f }} }, { 8.0f, {{ 13.202644f, 13.597814f, 11.524929f }} }, { 9.0f, {{ 13.192974f, 13.597458f, 12.264488f }} }, { 10.0f, {{ 13.132943f, 13.535914f, 12.560032f }} }, { 11.0f, {{ 13.088722f, 13.489535f, 12.692996f }} }, { 12.0f, {{ 13.067827f, 13.467483f, 12.745179f }} }, { 13.0f, {{ 13.069653f, 13.469413f, 12.740822f }} }, { 14.0f, {{ 13.094319f, 13.495428f, 12.678066f }} }, { 15.0f, {{ 13.142133f, 13.545483f, 12.526785f }} }, { 16.0f, {{ 13.201734f, 13.606017f, 12.188001f }} }, { 17.0f, {{ 13.182774f, 13.572725f, 11.311157f }} }, { 18.0f, {{ 12.448635f, 12.672520f, 8.267771f }} }, { 20.0f, {{ 0.000000f, 0.000000f, 0.000000f }} } }; // Precomputed luminance of sky in the zenith point in XYZ colorspace. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model. // This table is used for piecewise linear interpolation. Day/night transitions are highly inaccurate. // The scale of luminance change in Day/night transitions is not preserved. // Luminance at night was increased to eliminate need the of HDR render. static std::map<float, Color> skyLuminanceXYZTable = { { 0.0f, {{ 0.308f, 0.308f, 0.411f }} }, { 1.0f, {{ 0.308f, 0.308f, 0.410f }} }, { 2.0f, {{ 0.301f, 0.301f, 0.402f }} }, { 3.0f, {{ 0.287f, 0.287f, 0.382f }} }, { 4.0f, {{ 0.258f, 0.258f, 0.344f }} }, { 5.0f, {{ 0.258f, 0.258f, 0.344f }} }, { 7.0f, {{ 0.962851f, 1.000000f, 1.747835f }} }, { 8.0f, {{ 0.967787f, 1.000000f, 1.776762f }} }, { 9.0f, {{ 0.970173f, 1.000000f, 1.788413f }} }, { 10.0f, {{ 0.971431f, 1.000000f, 1.794102f }} }, { 11.0f, {{ 0.972099f, 1.000000f, 1.797096f }} }, { 12.0f, {{ 0.972385f, 1.000000f, 1.798389f }} }, { 13.0f, {{ 0.972361f, 1.000000f, 1.798278f }} }, { 14.0f, {{ 0.972020f, 1.000000f, 1.796740f }} }, { 15.0f, {{ 0.971275f, 1.000000f, 1.793407f }} }, { 16.0f, {{ 0.969885f, 1.000000f, 1.787078f }} }, { 17.0f, {{ 0.967216f, 1.000000f, 1.773758f }} }, { 18.0f, {{ 0.961668f, 1.000000f, 1.739891f }} }, { 20.0f, {{ 0.264f, 0.264f, 0.352f }} }, { 21.0f, {{ 0.264f, 0.264f, 0.352f }} }, { 22.0f, {{ 0.290f, 0.290f, 0.386f }} }, { 23.0f, {{ 0.303f, 0.303f, 0.404f }} } }; // Turbidity tables. Taken from: // A. J. Preetham, P. Shirley, and B. Smits. A Practical Analytic Model for Daylight. SIGGRAPH ’99 // Coefficients correspond to xyY colorspace. static Color ABCDE[] = { {{ -0.2592f, -0.2608f, -1.4630f }}, {{ 0.0008f, 0.0092f, 0.4275f }}, {{ 0.2125f, 0.2102f, 5.3251f }}, {{ -0.8989f, -1.6537f, -2.5771f }}, {{ 0.0452f, 0.0529f, 0.3703f }} }; static Color ABCDE_t[] = { {{ -0.0193f, -0.0167f, 0.1787f }}, {{ -0.0665f, -0.0950f, -0.3554f }}, {{ -0.0004f, -0.0079f, -0.0227f }}, {{ -0.0641f, -0.0441f, 0.1206f }}, {{ -0.0033f, -0.0109f, -0.0670f }} }; // Performs piecewise linear interpolation of a Color parameter. class DynamicValueController { typedef Color ValueType; typedef std::map<float, ValueType> KeyMap; public: DynamicValueController() {}; ~DynamicValueController() {}; void SetMap(const KeyMap& keymap) { m_keyMap = keymap; } ValueType GetValue(float time) const { typename KeyMap::const_iterator itUpper = m_keyMap.upper_bound(time + 1e-6f); typename KeyMap::const_iterator itLower = itUpper; --itLower; if (itLower == m_keyMap.end()) { return itUpper->second; } if (itUpper == m_keyMap.end()) { return itLower->second; } float lowerTime = itLower->first; const ValueType& lowerVal = itLower->second; float upperTime = itUpper->first; const ValueType& upperVal = itUpper->second; if (lowerTime == upperTime) { return lowerVal; } return interpolate(lowerTime, lowerVal, upperTime, upperVal, time); }; void Clear() { m_keyMap.clear(); }; private: const ValueType interpolate(float lowerTime, const ValueType& lowerVal, float upperTime, const ValueType& upperVal, float time) const { float x = (time - lowerTime) / (upperTime - lowerTime); ValueType result; bx::vec3Lerp(result.data, lowerVal.data, upperVal.data, x); return result; }; KeyMap m_keyMap; }; // Controls sun position according to time, month, and observer's latitude. // Sun position computation based on Earth's orbital elements: https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html class SunController { public: enum Month : int { January = 0, February, March, April, May, June, July, August, September, October, November, December }; SunController(): m_latitude(50.0f), m_month(June), m_eclipticObliquity(bx::toRad(23.4f)), m_delta(0.0f) { m_northDirection[0] = 1.0; m_northDirection[1] = 0.0; m_northDirection[2] = 0.0; m_upvector[0] = 0.0f; m_upvector[1] = 1.0f; m_upvector[2] = 0.0f; } void Update(float time) { CalculateSunOrbit(); UpdateSunPosition(time - 12.0f); } float m_northDirection[3]; float m_sunDirection[4]; float m_upvector[3]; float m_latitude; Month m_month; private: void CalculateSunOrbit() { float day = 30.0f * m_month + 15.0f; float lambda = 280.46f + 0.9856474f * day; lambda = bx::toRad(lambda); m_delta = bx::fasin(bx::fsin(m_eclipticObliquity) * bx::fsin(lambda)); } void UpdateSunPosition(float hour) { float latitude = bx::toRad(m_latitude); float h = hour * bx::kPi / 12.0f; float azimuth = bx::fatan2( bx::fsin(h), bx::fcos(h) * bx::fsin(latitude) - bx::ftan(m_delta) * bx::fcos(latitude) ); float altitude = bx::fasin( bx::fsin(latitude) * bx::fsin(m_delta) + bx::fcos(latitude) * bx::fcos(m_delta) * bx::fcos(h) ); float rotation[4]; bx::quatRotateAxis(rotation, m_upvector, -azimuth); float direction[3]; bx::vec3MulQuat(direction, m_northDirection, rotation); float v[3]; bx::vec3Cross(v, m_upvector, direction); bx::quatRotateAxis(rotation, v, altitude); bx::vec3MulQuat(m_sunDirection, direction, rotation); } float m_eclipticObliquity; float m_delta; }; struct ScreenPosVertex { float m_x; float m_y; static void init() { ms_decl .begin() .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float) .end(); } static bgfx::VertexDecl ms_decl; }; bgfx::VertexDecl ScreenPosVertex::ms_decl; // Renders a screen-space grid of triangles. // Because of performance reasons, and because sky color is smooth, sky color is computed in vertex shader. // 32x32 is a reasonable size for the grid to have smooth enough colors. struct ProceduralSky { void init(int verticalCount, int horizontalCount) { // Create vertex stream declaration. ScreenPosVertex::init(); m_skyProgram = loadProgram("vs_sky", "fs_sky"); m_skyProgram_colorBandingFix = loadProgram("vs_sky", "fs_sky_color_banding_fix"); m_preventBanding = true; bx::AllocatorI* allocator = entry::getAllocator(); ScreenPosVertex* vertices = (ScreenPosVertex*)BX_ALLOC(allocator , verticalCount * horizontalCount * sizeof(ScreenPosVertex) ); for (int i = 0; i < verticalCount; i++) { for (int j = 0; j < horizontalCount; j++) { ScreenPosVertex& v = vertices[i * verticalCount + j]; v.m_x = float(j) / (horizontalCount - 1) * 2.0f - 1.0f; v.m_y = float(i) / (verticalCount - 1) * 2.0f - 1.0f; } } uint16_t* indices = (uint16_t*)BX_ALLOC(allocator , (verticalCount - 1) * (horizontalCount - 1) * 6 * sizeof(uint16_t) ); int k = 0; for (int i = 0; i < verticalCount - 1; i++) { for (int j = 0; j < horizontalCount - 1; j++) { indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 0)); indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0)); indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1)); indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0)); indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 1)); indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1)); } } m_vbh = bgfx::createVertexBuffer(bgfx::copy(vertices, sizeof(ScreenPosVertex) * verticalCount * horizontalCount), ScreenPosVertex::ms_decl); m_ibh = bgfx::createIndexBuffer(bgfx::copy(indices, sizeof(uint16_t) * k)); BX_FREE(allocator, indices); BX_FREE(allocator, vertices); } void shutdown() { bgfx::destroy(m_ibh); bgfx::destroy(m_vbh); bgfx::destroy(m_skyProgram); bgfx::destroy(m_skyProgram_colorBandingFix); } void draw() { bgfx::setState(BGFX_STATE_RGB_WRITE | BGFX_STATE_DEPTH_TEST_EQUAL); bgfx::setIndexBuffer(m_ibh); bgfx::setVertexBuffer(0, m_vbh); bgfx::submit(0, m_preventBanding ? m_skyProgram_colorBandingFix : m_skyProgram); } bgfx::VertexBufferHandle m_vbh; bgfx::IndexBufferHandle m_ibh; bgfx::ProgramHandle m_skyProgram; bgfx::ProgramHandle m_skyProgram_colorBandingFix; bool m_preventBanding; }; class ExampleProceduralSky : public entry::AppI { public: ExampleProceduralSky(const char* _name, const char* _description): entry::AppI(_name, _description) {} void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_NONE; m_reset = BGFX_RESET_VSYNC; bgfx::init(args.m_type, args.m_pciId); bgfx::reset(m_width, m_height, m_reset); // Enable m_debug text. bgfx::setDebug(m_debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH , 0x000000ff , 1.0f , 0 ); m_sunLuminanceXYZ.SetMap(sunLuminanceXYZTable); m_skyLuminanceXYZ.SetMap(skyLuminanceXYZTable); m_mesh = meshLoad("meshes/test_scene.bin"); m_lightmapTexture = loadTexture("textures/lightmap.ktx"); // Imgui. imguiCreate(); m_timeOffset = bx::getHPCounter(); m_time = 0.0f; m_timeScale = 1.0f; s_texLightmap = bgfx::createUniform("s_texLightmap", bgfx::UniformType::Int1); u_sunLuminance = bgfx::createUniform("u_sunLuminance", bgfx::UniformType::Vec4); u_skyLuminanceXYZ = bgfx::createUniform("u_skyLuminanceXYZ", bgfx::UniformType::Vec4); u_skyLuminance = bgfx::createUniform("u_skyLuminance", bgfx::UniformType::Vec4); u_sunDirection = bgfx::createUniform("u_sunDirection", bgfx::UniformType::Vec4); u_parameters = bgfx::createUniform("u_parameters", bgfx::UniformType::Vec4); u_perezCoeff = bgfx::createUniform("u_perezCoeff", bgfx::UniformType::Vec4, 5); m_landscapeProgram = loadProgram("vs_sky_landscape", "fs_sky_landscape"); m_sky.init(32, 32); m_sun.Update(0); cameraCreate(); const float initialPos[3] = { 5.0f, 3.0, 0.0f }; cameraSetPosition(initialPos); cameraSetVerticalAngle(bx::kPi / 8.0f); cameraSetHorizontalAngle(-bx::kPi / 3.0f); m_turbidity = 2.15f; } virtual int shutdown() override { // Cleanup. cameraDestroy(); imguiDestroy(); meshUnload(m_mesh); m_sky.shutdown(); bgfx::destroy(s_texLightmap); bgfx::destroy(u_sunLuminance); bgfx::destroy(u_skyLuminanceXYZ); bgfx::destroy(u_skyLuminance); bgfx::destroy(u_sunDirection); bgfx::destroy(u_parameters); bgfx::destroy(u_perezCoeff); bgfx::destroy(m_lightmapTexture); bgfx::destroy(m_landscapeProgram); bgfx::frame(); // Shutdown bgfx. bgfx::shutdown(); return 0; } void imgui(uint32_t _width) { ImGui::Begin("ProceduralSky"); ImGui::SetWindowSize(ImVec2(float(_width), 200.0f) ); ImGui::SliderFloat("Time scale", &m_timeScale, 0.0f, 1.0f); ImGui::SliderFloat("Time", &m_time, 0.0f, 24.0f); ImGui::SliderFloat("Latitude", &m_sun.m_latitude, -90.0f, 90.0f); ImGui::SliderFloat("Turbidity", &m_turbidity, 1.9f, 10.0f); ImGui::Checkbox("Prevent color banding", &m_sky.m_preventBanding); const char* items[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; ImGui::Combo("Month", (int*)&m_sun.m_month, items, 12); ImGui::End(); } bool update() override { if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState)) { int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency()); const float deltaTime = float(frameTime / freq); m_time += m_timeScale * deltaTime; m_time = bx::fmod(m_time, 24.0f); m_sun.Update(m_time); imguiBeginFrame(m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this); ImGui::SetNextWindowPos( ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f) , ImGuiSetCond_FirstUseEver ); imgui(m_width / 5.0f - 10.0f); imguiEndFrame(); if (!ImGui::MouseOverArea()) { // Update camera. cameraUpdate(deltaTime, m_mouseState); } // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height)); float view[16]; cameraGetViewMtx(view); float proj[16]; bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 2000.0f, bgfx::getCaps()->homogeneousDepth); bgfx::setViewTransform(0, view, proj); Color sunLuminanceXYZ = m_sunLuminanceXYZ.GetValue(m_time); Color sunLuminanceRGB = XYZToRGB(sunLuminanceXYZ); Color skyLuminanceXYZ = m_skyLuminanceXYZ.GetValue(m_time); Color skyLuminanceRGB = XYZToRGB(skyLuminanceXYZ); bgfx::setUniform(u_sunLuminance, sunLuminanceRGB.data); bgfx::setUniform(u_skyLuminanceXYZ, skyLuminanceXYZ.data); bgfx::setUniform(u_skyLuminance, skyLuminanceRGB.data); bgfx::setUniform(u_sunDirection, m_sun.m_sunDirection); float exposition[4] = { 0.02f, 3.0f, 0.1f, m_time }; bgfx::setUniform(u_parameters, exposition); float perezCoeff[4 * 5]; computePerezCoeff(m_turbidity, perezCoeff); bgfx::setUniform(u_perezCoeff, perezCoeff, 5); bgfx::setTexture(0, s_texLightmap, m_lightmapTexture); meshSubmit(m_mesh, 0, m_landscapeProgram, NULL); m_sky.draw(); bgfx::frame(); return true; } return false; } void computePerezCoeff(float turbidity, float* perezCoeff) { for (int i = 0; i < 5; ++i) { Color tmp; bx::vec3Mul(tmp.data, ABCDE_t[i].data, turbidity); bx::vec3Add(perezCoeff + 4 * i, tmp.data, ABCDE[i].data); perezCoeff[4 * i + 3] = 0.0f; } } bgfx::ProgramHandle m_landscapeProgram; bgfx::UniformHandle s_texLightmap; bgfx::TextureHandle m_lightmapTexture; bgfx::UniformHandle u_sunLuminance; bgfx::UniformHandle u_skyLuminanceXYZ; bgfx::UniformHandle u_skyLuminance; bgfx::UniformHandle u_sunDirection; bgfx::UniformHandle u_parameters; bgfx::UniformHandle u_perezCoeff; ProceduralSky m_sky; SunController m_sun; DynamicValueController m_sunLuminanceXYZ; DynamicValueController m_skyLuminanceXYZ; uint32_t m_width; uint32_t m_height; uint32_t m_debug; uint32_t m_reset; Mesh* m_mesh; entry::MouseState m_mouseState; float m_time; float m_timeScale; int64_t m_timeOffset; float m_turbidity; }; } // namespace ENTRY_IMPLEMENT_MAIN(ExampleProceduralSky, "36-sky", "Perez dynamic sky model.");
// // ofxAvVideoPlayer.cpp // emptyExample // // Created by Hansi on 13.07.15. // // a huge chunk of this file is based on the // blog entry https://blinkingblip.wordpress.com/2011/10/08/decoding-and-playing-an-audio-stream-using-libavcodec-libavformat-and-libao/ // (had to make some adjustments for changes in ffmpeg // and libavcodecs examples // https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/decoding_encoding.c #include "ofxAvVideoPlayer.h" #include "ofMain.h" #include "ofxAvUtils.h" extern "C"{ #include <libavutil/opt.h> } // for release: // #define AVL_MEASURE(x) // for debug: // #define AVL_MEASURE(x) x #define AVL_MEASURE(x) using namespace std; #define die(msg) { unload(); cerr << msg << endl; return false; } // this holds an image class ofxAvVideoData{ public: uint8_t *video_dst_data[4]; int video_dst_linesize[4]; int video_dst_bufsize; bool allocated; int64_t pts; double t; ofxAvVideoData() : allocated(false), video_dst_bufsize(0),pts(-1),t(-1){} }; class ofxAvAudioData{ public: int64_t pts; int64_t pts_native; double t; // contains audio data, always in interleaved float format int decoded_buffer_pos; int decoded_buffer_len; float decoded_buffer[AVCODEC_MAX_AUDIO_FRAME_SIZE]; ofxAvAudioData() : decoded_buffer_len(0){} }; ofxAvVideoPlayer::ofxAvVideoPlayer(){ ofxAvUtils::init(); // default audio settings output_channel_layout = av_get_default_channel_layout(2); output_sample_rate = 44100; output_num_channels = 2; output_config_changed = false; output_setup_called = false; volume = 1; isLooping = false; fmt_ctx = NULL; decoded_frame = NULL; audio_context = NULL; video_context = NULL; audio_stream = NULL; video_stream = NULL; buffer_size = AVCODEC_MAX_AUDIO_FRAME_SIZE; swr_context = NULL; sws_context = NULL; av_init_packet(&packet); unload(); } ofxAvVideoPlayer::~ofxAvVideoPlayer(){ unload(); } static int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type){ int ret, stream_index; AVStream *st; AVCodecContext *dec_ctx = NULL; AVCodec *dec = NULL; AVDictionary *opts = NULL; ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0); if (ret < 0) { fprintf(stderr, "Could not find %s stream in input file\n", av_get_media_type_string(type)); return ret; } else { stream_index = ret; st = fmt_ctx->streams[stream_index]; /* find decoder for the stream */ dec_ctx = st->codec; if( type == AVMEDIA_TYPE_VIDEO){ av_opt_set(dec_ctx->priv_data, "tune", "zerolatency", 0); dec_ctx->thread_type = FF_THREAD_SLICE | FF_THREAD_FRAME; } dec = avcodec_find_decoder(dec_ctx->codec_id); if (!dec) { fprintf(stderr, "Failed to find %s codec\n", av_get_media_type_string(type)); return AVERROR(EINVAL); } if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) { fprintf(stderr, "Failed to open %s codec\n", av_get_media_type_string(type)); return ret; } av_dict_set(&opts, "refcounted_frames", "1", 0); *stream_idx = stream_index; } return 0; } bool ofxAvVideoPlayer::load(string fileName, bool stream){ unload(); fileNameAbs = ofToDataPath(fileName,true); fileNameBase = ofFile(fileNameAbs,ofFile::Reference).getFileName(); const char * input_filename = fileNameAbs.c_str(); // the first finds the right codec, following https://blinkingblip.wordpress.com/2011/10/08/decoding-and-playing-an-audio-stream-using-libavcodec-libavformat-and-libao/ // and also demuxing_decoding.c in the ffmpeg examples // throughout all of it we are using "new api, reference counted" for memory management fmt_ctx = 0; // AVInputFormat fmt; // fmt.flags = AVFMT_SEEK_TO_PTS; if (avformat_open_input(&fmt_ctx, input_filename, NULL, NULL) < 0) { die("Could not open file"); } fmt_ctx->iformat->flags |= AVFMT_SEEK_TO_PTS; if (avformat_find_stream_info(fmt_ctx,NULL) < 0) { die("Could not find file info"); } // ---------------------------------------------- // Find video stream // ---------------------------------------------- if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) { video_stream = fmt_ctx->streams[video_stream_idx]; video_context = video_stream->codec; /* allocate image where the decoded image will be put */ // we will use the sws resampling context to fill out the data! width = video_context->width; height = video_context->height; pix_fmt = AV_PIX_FMT_RGB24; // allocate a bunch of images! // we take 1.2 times frame rate (e.g. 36 frames for a 30fps video), // and at least 30 frames to avoid big issues just in case r_frame_rate is a bit off. int numBufferedFrames = (int)ofClamp(av_q2d(video_stream->r_frame_rate)*1.4, 30.0, 70.0); ofLogError() << "[ofxAvVideoPlayer] Buffering " << numBufferedFrames << endl; for( int i = 0; i < numBufferedFrames; i++ ){ ofxAvVideoData * data = new ofxAvVideoData(); int ret = av_image_alloc(data->video_dst_data, data->video_dst_linesize, video_context->width, video_context->height, video_context->pix_fmt, 1); if (ret < 0) { die("Could not allocate raw video buffer"); } data->video_dst_bufsize = ret; video_buffers.push_back(data); } } if( video_stream_idx == -1 ){ die("Could not find a video stream"); } // ---------------------------------------------- // Find audio stream // ---------------------------------------------- audio_stream_idx = -1; if(open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0){ audio_stream = fmt_ctx->streams[audio_stream_idx]; audio_context = audio_stream->codec; } //TODO: we don't want to require an audio stream //when reading video if (audio_stream_idx == -1) { //die("Could not find an audio stream"); //nope, not a problem anymore! } // Find the apropriate codec and open it if( forceNativeAudioFormat && audio_stream_idx >= 0){ output_sample_rate = audio_context->sample_rate; output_setup_called = true; output_channel_layout = audio_context->channel_layout; if( output_channel_layout == 0 ){ output_num_channels = audio_context->channels; output_channel_layout = av_get_default_channel_layout(output_num_channels); } else{ output_num_channels = av_get_channel_layout_nb_channels( output_channel_layout ); } AVL_MEASURE(cout << "native audio thing: " << output_sample_rate << "Hz / " << output_num_channels << " channels" << endl;) } // dump info, this is interresting! av_dump_format(fmt_ctx, 0, input_filename, 0); // from here on it's mostly following // https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/decoding_encoding.c //packet.data = inbuf; //packet.size = fread(inbuf, 1, AVCODEC_AUDIO_INBUF_SIZE, f); av_init_packet(&packet); packet.data = NULL; packet.size = 0; swr_context = NULL; sws_context = NULL; fileLoaded = true; isPlaying = true; // we continue here: decode_next_frame(); //TODO: only video should be required. if( video_stream_idx >= 0){ duration = 1000*video_stream->duration*av_q2d(video_stream->time_base); } else if( audio_stream_idx >= 0 ){ duration = 1000*audio_stream->duration*av_q2d(audio_stream->time_base); } if( duration <= 0 ){ duration = 1000 * fmt_ctx->duration*av_q2d(AVRational{ 1,AV_TIME_BASE }); } if( duration <= 0 ){ unload(); return false; } next_seekTarget = 0; requestedSeek = true; decoderThread = thread(&ofxAvVideoPlayer::run_decoder, this); return true; } bool ofxAvVideoPlayer::setupAudioOut( int numChannels, int sampleRate ){ output_setup_called = true; if( numChannels != output_num_channels || sampleRate != output_sample_rate ){ output_channel_layout = av_get_default_channel_layout(numChannels); output_sample_rate = sampleRate; output_num_channels = numChannels; if( swr_context != NULL ){ output_config_changed = true; } } return true; } void ofxAvVideoPlayer::unload(){ fileNameAbs = ""; fileLoaded = false; isPlaying = false; wantsUnload = true; if( decoderThread.joinable() ){ decoderThread.join(); } wantsUnload = false; packet_data_size = 0; len = 0; last_t = 0; last_pts = 0; restart_loop = false; texturePts = -1; next_seekTarget = 0; requestedSeek = false; decoder_last_audio_pts = 0; waitForVideoDelta = 0; audio_queue_mutex.lock(); while( audio_queue.size() > 0 ){ ofxAvAudioData * data = audio_queue.front(); delete data; audio_queue.pop(); } audio_frames_available = 0; audio_queue_mutex.unlock(); video_buffers_mutex.lock(); for( ofxAvVideoData * data : video_buffers ){ av_freep(&data->video_dst_data[0]); delete data; } video_buffers_pos = 0; video_buffers.clear(); video_buffers_mutex.unlock(); next_seekTarget = -1; video_stream_idx = -1; audio_stream_idx = -1; av_free_packet(&packet); if( decoded_frame ){ //TODO: do we really need the unref here? av_frame_unref(decoded_frame); av_frame_free(&decoded_frame); decoded_frame = NULL; } if( fmt_ctx ){ avcodec_close(video_context); avcodec_close(audio_context); avformat_close_input(&fmt_ctx); avformat_free_context(fmt_ctx); av_free(fmt_ctx); fmt_ctx = NULL; audio_context = NULL; video_context = NULL; } if( swr_context ){ swr_close(swr_context); swr_free(&swr_context); swr_context = NULL; } if( sws_context ){ sws_freeContext(sws_context); sws_context = NULL; } } ofxAvVideoPlayer::AudioResult ofxAvVideoPlayer::audioOut(float *output, int bufferSize, int nChannels){ AudioResult result{0,last_pts,last_t}; if( !fileLoaded ){ return result; } if( !isPlaying ){ return result; } if( !output_setup_called ){ ofLogWarning() << "[ofxAvVideoPlayer] audioOut() called, but audio was not set up. you must call either player.setupAudioOut() or, if you know what you are doing, set player.forceNativeAudioFormat=true" << endl; return result; } lock_guard<mutex> lock(audio_queue_mutex); if( audio_stream_idx < 0 ){ memset(output,0,bufferSize*nChannels*sizeof(float)); int64_t outLen = bufferSize; if(allowWaitForVideo && waitForVideoDelta>0){ outLen = MAX(bufferSize/8,MIN(bufferSize,bufferSize-waitForVideoDelta*output_sample_rate)); waitForVideoDelta -= outLen/(float)output_sample_rate; } int64_t nextPts = last_pts + outLen; double maxPts = duration*output_sample_rate/1000.0; if( nextPts > maxPts ){ nextPts = maxPts; } result.pts = nextPts; result.t = result.pts/(double)output_sample_rate; result.numFrames = nextPts-last_pts; last_t = result.t; last_pts = result.pts; return result; } int num_samples_read = 0; uint64_t pts = 0; if( audio_queue.size() > 0 ){ ofxAvAudioData * data = audio_queue.front(); result.pts = data->pts + data->decoded_buffer_pos/output_num_channels; result.t = data->t + data->decoded_buffer_pos/output_num_channels/(double)output_sample_rate; last_pts = data->pts_native + data->decoded_buffer_pos/output_num_channels/(double)output_sample_rate/av_q2d(audio_stream->time_base); last_t = result.t; } if(audio_frames_available < 2*bufferSize){ requestSkipFrame = true; AVL_MEASURE(cout << "Request skip frame" << endl); } while( audio_queue.size() > 0 ){ ofxAvAudioData * data = audio_queue.front(); int missing_samples = bufferSize*nChannels - num_samples_read; int available_samples = data->decoded_buffer_len - data->decoded_buffer_pos; if( missing_samples > 0 && available_samples > 0 ){ int samples = min( missing_samples, available_samples ); if( volume != 0 ){ memcpy(output+num_samples_read, data->decoded_buffer+data->decoded_buffer_pos, samples*sizeof(float) ); } if( volume != 1 && volume != 0 ){ for( int i = 0; i < samples; i++ ){ output[i+num_samples_read] *= volume; } } data->decoded_buffer_pos += samples; num_samples_read += samples; audio_frames_available -= samples/nChannels; //TODO: increment timestamp? if( data->decoded_buffer_pos >= data->decoded_buffer_len ){ audio_queue.pop(); delete data; } if( num_samples_read >= bufferSize*nChannels ){ result.numFrames = bufferSize; return result; } } } result.numFrames = num_samples_read/nChannels; return result; } // this is _mostly_ only called from the special happy thread! bool ofxAvVideoPlayer::decode_next_frame(){ av_free_packet(&packet); int res = av_read_frame(fmt_ctx, &packet); bool didRead = res >= 0; if( didRead ){ int got_frame = 0; if (!decoded_frame) { if (!(decoded_frame = av_frame_alloc())) { fprintf(stderr, "Could not allocate audio frame\n"); return false; } } else{ av_frame_unref(decoded_frame); } // ---------------------------------------------- // Handle audio stream // ---------------------------------------------- if( packet.stream_index == audio_stream_idx && output_setup_called && audio_stream_idx >= 0 ){ decode_audio_frame(got_frame); return true; } // ---------------------------------------------- // Handle video stream // ---------------------------------------------- else if(packet.stream_index == video_stream_idx ){ decode_video_frame(got_frame); return true; } // ---------------------------------------------- // Unknown data stream // ---------------------------------------------- else{ return true; } } else{ // no data read... // there might be some leftover frames in the buffer! packet.data = NULL; packet.size = 0; int got_frame; if( decode_video_frame(got_frame,false) || got_frame ){ // yep, we got another. // back to the start. btw, this game could happen >3 times ! return true; } packet_data_size = 0; //TODO: clear out all buffers! if( isLooping ){ //avformat_seek_file(fmt_ctx,audio_stream_idx,0,0,0,AVSEEK_FLAG_ANY); //avcodec_flush_buffers(audio_context); //decode_next_frame(); if( isPlaying ){ if( last_pts > 0 ){ restart_loop = true; } } else{ needsMoreVideo = false; } return false; } else{ isPlaying = false; } return false; } } bool ofxAvVideoPlayer::decode_video_frame( int & got_frame, bool maySkip ){ // maybe skip a frame? if(allowSkipFrames && requestSkipFrame && maySkip){ requestSkipFrame = false; got_frame = 0; return false; } /* decode video frame */ AVL_MEASURE(uint64_t decode_start = ofGetSystemTime();) int res = avcodec_decode_video2(video_context, decoded_frame, &got_frame, &packet); AVL_MEASURE(uint64_t decode_end = ofGetSystemTime();) AVL_MEASURE(cout << "decode_2 = " << (decode_end-decode_start)/1000.0 << endl;) if (res < 0) { fprintf(stderr, "Error decoding video frame (%s)\n", ofxAvUtils::errorString(res).c_str()); return false; } if (got_frame) { lock_guard<mutex> lock(video_buffers_mutex); AVL_MEASURE(uint64_t queue_start = ofGetSystemTime();) queue_decoded_video_frame_vlocked(); AVL_MEASURE(uint64_t queue_end = ofGetSystemTime();) AVL_MEASURE(cout << "queue_frame = " << (queue_end-queue_start)/1000.0 << endl;) needsMoreVideo = false; return true; } else{ return false; } } bool ofxAvVideoPlayer::decode_audio_frame( int & got_frame ){ len = avcodec_decode_audio4(audio_context, decoded_frame, &got_frame, &packet); if (len < 0) { // no data return false; } if (got_frame) { lock_guard<mutex> lock(audio_queue_mutex); queue_decoded_audio_frame_alocked(); } packet.size -= len; packet.data += len; return true; } bool ofxAvVideoPlayer::queue_decoded_audio_frame_alocked(){ if( swr_context != NULL && output_config_changed ){ output_config_changed = false; if( swr_context ){ swr_close(swr_context); swr_free(&swr_context); swr_context = NULL; } } if( swr_context == NULL ){ int input_channel_layout = decoded_frame->channel_layout; if( input_channel_layout == 0 ){ input_channel_layout = av_get_default_channel_layout( audio_context->channels ); } swr_context = swr_alloc_set_opts(NULL, output_channel_layout, AV_SAMPLE_FMT_FLT, output_sample_rate, input_channel_layout, (AVSampleFormat)decoded_frame->format, decoded_frame->sample_rate, 0, NULL); swr_init(swr_context); if (!swr_context){ fprintf(stderr, "Could not allocate resampler context\n"); return false; } } int samples_per_channel = AVCODEC_MAX_AUDIO_FRAME_SIZE/output_num_channels; ofxAvAudioData * data = new ofxAvAudioData(); uint8_t * out = (uint8_t*)data->decoded_buffer; int samples_converted = swr_convert(swr_context, (uint8_t**)&out, samples_per_channel, (const uint8_t**)decoded_frame->extended_data, decoded_frame->nb_samples); data->decoded_buffer_len = samples_converted*output_num_channels; data->decoded_buffer_pos = 0; if(packet.pts != AV_NOPTS_VALUE) { if(decoder_last_audio_pts < 0 ){ decoder_last_audio_pts = (decoded_frame->pkt_pts)*output_sample_rate*av_q2d(audio_stream->time_base); } data->pts = decoder_last_audio_pts; data->pts_native = decoded_frame->pkt_pts; data->t = av_q2d(audio_stream->time_base)*(decoded_frame->pkt_pts); decoder_last_audio_pts += samples_converted; AVL_MEASURE(cout << "A: t=" << data->t << "\t\t" << last_t << endl;) } // the entire function must be called with an audio lock. // in reality locking from here on out would be good enough. audio_frames_available += samples_converted; audio_queue.push(data); return true; } // this is _mostly_ only called from the special happy thread! bool ofxAvVideoPlayer::decode_until( double t, double & decoded_t ){ int lookForDelayedPackets = 20; decode_another: av_free_packet(&packet); int res = av_read_frame(fmt_ctx, &packet); bool didRead = res >= 0; if( !didRead && lookForDelayedPackets > 0 ){ // no data read... // are frames hiding in the pipe? packet.data = NULL; packet.size = 0; packet.stream_index = video_stream_idx; packet_data_size = 0; lookForDelayedPackets --; didRead = true; } // another seek requested during our seek? cancel! if( requestedSeek ) return false; if( didRead ){ int got_frame = 0; if (!decoded_frame) { if (!(decoded_frame = av_frame_alloc())) { fprintf(stderr, "Could not allocate audio frame\n"); return false; } } else{ av_frame_unref(decoded_frame); } // ---------------------------------------------- // Handle audio stream // ---------------------------------------------- if( packet.stream_index == audio_stream_idx ){ goto decode_another; } // ---------------------------------------------- // Handle video stream // ---------------------------------------------- else if(packet.stream_index == video_stream_idx ){ /* decode video frame */ res = avcodec_decode_video2(video_context, decoded_frame, &got_frame, &packet); if (res < 0) { fprintf(stderr, "Error decoding video frame (%s)\n", ofxAvUtils::errorString(res).c_str()); goto decode_another; } if (got_frame) { double nextT = av_q2d(video_stream->time_base)*decoded_frame->pkt_pts; bool stillBehind = nextT < t; bool notTooFarBehind = t - nextT < 5; bool notTooLittleBehind = nextT+1/getFps()/2 < t; if( stillBehind && notTooFarBehind && notTooLittleBehind ){ goto decode_another; } queue_decoded_video_frame_vlocked(); decoded_t = video_buffers[(video_buffers_pos)%video_buffers.size()]->t; } else{ goto decode_another; } return true; } // ---------------------------------------------- // Unknown data stream // ---------------------------------------------- else{ goto decode_another; } } else{ return false; } } bool ofxAvVideoPlayer::queue_decoded_video_frame_vlocked(){ if (decoded_frame->width != width || decoded_frame->height != height /*|| decoded_frame->format != pix_fmt*/) { /* To handle this change, one could call av_image_alloc again and * decode the following frames into another rawvideo file. */ fprintf(stderr, "Error: Width, height and pixel format have to be " "constant in a rawvideo file, but the width, height or " "pixel format of the input video changed:\n" "old: width = %d, height = %d, format = %s\n" "new: width = %d, height = %d, format = %s\n", width, height, av_get_pix_fmt_name(pix_fmt), decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name((AVPixelFormat)decoded_frame->format)); return -1; } video_buffers_pos ++; video_buffers_pos %= video_buffers.size(); ofxAvVideoData * data = video_buffers[video_buffers_pos]; AVL_MEASURE(uint64_t cp_start = ofGetSystemTime();) av_image_copy(data->video_dst_data, data->video_dst_linesize, (const uint8_t**)decoded_frame->data, decoded_frame->linesize, video_context->pix_fmt, video_context->width, video_context->height); AVL_MEASURE(cout << "\tdata->pts = " << decoded_frame->pkt_pts << endl); AVL_MEASURE(uint64_t cp_end = ofGetSystemTime();) AVL_MEASURE(cout << "cp = " << (cp_end-cp_start)/1000.0 << endl;) //cout << packet.pts << "\t" << packet.dts <<"\t" << video_stream->first_dts << "\t" << decoded_frame->pkt_pts << "\t" << decoded_frame->pkt_dts << endl; data->pts = decoded_frame->pkt_pts; data->t = av_q2d(video_stream->time_base)*decoded_frame->pkt_pts; AVL_MEASURE(cout << "V: t=" << data->t << "\t" << last_t << endl;) return true; } bool ofxAvVideoPlayer::copy_to_pixels_vlocked( ofxAvVideoData * data ){ if( sws_context == NULL ){ // Create context AVPixelFormat pixFormat = video_context->pix_fmt; switch (video_stream->codec->pix_fmt) { case AV_PIX_FMT_YUVJ420P : pixFormat = AV_PIX_FMT_YUV420P; break; case AV_PIX_FMT_YUVJ422P : pixFormat = AV_PIX_FMT_YUV422P; break; case AV_PIX_FMT_YUVJ444P : pixFormat = AV_PIX_FMT_YUV444P; break; case AV_PIX_FMT_YUVJ440P : pixFormat = AV_PIX_FMT_YUV440P; default: pixFormat = video_stream->codec->pix_fmt; break; } sws_context = sws_getContext( // source video_context->width, video_context->height, video_context->pix_fmt, // dest video_context->width, video_context->height, AV_PIX_FMT_RGB24, // flags / src filter / dest filter / param SWS_FAST_BILINEAR, NULL, NULL, NULL ); // transfer color space from decoder to encoder int *coefficients; const int *new_coefficients; int full_range; int brightness, contrast, saturation; bool use_full_range = 0; if ( sws_getColorspaceDetails( sws_context, &coefficients, &full_range, &coefficients, &full_range, &brightness, &contrast, &saturation ) != -1 ) { new_coefficients = sws_getCoefficients(video_stream->codec->colorspace); sws_setColorspaceDetails( sws_context, new_coefficients, full_range, new_coefficients, full_range, brightness, contrast, saturation ); } } if( !video_pixels.isAllocated() || video_pixels.getWidth() != width || video_pixels.getHeight() != height ){ video_pixels.allocate(width, height, OF_IMAGE_COLOR); } AVL_MEASURE(uint64_t sws_start = ofGetSystemTime();) int linesize[4] = {3*width,0,0,0}; uint8_t * video_pixel_data = video_pixels.getData(); uint8_t * dst[4] = {video_pixel_data, 0, 0, 0}; sws_scale(sws_context, // src slice / src stride data->video_dst_data, data->video_dst_linesize, // src slice y / src slice h 0, height, // destinatin / destination stride dst, linesize ); AVL_MEASURE(uint64_t sws_end = ofGetSystemTime();) AVL_MEASURE(cout << "sws = " << (sws_end-sws_start)/1000.0 << endl;) return true; } long long ofxAvVideoPlayer::av_time_to_millis( int64_t av_time ){ if( audio_stream_idx >= 0 ){ return av_rescale(1000*av_time,audio_stream->time_base.num,audio_stream->time_base.den); } else if( output_setup_called ){ return av_rescale(1000*av_time, 1, output_sample_rate); } else if( video_stream_idx >= 0 ){ return av_rescale(1000*av_time,video_stream->time_base.num,video_stream->time_base.den); } else{ return 0; } //alternative: //return av_time*1000*av_q2d(fmt_ctx->streams[audio_stream_id]->time_base); } int64_t ofxAvVideoPlayer::millis_to_av_time( long long ms ){ //TODO: fix conversion /* int64_t timeBase = (int64_t(audio_context->time_base.num) * AV_TIME_BASE) / int64_t(audio_context->time_base.den); int64_t seekTarget = int64_t(ms) / timeBase;*/ if( audio_stream_idx >= 0 ){ return av_rescale(ms,audio_stream->time_base.den,audio_stream->time_base.num)/1000; } else if( output_setup_called ){ return av_rescale(ms, output_sample_rate, 1)/1000.0; } else if( video_stream_idx >= 0 ){ return av_rescale(ms,video_stream->time_base.den,video_stream->time_base.num)/1000; } else{ return 0; } } void ofxAvVideoPlayer::setPositionMS(long long ms){ int64_t next = millis_to_av_time(min(ms,duration)); if( next != next_seekTarget ){ requestedSeek = true; next_seekTarget = next; } } int ofxAvVideoPlayer::getPositionMS(){ if( !fileLoaded ) return 0; return audio_stream_idx<0&&output_setup_called? av_rescale(1000*texturePts,video_stream->time_base.num,video_stream->time_base.den) :av_time_to_millis( last_pts ); } float ofxAvVideoPlayer::getPosition(){ return duration == 0? 0 : (getPositionMS()/(float)duration); } void ofxAvVideoPlayer::setPosition(float percent){ if(duration>0) setPositionMS((int)(percent*duration)); } void ofxAvVideoPlayer::stop(){ isPlaying =false; } void ofxAvVideoPlayer::play(){ if( fileLoaded ){ isPlaying = true; } } void ofxAvVideoPlayer::setPaused(bool paused){ isPlaying = fileLoaded?!paused:false; } void ofxAvVideoPlayer::setLoop(bool loop){ isLooping = loop; } void ofxAvVideoPlayer::setVolume(float vol){ this->volume = vol; } float ofxAvVideoPlayer::getVolume(){ return volume; } bool ofxAvVideoPlayer::isLoaded(){ return fileLoaded; } long long ofxAvVideoPlayer::getDurationMs(){ return duration; } bool ofxAvVideoPlayer::getIsPlaying(){ return isPlaying; } string ofxAvVideoPlayer::getMetadata( string key ){ if( fmt_ctx != NULL ){ AVDictionaryEntry * entry = av_dict_get(fmt_ctx->metadata, key.c_str(), NULL, 0); if( entry == NULL ) return ""; else return string(entry->value); } else{ return ""; } } map<string,string> ofxAvVideoPlayer::getMetadata(){ map<string,string> meta; AVDictionary * d = fmt_ctx->metadata; AVDictionaryEntry *t = NULL; while ((t = av_dict_get(d, "", t, AV_DICT_IGNORE_SUFFIX))!=0){ meta[string(t->key)] = string(t->value); } return meta; } ofTexture & ofxAvVideoPlayer::getTexture(){ return texture; } const ofPixels & ofxAvVideoPlayer::getPixels(){ return video_pixels; } int ofxAvVideoPlayer::getFrameNumber(){ if( !isLoaded() ) return 0; // this is not ideal! in fact: it's simply not working yet! lock_guard<mutex> lock(video_buffers_mutex); return last_t*av_q2d(video_stream->r_frame_rate); } double ofxAvVideoPlayer::getFps(){ if( !isLoaded() ) return 0; return av_q2d(video_stream->r_frame_rate); } ofxAvVideoData * ofxAvVideoPlayer::video_data_for_time_vlocked( double t ){ ofxAvVideoData * data = video_buffers[0]; double bestDistance = 10; bool needsMoreVideo = true; int j = 0, bestJ = 0; for( ofxAvVideoData * buffer : video_buffers ){ double distance = fabs(buffer->t - last_t); if( buffer->t > -1 && distance < bestDistance ){ data = buffer; bestDistance = distance; bestJ = j; } j++; } return data; } void ofxAvVideoPlayer::update(){ if( !texture.isAllocated()){ texture.allocate(1,1,GL_RGB); } if( !fileLoaded ){ return; } if( true ){ // fudge it, we don't need a lock! ^^ // lock_guard<mutex> lock(video_buffers_mutex); double request_t = last_t; ofxAvVideoData * data = video_data_for_time_vlocked(request_t); if( texturePts != data->pts ){ if( !texture.isAllocated() || texture.getWidth() != width || texture.getHeight() != height ){ texture.allocate( width, height, GL_RGB ); } copy_to_pixels_vlocked(data); texture.loadData(video_pixels); texturePts = data->pts; } // we're basically done, now check for the next frame, maybe. if( isPlaying || texturePts == -1 ){ double dt = 1.0/getFps(); bool useVideoClock = !output_setup_called; float numFramesPreloaded = useVideoClock?2.2:1.1; double targetT = request_t+numFramesPreloaded*dt; ofxAvVideoData * nextFrame = video_data_for_time_vlocked(targetT); if( nextFrame->t < request_t || nextFrame->t == -1) needsMoreVideo = true; if( nextFrame->t < request_t && (request_t-nextFrame->t)>4*dt && allowWaitForVideo && audio_stream_idx<0){ AVL_MEASURE(cout << "CRAZY DELAY [" << (request_t-nextFrame->t) << "]. request skipframe!" << endl ); waitForVideoDelta = request_t-nextFrame->t - 2*dt; } else if(nextFrame->t < request_t && (request_t-nextFrame->t)>2*dt && allowSkipFrames){ requestSkipFrame = true; } if( useVideoClock ){ last_t += ofGetLastFrameTime(); last_pts = last_t/av_q2d(video_stream->time_base); } } /* for( int i = 0; i < video_buffers.size(); i++ ){ if( i == bestJ ) ofSetColor(255); else ofSetColor(200); ofDrawBitmapString(ofToString(video_buffers[i]->t), 10+40*i, 200); }*/ } } void ofxAvVideoPlayer::run_decoder(){ while( isLoaded() && !wantsUnload){ if( restart_loop && isPlaying ){ restart_loop = false; // wait until we run out of samples! while( audio_frames_available > 0 && !wantsUnload && isPlaying){ ofSleepMillis(1); } if( isPlaying ){ next_seekTarget = 0; requestedSeek = true; } //last_pts = 0; needsMoreVideo = true; } if( requestedSeek && next_seekTarget >= 0 ){ requestedSeek = false; //av_seek_frame(fmt_ctx,-1,next_seekTarget,AVSEEK_FLAG_ANY); /* avcodec_flush_buffers(video_context); avcodec_flush_buffers(audio_context); avformat_seek_file(fmt_ctx,audio_stream_idx,0,next_seekTarget,next_seekTarget,AVSEEK_FLAG_BACKWARD); avformat_seek_file(fmt_ctx,video_stream_idx,0,next_seekTarget,next_seekTarget,AVSEEK_FLAG_BACKWARD); */ lock_guard<mutex> audio_guard(audio_queue_mutex); lock_guard<mutex> video_guard(video_buffers_mutex); int stream_index = video_stream_idx; avcodec_flush_buffers(video_context); if(audio_stream_idx>=0){ avcodec_flush_buffers(audio_context); } int64_t seek_target; if( audio_stream_idx >= 0 ){ seek_target = next_seekTarget*1000000*av_q2d(audio_stream->time_base)-1000000; } else if( output_setup_called ){ seek_target = next_seekTarget*1000000/(double)output_sample_rate-1000000; } else if( video_stream_idx >= 0 ){ seek_target = next_seekTarget*1000000*av_q2d(video_stream->time_base)-1000000; } else{ isPlaying = false; continue; } int flags = AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD; if(av_seek_frame(fmt_ctx, -1, seek_target, flags)<0) { cerr << "error while seeking\n" << fileNameAbs << endl; //last_t = 0; //last_pts = 0; } else{ // last_pts = next_seekTarget; if( audio_stream_idx >= 0 ){ //last_t = av_q2d(audio_stream->time_base)*last_pts; } else if( output_setup_called ){ //last_t = last_pts/(double)output_sample_rate; } else if( video_stream_idx >= 0 ){ //last_t = av_q2d(video_stream->time_base)*last_pts; } else{ isPlaying = false; continue; } } // cancel if there was another seek if( requestedSeek ) continue; double want_t; if( audio_stream_idx >= 0 ){ want_t = next_seekTarget*av_q2d(audio_stream->time_base);; } else if( output_setup_called ){ want_t = next_seekTarget/(double)output_sample_rate; } else if( video_stream_idx >= 0 ){ want_t = next_seekTarget*av_q2d(video_stream->time_base);; } else{ isPlaying = false; continue; } double got_t = -1; if( next_seekTarget == 0 ){ needsMoreVideo = true; //last_t = 0; //last_pts = 0; got_t = 0; } else{ decode_until(want_t, got_t); } // cancel if there was another seek if( requestedSeek ) continue; // did we skip within half a frame accuracy? great! if( got_t > want_t+1/getFps()/2.0 ){ cout << "went too far!" << endl; // seek to 0, go forward if( video_stream_idx >= 0 ){ avcodec_flush_buffers(video_context); } if( audio_stream_idx >= 0 ){ avcodec_flush_buffers(audio_context); } if( audio_stream_idx >= 0 ){ seek_target = next_seekTarget*1000000*av_q2d(audio_stream->time_base)-2500000; } else if( output_setup_called ){ seek_target = next_seekTarget*1000000/(double)output_sample_rate-2500000; } else if( video_stream_idx >= 0 ){ seek_target = next_seekTarget*1000000*av_q2d(video_stream->time_base)-2500000; } else{ isPlaying = false; continue; } av_seek_frame(fmt_ctx, -1, seek_target, AVSEEK_FLAG_BACKWARD|AVSEEK_FLAG_ANY); //avformat_seek_file(fmt_ctx, video_stream_idx, 0, 0, 0, AVSEEK_FLAG_BYTE|AVSEEK_FLAG_BACKWARD); if( video_stream_idx >= 0 ){ avcodec_flush_buffers(video_context); } if( audio_stream_idx >= 0 ){ avcodec_flush_buffers(audio_context); } // cancel if there was another seek if( requestedSeek ) continue; decode_until(want_t, got_t); cout << "p2 tried decoding to " << want_t << ", got " << got_t << endl; } if( got_t == -1 ){ // emergency back to 0 av_seek_frame(fmt_ctx, -1, seek_target, AVSEEK_FLAG_BACKWARD|AVSEEK_FLAG_ANY); if( video_stream_idx >= 0 ) avcodec_flush_buffers(video_context); if( audio_stream_idx >= 0 ) avcodec_flush_buffers(audio_context); // alright, jump to 0 :( last_pts = 0; last_t = 0; } else{ last_pts = next_seekTarget; last_t = got_t; } while( audio_queue.size() > 0 ){ ofxAvAudioData * data = audio_queue.front(); delete data; audio_queue.pop(); audio_frames_available = 0; } decoder_last_audio_pts = -1; next_seekTarget = -1; } bool needsMoreAudio = audio_stream_idx >= 0 && output_setup_called && (audio_frames_available < output_sample_rate*0.5); if( (needsMoreAudio && isPlaying) || (needsMoreVideo) ){ AVL_MEASURE(uint64_t time_start = ofGetSystemTime();) decode_next_frame(); AVL_MEASURE(uint64_t time_end = ofGetSystemTime();) AVL_MEASURE(cout << "decode_time = " << (time_end-time_start)/1000.0 << endl;) } else{ ofSleepMillis(1); } } } string ofxAvVideoPlayer::getFile(){ return fileNameAbs; } string ofxAvVideoPlayer::getInfo(){ stringstream info; if( isLoaded() ){ info << "File: " << fileNameBase << endl; if( video_stream_idx >= 0 ){ info << "Video: " << video_context->codec->name << ", " << video_context->width << " x " << video_context->height; float aspect = video_context->width/(float)video_context->height; float eps = 0.001; if( fabsf(aspect-4.0f/3.0f) < eps ) info <<" (4:3)"; else if( fabsf(aspect-16.0f/9.0f) < eps ) info <<" (16:9)"; else if( fabsf(aspect-3.0f/2.0f) < eps ) info <<" (3:2)"; else if( fabsf(aspect-2.35f/1.0f) < eps ) info <<" (2.35:1)"; info << " @ " << av_q2d(video_stream->r_frame_rate) << "fps" << endl; } else{ info << "Video: -" << endl; } if( audio_stream_idx >= 0 ){ info << "Audio: " << audio_context->codec->name << ", " << audio_context->channels << " channels, " << audio_context->sample_rate << "kHz" << endl; } else{ info << "Audio: -" << endl; } } else{ info << "no video loaded"; } return info.str(); } int ofxAvVideoPlayer::getCurrentFrame() { return (int)(round(getPositionMS()/(1000.0/getFps()))); } int ofxAvVideoPlayer::getTotalNumFrames() { if( !isLoaded() ) return 0; return (int)(duration * 1000 * getFps()); } void ofxAvVideoPlayer::firstFrame(){ if(duration>0) { setPositionMS(0.0); } } void ofxAvVideoPlayer::nextFrame(){ if(duration>0) { setPositionMS(getPositionMS() + 1000.0/getFps()); } } void ofxAvVideoPlayer::previousFrame(){ if(duration>0) { setPositionMS(getPositionMS() - 1000.0/getFps()); }} float ofxAvVideoPlayer::getHeight() const { return (float)height; } float ofxAvVideoPlayer::getWidth() const { return (float)width; } void ofxAvVideoPlayer::draw(float _x, float _y, float _w, float _h) { getTexture().draw(_x,_y,_w,_h); } void ofxAvVideoPlayer::draw(float _x, float _y) { draw(_x, _y, getWidth(), getHeight()); } AVCodecID ofxAvVideoPlayer::getVideoCodec(){ if(!fileLoaded || wantsUnload || video_stream_idx<0 || !video_context){ return AV_CODEC_ID_NONE; } else{ return video_context->codec_id; } } disabled dropframes again for everything other than prores. causes too much pain // // ofxAvVideoPlayer.cpp // emptyExample // // Created by Hansi on 13.07.15. // // a huge chunk of this file is based on the // blog entry https://blinkingblip.wordpress.com/2011/10/08/decoding-and-playing-an-audio-stream-using-libavcodec-libavformat-and-libao/ // (had to make some adjustments for changes in ffmpeg // and libavcodecs examples // https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/decoding_encoding.c #include "ofxAvVideoPlayer.h" #include "ofMain.h" #include "ofxAvUtils.h" extern "C"{ #include <libavutil/opt.h> } // for release: // #define AVL_MEASURE(x) // for debug: // #define AVL_MEASURE(x) x #define AVL_MEASURE(x) using namespace std; #define die(msg) { unload(); cerr << msg << endl; return false; } // this holds an image class ofxAvVideoData{ public: uint8_t *video_dst_data[4]; int video_dst_linesize[4]; int video_dst_bufsize; bool allocated; int64_t pts; double t; ofxAvVideoData() : allocated(false), video_dst_bufsize(0),pts(-1),t(-1){} }; class ofxAvAudioData{ public: int64_t pts; int64_t pts_native; double t; // contains audio data, always in interleaved float format int decoded_buffer_pos; int decoded_buffer_len; float decoded_buffer[AVCODEC_MAX_AUDIO_FRAME_SIZE]; ofxAvAudioData() : decoded_buffer_len(0){} }; ofxAvVideoPlayer::ofxAvVideoPlayer(){ ofxAvUtils::init(); // default audio settings output_channel_layout = av_get_default_channel_layout(2); output_sample_rate = 44100; output_num_channels = 2; output_config_changed = false; output_setup_called = false; volume = 1; isLooping = false; fmt_ctx = NULL; decoded_frame = NULL; audio_context = NULL; video_context = NULL; audio_stream = NULL; video_stream = NULL; buffer_size = AVCODEC_MAX_AUDIO_FRAME_SIZE; swr_context = NULL; sws_context = NULL; av_init_packet(&packet); unload(); } ofxAvVideoPlayer::~ofxAvVideoPlayer(){ unload(); } static int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type){ int ret, stream_index; AVStream *st; AVCodecContext *dec_ctx = NULL; AVCodec *dec = NULL; AVDictionary *opts = NULL; ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0); if (ret < 0) { fprintf(stderr, "Could not find %s stream in input file\n", av_get_media_type_string(type)); return ret; } else { stream_index = ret; st = fmt_ctx->streams[stream_index]; /* find decoder for the stream */ dec_ctx = st->codec; if( type == AVMEDIA_TYPE_VIDEO){ av_opt_set(dec_ctx->priv_data, "tune", "zerolatency", 0); dec_ctx->thread_type = FF_THREAD_SLICE | FF_THREAD_FRAME; } dec = avcodec_find_decoder(dec_ctx->codec_id); if (!dec) { fprintf(stderr, "Failed to find %s codec\n", av_get_media_type_string(type)); return AVERROR(EINVAL); } if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) { fprintf(stderr, "Failed to open %s codec\n", av_get_media_type_string(type)); return ret; } av_dict_set(&opts, "refcounted_frames", "1", 0); *stream_idx = stream_index; } return 0; } bool ofxAvVideoPlayer::load(string fileName, bool stream){ unload(); fileNameAbs = ofToDataPath(fileName,true); fileNameBase = ofFile(fileNameAbs,ofFile::Reference).getFileName(); const char * input_filename = fileNameAbs.c_str(); // the first finds the right codec, following https://blinkingblip.wordpress.com/2011/10/08/decoding-and-playing-an-audio-stream-using-libavcodec-libavformat-and-libao/ // and also demuxing_decoding.c in the ffmpeg examples // throughout all of it we are using "new api, reference counted" for memory management fmt_ctx = 0; // AVInputFormat fmt; // fmt.flags = AVFMT_SEEK_TO_PTS; if (avformat_open_input(&fmt_ctx, input_filename, NULL, NULL) < 0) { die("Could not open file"); } fmt_ctx->iformat->flags |= AVFMT_SEEK_TO_PTS; if (avformat_find_stream_info(fmt_ctx,NULL) < 0) { die("Could not find file info"); } // ---------------------------------------------- // Find video stream // ---------------------------------------------- if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) { video_stream = fmt_ctx->streams[video_stream_idx]; video_context = video_stream->codec; /* allocate image where the decoded image will be put */ // we will use the sws resampling context to fill out the data! width = video_context->width; height = video_context->height; pix_fmt = AV_PIX_FMT_RGB24; // allow skip frames only for prores, which seems to decode particularly slow allowSkipFrames = video_context->codec_id == AV_CODEC_ID_PRORES; // allocate a bunch of images! // we take 1.2 times frame rate (e.g. 36 frames for a 30fps video), // and at least 30 frames to avoid big issues just in case r_frame_rate is a bit off. int numBufferedFrames = (int)ofClamp(av_q2d(video_stream->r_frame_rate)*1.4, 30.0, 70.0); ofLogError() << "[ofxAvVideoPlayer] Buffering " << numBufferedFrames << endl; for( int i = 0; i < numBufferedFrames; i++ ){ ofxAvVideoData * data = new ofxAvVideoData(); int ret = av_image_alloc(data->video_dst_data, data->video_dst_linesize, video_context->width, video_context->height, video_context->pix_fmt, 1); if (ret < 0) { die("Could not allocate raw video buffer"); } data->video_dst_bufsize = ret; video_buffers.push_back(data); } } if( video_stream_idx == -1 ){ die("Could not find a video stream"); } // ---------------------------------------------- // Find audio stream // ---------------------------------------------- audio_stream_idx = -1; if(open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0){ audio_stream = fmt_ctx->streams[audio_stream_idx]; audio_context = audio_stream->codec; } //TODO: we don't want to require an audio stream //when reading video if (audio_stream_idx == -1) { //die("Could not find an audio stream"); //nope, not a problem anymore! } // Find the apropriate codec and open it if( forceNativeAudioFormat && audio_stream_idx >= 0){ output_sample_rate = audio_context->sample_rate; output_setup_called = true; output_channel_layout = audio_context->channel_layout; if( output_channel_layout == 0 ){ output_num_channels = audio_context->channels; output_channel_layout = av_get_default_channel_layout(output_num_channels); } else{ output_num_channels = av_get_channel_layout_nb_channels( output_channel_layout ); } AVL_MEASURE(cout << "native audio thing: " << output_sample_rate << "Hz / " << output_num_channels << " channels" << endl;) } // dump info, this is interresting! av_dump_format(fmt_ctx, 0, input_filename, 0); // from here on it's mostly following // https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/decoding_encoding.c //packet.data = inbuf; //packet.size = fread(inbuf, 1, AVCODEC_AUDIO_INBUF_SIZE, f); av_init_packet(&packet); packet.data = NULL; packet.size = 0; swr_context = NULL; sws_context = NULL; fileLoaded = true; isPlaying = true; // we continue here: decode_next_frame(); //TODO: only video should be required. if( video_stream_idx >= 0){ duration = 1000*video_stream->duration*av_q2d(video_stream->time_base); } else if( audio_stream_idx >= 0 ){ duration = 1000*audio_stream->duration*av_q2d(audio_stream->time_base); } if( duration <= 0 ){ duration = 1000 * fmt_ctx->duration*av_q2d(AVRational{ 1,AV_TIME_BASE }); } if( duration <= 0 ){ unload(); return false; } next_seekTarget = 0; requestedSeek = true; decoderThread = thread(&ofxAvVideoPlayer::run_decoder, this); return true; } bool ofxAvVideoPlayer::setupAudioOut( int numChannels, int sampleRate ){ output_setup_called = true; if( numChannels != output_num_channels || sampleRate != output_sample_rate ){ output_channel_layout = av_get_default_channel_layout(numChannels); output_sample_rate = sampleRate; output_num_channels = numChannels; if( swr_context != NULL ){ output_config_changed = true; } } return true; } void ofxAvVideoPlayer::unload(){ fileNameAbs = ""; fileLoaded = false; isPlaying = false; wantsUnload = true; if( decoderThread.joinable() ){ decoderThread.join(); } wantsUnload = false; packet_data_size = 0; len = 0; last_t = 0; last_pts = 0; restart_loop = false; texturePts = -1; next_seekTarget = 0; requestedSeek = false; decoder_last_audio_pts = 0; waitForVideoDelta = 0; audio_queue_mutex.lock(); while( audio_queue.size() > 0 ){ ofxAvAudioData * data = audio_queue.front(); delete data; audio_queue.pop(); } audio_frames_available = 0; audio_queue_mutex.unlock(); video_buffers_mutex.lock(); for( ofxAvVideoData * data : video_buffers ){ av_freep(&data->video_dst_data[0]); delete data; } video_buffers_pos = 0; video_buffers.clear(); video_buffers_mutex.unlock(); next_seekTarget = -1; video_stream_idx = -1; audio_stream_idx = -1; av_free_packet(&packet); if( decoded_frame ){ //TODO: do we really need the unref here? av_frame_unref(decoded_frame); av_frame_free(&decoded_frame); decoded_frame = NULL; } if( fmt_ctx ){ avcodec_close(video_context); avcodec_close(audio_context); avformat_close_input(&fmt_ctx); avformat_free_context(fmt_ctx); av_free(fmt_ctx); fmt_ctx = NULL; audio_context = NULL; video_context = NULL; } if( swr_context ){ swr_close(swr_context); swr_free(&swr_context); swr_context = NULL; } if( sws_context ){ sws_freeContext(sws_context); sws_context = NULL; } } ofxAvVideoPlayer::AudioResult ofxAvVideoPlayer::audioOut(float *output, int bufferSize, int nChannels){ AudioResult result{0,last_pts,last_t}; if( !fileLoaded ){ return result; } if( !isPlaying ){ return result; } if( !output_setup_called ){ ofLogWarning() << "[ofxAvVideoPlayer] audioOut() called, but audio was not set up. you must call either player.setupAudioOut() or, if you know what you are doing, set player.forceNativeAudioFormat=true" << endl; return result; } lock_guard<mutex> lock(audio_queue_mutex); if( audio_stream_idx < 0 ){ memset(output,0,bufferSize*nChannels*sizeof(float)); int64_t outLen = bufferSize; if(allowWaitForVideo && waitForVideoDelta>0){ outLen = MAX(bufferSize/8,MIN(bufferSize,bufferSize-waitForVideoDelta*output_sample_rate)); waitForVideoDelta -= outLen/(float)output_sample_rate; } int64_t nextPts = last_pts + outLen; double maxPts = duration*output_sample_rate/1000.0; if( nextPts > maxPts ){ nextPts = maxPts; } result.pts = nextPts; result.t = result.pts/(double)output_sample_rate; result.numFrames = nextPts-last_pts; last_t = result.t; last_pts = result.pts; return result; } int num_samples_read = 0; uint64_t pts = 0; if( audio_queue.size() > 0 ){ ofxAvAudioData * data = audio_queue.front(); result.pts = data->pts + data->decoded_buffer_pos/output_num_channels; result.t = data->t + data->decoded_buffer_pos/output_num_channels/(double)output_sample_rate; last_pts = data->pts_native + data->decoded_buffer_pos/output_num_channels/(double)output_sample_rate/av_q2d(audio_stream->time_base); last_t = result.t; } if(audio_frames_available < 2*bufferSize){ requestSkipFrame = true; AVL_MEASURE(cout << "Request skip frame" << endl); } while( audio_queue.size() > 0 ){ ofxAvAudioData * data = audio_queue.front(); int missing_samples = bufferSize*nChannels - num_samples_read; int available_samples = data->decoded_buffer_len - data->decoded_buffer_pos; if( missing_samples > 0 && available_samples > 0 ){ int samples = min( missing_samples, available_samples ); if( volume != 0 ){ memcpy(output+num_samples_read, data->decoded_buffer+data->decoded_buffer_pos, samples*sizeof(float) ); } if( volume != 1 && volume != 0 ){ for( int i = 0; i < samples; i++ ){ output[i+num_samples_read] *= volume; } } data->decoded_buffer_pos += samples; num_samples_read += samples; audio_frames_available -= samples/nChannels; //TODO: increment timestamp? if( data->decoded_buffer_pos >= data->decoded_buffer_len ){ audio_queue.pop(); delete data; } if( num_samples_read >= bufferSize*nChannels ){ result.numFrames = bufferSize; return result; } } } result.numFrames = num_samples_read/nChannels; return result; } // this is _mostly_ only called from the special happy thread! bool ofxAvVideoPlayer::decode_next_frame(){ av_free_packet(&packet); int res = av_read_frame(fmt_ctx, &packet); bool didRead = res >= 0; if( didRead ){ int got_frame = 0; if (!decoded_frame) { if (!(decoded_frame = av_frame_alloc())) { fprintf(stderr, "Could not allocate audio frame\n"); return false; } } else{ av_frame_unref(decoded_frame); } // ---------------------------------------------- // Handle audio stream // ---------------------------------------------- if( packet.stream_index == audio_stream_idx && output_setup_called && audio_stream_idx >= 0 ){ decode_audio_frame(got_frame); return true; } // ---------------------------------------------- // Handle video stream // ---------------------------------------------- else if(packet.stream_index == video_stream_idx ){ decode_video_frame(got_frame); return true; } // ---------------------------------------------- // Unknown data stream // ---------------------------------------------- else{ return true; } } else{ // no data read... // there might be some leftover frames in the buffer! packet.data = NULL; packet.size = 0; int got_frame; if( decode_video_frame(got_frame,false) || got_frame ){ // yep, we got another. // back to the start. btw, this game could happen >3 times ! return true; } packet_data_size = 0; //TODO: clear out all buffers! if( isLooping ){ //avformat_seek_file(fmt_ctx,audio_stream_idx,0,0,0,AVSEEK_FLAG_ANY); //avcodec_flush_buffers(audio_context); //decode_next_frame(); if( isPlaying ){ if( last_pts > 0 ){ restart_loop = true; } } else{ needsMoreVideo = false; } return false; } else{ isPlaying = false; } return false; } } bool ofxAvVideoPlayer::decode_video_frame( int & got_frame, bool maySkip ){ // maybe skip a frame? if(allowSkipFrames && requestSkipFrame && maySkip){ requestSkipFrame = false; got_frame = 0; return false; } /* decode video frame */ AVL_MEASURE(uint64_t decode_start = ofGetSystemTime();) int res = avcodec_decode_video2(video_context, decoded_frame, &got_frame, &packet); AVL_MEASURE(uint64_t decode_end = ofGetSystemTime();) AVL_MEASURE(cout << "decode_2 = " << (decode_end-decode_start)/1000.0 << endl;) if (res < 0) { fprintf(stderr, "Error decoding video frame (%s)\n", ofxAvUtils::errorString(res).c_str()); return false; } if (got_frame) { lock_guard<mutex> lock(video_buffers_mutex); AVL_MEASURE(uint64_t queue_start = ofGetSystemTime();) queue_decoded_video_frame_vlocked(); AVL_MEASURE(uint64_t queue_end = ofGetSystemTime();) AVL_MEASURE(cout << "queue_frame = " << (queue_end-queue_start)/1000.0 << endl;) needsMoreVideo = false; return true; } else{ return false; } } bool ofxAvVideoPlayer::decode_audio_frame( int & got_frame ){ len = avcodec_decode_audio4(audio_context, decoded_frame, &got_frame, &packet); if (len < 0) { // no data return false; } if (got_frame) { lock_guard<mutex> lock(audio_queue_mutex); queue_decoded_audio_frame_alocked(); } packet.size -= len; packet.data += len; return true; } bool ofxAvVideoPlayer::queue_decoded_audio_frame_alocked(){ if( swr_context != NULL && output_config_changed ){ output_config_changed = false; if( swr_context ){ swr_close(swr_context); swr_free(&swr_context); swr_context = NULL; } } if( swr_context == NULL ){ int input_channel_layout = decoded_frame->channel_layout; if( input_channel_layout == 0 ){ input_channel_layout = av_get_default_channel_layout( audio_context->channels ); } swr_context = swr_alloc_set_opts(NULL, output_channel_layout, AV_SAMPLE_FMT_FLT, output_sample_rate, input_channel_layout, (AVSampleFormat)decoded_frame->format, decoded_frame->sample_rate, 0, NULL); swr_init(swr_context); if (!swr_context){ fprintf(stderr, "Could not allocate resampler context\n"); return false; } } int samples_per_channel = AVCODEC_MAX_AUDIO_FRAME_SIZE/output_num_channels; ofxAvAudioData * data = new ofxAvAudioData(); uint8_t * out = (uint8_t*)data->decoded_buffer; int samples_converted = swr_convert(swr_context, (uint8_t**)&out, samples_per_channel, (const uint8_t**)decoded_frame->extended_data, decoded_frame->nb_samples); data->decoded_buffer_len = samples_converted*output_num_channels; data->decoded_buffer_pos = 0; if(packet.pts != AV_NOPTS_VALUE) { if(decoder_last_audio_pts < 0 ){ decoder_last_audio_pts = (decoded_frame->pkt_pts)*output_sample_rate*av_q2d(audio_stream->time_base); } data->pts = decoder_last_audio_pts; data->pts_native = decoded_frame->pkt_pts; data->t = av_q2d(audio_stream->time_base)*(decoded_frame->pkt_pts); decoder_last_audio_pts += samples_converted; AVL_MEASURE(cout << "A: t=" << data->t << "\t\t" << last_t << endl;) } // the entire function must be called with an audio lock. // in reality locking from here on out would be good enough. audio_frames_available += samples_converted; audio_queue.push(data); return true; } // this is _mostly_ only called from the special happy thread! bool ofxAvVideoPlayer::decode_until( double t, double & decoded_t ){ int lookForDelayedPackets = 20; decode_another: av_free_packet(&packet); int res = av_read_frame(fmt_ctx, &packet); bool didRead = res >= 0; if( !didRead && lookForDelayedPackets > 0 ){ // no data read... // are frames hiding in the pipe? packet.data = NULL; packet.size = 0; packet.stream_index = video_stream_idx; packet_data_size = 0; lookForDelayedPackets --; didRead = true; } // another seek requested during our seek? cancel! if( requestedSeek ) return false; if( didRead ){ int got_frame = 0; if (!decoded_frame) { if (!(decoded_frame = av_frame_alloc())) { fprintf(stderr, "Could not allocate audio frame\n"); return false; } } else{ av_frame_unref(decoded_frame); } // ---------------------------------------------- // Handle audio stream // ---------------------------------------------- if( packet.stream_index == audio_stream_idx ){ goto decode_another; } // ---------------------------------------------- // Handle video stream // ---------------------------------------------- else if(packet.stream_index == video_stream_idx ){ /* decode video frame */ res = avcodec_decode_video2(video_context, decoded_frame, &got_frame, &packet); if (res < 0) { fprintf(stderr, "Error decoding video frame (%s)\n", ofxAvUtils::errorString(res).c_str()); goto decode_another; } if (got_frame) { double nextT = av_q2d(video_stream->time_base)*decoded_frame->pkt_pts; bool stillBehind = nextT < t; bool notTooFarBehind = t - nextT < 5; bool notTooLittleBehind = nextT+1/getFps()/2 < t; if( stillBehind && notTooFarBehind && notTooLittleBehind ){ goto decode_another; } queue_decoded_video_frame_vlocked(); decoded_t = video_buffers[(video_buffers_pos)%video_buffers.size()]->t; } else{ goto decode_another; } return true; } // ---------------------------------------------- // Unknown data stream // ---------------------------------------------- else{ goto decode_another; } } else{ return false; } } bool ofxAvVideoPlayer::queue_decoded_video_frame_vlocked(){ if (decoded_frame->width != width || decoded_frame->height != height /*|| decoded_frame->format != pix_fmt*/) { /* To handle this change, one could call av_image_alloc again and * decode the following frames into another rawvideo file. */ fprintf(stderr, "Error: Width, height and pixel format have to be " "constant in a rawvideo file, but the width, height or " "pixel format of the input video changed:\n" "old: width = %d, height = %d, format = %s\n" "new: width = %d, height = %d, format = %s\n", width, height, av_get_pix_fmt_name(pix_fmt), decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name((AVPixelFormat)decoded_frame->format)); return -1; } video_buffers_pos ++; video_buffers_pos %= video_buffers.size(); ofxAvVideoData * data = video_buffers[video_buffers_pos]; AVL_MEASURE(uint64_t cp_start = ofGetSystemTime();) av_image_copy(data->video_dst_data, data->video_dst_linesize, (const uint8_t**)decoded_frame->data, decoded_frame->linesize, video_context->pix_fmt, video_context->width, video_context->height); AVL_MEASURE(cout << "\tdata->pts = " << decoded_frame->pkt_pts << endl); AVL_MEASURE(uint64_t cp_end = ofGetSystemTime();) AVL_MEASURE(cout << "cp = " << (cp_end-cp_start)/1000.0 << endl;) //cout << packet.pts << "\t" << packet.dts <<"\t" << video_stream->first_dts << "\t" << decoded_frame->pkt_pts << "\t" << decoded_frame->pkt_dts << endl; data->pts = decoded_frame->pkt_pts; data->t = av_q2d(video_stream->time_base)*decoded_frame->pkt_pts; AVL_MEASURE(cout << "V: t=" << data->t << "\t" << last_t << endl;) return true; } bool ofxAvVideoPlayer::copy_to_pixels_vlocked( ofxAvVideoData * data ){ if( sws_context == NULL ){ // Create context AVPixelFormat pixFormat = video_context->pix_fmt; switch (video_stream->codec->pix_fmt) { case AV_PIX_FMT_YUVJ420P : pixFormat = AV_PIX_FMT_YUV420P; break; case AV_PIX_FMT_YUVJ422P : pixFormat = AV_PIX_FMT_YUV422P; break; case AV_PIX_FMT_YUVJ444P : pixFormat = AV_PIX_FMT_YUV444P; break; case AV_PIX_FMT_YUVJ440P : pixFormat = AV_PIX_FMT_YUV440P; default: pixFormat = video_stream->codec->pix_fmt; break; } sws_context = sws_getContext( // source video_context->width, video_context->height, video_context->pix_fmt, // dest video_context->width, video_context->height, AV_PIX_FMT_RGB24, // flags / src filter / dest filter / param SWS_FAST_BILINEAR, NULL, NULL, NULL ); // transfer color space from decoder to encoder int *coefficients; const int *new_coefficients; int full_range; int brightness, contrast, saturation; bool use_full_range = 0; if ( sws_getColorspaceDetails( sws_context, &coefficients, &full_range, &coefficients, &full_range, &brightness, &contrast, &saturation ) != -1 ) { new_coefficients = sws_getCoefficients(video_stream->codec->colorspace); sws_setColorspaceDetails( sws_context, new_coefficients, full_range, new_coefficients, full_range, brightness, contrast, saturation ); } } if( !video_pixels.isAllocated() || video_pixels.getWidth() != width || video_pixels.getHeight() != height ){ video_pixels.allocate(width, height, OF_IMAGE_COLOR); } AVL_MEASURE(uint64_t sws_start = ofGetSystemTime();) int linesize[4] = {3*width,0,0,0}; uint8_t * video_pixel_data = video_pixels.getData(); uint8_t * dst[4] = {video_pixel_data, 0, 0, 0}; sws_scale(sws_context, // src slice / src stride data->video_dst_data, data->video_dst_linesize, // src slice y / src slice h 0, height, // destinatin / destination stride dst, linesize ); AVL_MEASURE(uint64_t sws_end = ofGetSystemTime();) AVL_MEASURE(cout << "sws = " << (sws_end-sws_start)/1000.0 << endl;) return true; } long long ofxAvVideoPlayer::av_time_to_millis( int64_t av_time ){ if( audio_stream_idx >= 0 ){ return av_rescale(1000*av_time,audio_stream->time_base.num,audio_stream->time_base.den); } else if( output_setup_called ){ return av_rescale(1000*av_time, 1, output_sample_rate); } else if( video_stream_idx >= 0 ){ return av_rescale(1000*av_time,video_stream->time_base.num,video_stream->time_base.den); } else{ return 0; } //alternative: //return av_time*1000*av_q2d(fmt_ctx->streams[audio_stream_id]->time_base); } int64_t ofxAvVideoPlayer::millis_to_av_time( long long ms ){ //TODO: fix conversion /* int64_t timeBase = (int64_t(audio_context->time_base.num) * AV_TIME_BASE) / int64_t(audio_context->time_base.den); int64_t seekTarget = int64_t(ms) / timeBase;*/ if( audio_stream_idx >= 0 ){ return av_rescale(ms,audio_stream->time_base.den,audio_stream->time_base.num)/1000; } else if( output_setup_called ){ return av_rescale(ms, output_sample_rate, 1)/1000.0; } else if( video_stream_idx >= 0 ){ return av_rescale(ms,video_stream->time_base.den,video_stream->time_base.num)/1000; } else{ return 0; } } void ofxAvVideoPlayer::setPositionMS(long long ms){ int64_t next = millis_to_av_time(min(ms,duration)); if( next != next_seekTarget ){ requestedSeek = true; next_seekTarget = next; } } int ofxAvVideoPlayer::getPositionMS(){ if( !fileLoaded ) return 0; return audio_stream_idx<0&&output_setup_called? av_rescale(1000*texturePts,video_stream->time_base.num,video_stream->time_base.den) :av_time_to_millis( last_pts ); } float ofxAvVideoPlayer::getPosition(){ return duration == 0? 0 : (getPositionMS()/(float)duration); } void ofxAvVideoPlayer::setPosition(float percent){ if(duration>0) setPositionMS((int)(percent*duration)); } void ofxAvVideoPlayer::stop(){ isPlaying =false; } void ofxAvVideoPlayer::play(){ if( fileLoaded ){ isPlaying = true; } } void ofxAvVideoPlayer::setPaused(bool paused){ isPlaying = fileLoaded?!paused:false; } void ofxAvVideoPlayer::setLoop(bool loop){ isLooping = loop; } void ofxAvVideoPlayer::setVolume(float vol){ this->volume = vol; } float ofxAvVideoPlayer::getVolume(){ return volume; } bool ofxAvVideoPlayer::isLoaded(){ return fileLoaded; } long long ofxAvVideoPlayer::getDurationMs(){ return duration; } bool ofxAvVideoPlayer::getIsPlaying(){ return isPlaying; } string ofxAvVideoPlayer::getMetadata( string key ){ if( fmt_ctx != NULL ){ AVDictionaryEntry * entry = av_dict_get(fmt_ctx->metadata, key.c_str(), NULL, 0); if( entry == NULL ) return ""; else return string(entry->value); } else{ return ""; } } map<string,string> ofxAvVideoPlayer::getMetadata(){ map<string,string> meta; AVDictionary * d = fmt_ctx->metadata; AVDictionaryEntry *t = NULL; while ((t = av_dict_get(d, "", t, AV_DICT_IGNORE_SUFFIX))!=0){ meta[string(t->key)] = string(t->value); } return meta; } ofTexture & ofxAvVideoPlayer::getTexture(){ return texture; } const ofPixels & ofxAvVideoPlayer::getPixels(){ return video_pixels; } int ofxAvVideoPlayer::getFrameNumber(){ if( !isLoaded() ) return 0; // this is not ideal! in fact: it's simply not working yet! lock_guard<mutex> lock(video_buffers_mutex); return last_t*av_q2d(video_stream->r_frame_rate); } double ofxAvVideoPlayer::getFps(){ if( !isLoaded() ) return 0; return av_q2d(video_stream->r_frame_rate); } ofxAvVideoData * ofxAvVideoPlayer::video_data_for_time_vlocked( double t ){ ofxAvVideoData * data = video_buffers[0]; double bestDistance = 10; bool needsMoreVideo = true; int j = 0, bestJ = 0; for( ofxAvVideoData * buffer : video_buffers ){ double distance = fabs(buffer->t - last_t); if( buffer->t > -1 && distance < bestDistance ){ data = buffer; bestDistance = distance; bestJ = j; } j++; } return data; } void ofxAvVideoPlayer::update(){ if( !texture.isAllocated()){ texture.allocate(1,1,GL_RGB); } if( !fileLoaded ){ return; } if( true ){ // fudge it, we don't need a lock! ^^ // lock_guard<mutex> lock(video_buffers_mutex); double request_t = last_t; ofxAvVideoData * data = video_data_for_time_vlocked(request_t); if( texturePts != data->pts ){ if( !texture.isAllocated() || texture.getWidth() != width || texture.getHeight() != height ){ texture.allocate( width, height, GL_RGB ); } copy_to_pixels_vlocked(data); texture.loadData(video_pixels); texturePts = data->pts; } // we're basically done, now check for the next frame, maybe. if( isPlaying || texturePts == -1 ){ double dt = 1.0/getFps(); bool useVideoClock = !output_setup_called; float numFramesPreloaded = useVideoClock?2.2:1.1; double targetT = request_t+numFramesPreloaded*dt; ofxAvVideoData * nextFrame = video_data_for_time_vlocked(targetT); if( nextFrame->t < request_t || nextFrame->t == -1) needsMoreVideo = true; if( nextFrame->t < request_t && (request_t-nextFrame->t)>4*dt && allowWaitForVideo && audio_stream_idx<0){ AVL_MEASURE(cout << "CRAZY DELAY [" << (request_t-nextFrame->t) << "]. request skipframe!" << endl ); waitForVideoDelta = request_t-nextFrame->t - 2*dt; } else if(nextFrame->t < request_t && (request_t-nextFrame->t)>2*dt && allowSkipFrames){ requestSkipFrame = true; } if( useVideoClock ){ last_t += ofGetLastFrameTime(); last_pts = last_t/av_q2d(video_stream->time_base); } } /* for( int i = 0; i < video_buffers.size(); i++ ){ if( i == bestJ ) ofSetColor(255); else ofSetColor(200); ofDrawBitmapString(ofToString(video_buffers[i]->t), 10+40*i, 200); }*/ } } void ofxAvVideoPlayer::run_decoder(){ while( isLoaded() && !wantsUnload){ if( restart_loop && isPlaying ){ restart_loop = false; // wait until we run out of samples! while( audio_frames_available > 0 && !wantsUnload && isPlaying){ ofSleepMillis(1); } if( isPlaying ){ next_seekTarget = 0; requestedSeek = true; } //last_pts = 0; needsMoreVideo = true; } if( requestedSeek && next_seekTarget >= 0 ){ requestedSeek = false; //av_seek_frame(fmt_ctx,-1,next_seekTarget,AVSEEK_FLAG_ANY); /* avcodec_flush_buffers(video_context); avcodec_flush_buffers(audio_context); avformat_seek_file(fmt_ctx,audio_stream_idx,0,next_seekTarget,next_seekTarget,AVSEEK_FLAG_BACKWARD); avformat_seek_file(fmt_ctx,video_stream_idx,0,next_seekTarget,next_seekTarget,AVSEEK_FLAG_BACKWARD); */ lock_guard<mutex> audio_guard(audio_queue_mutex); lock_guard<mutex> video_guard(video_buffers_mutex); int stream_index = video_stream_idx; avcodec_flush_buffers(video_context); if(audio_stream_idx>=0){ avcodec_flush_buffers(audio_context); } int64_t seek_target; if( audio_stream_idx >= 0 ){ seek_target = next_seekTarget*1000000*av_q2d(audio_stream->time_base)-1000000; } else if( output_setup_called ){ seek_target = next_seekTarget*1000000/(double)output_sample_rate-1000000; } else if( video_stream_idx >= 0 ){ seek_target = next_seekTarget*1000000*av_q2d(video_stream->time_base)-1000000; } else{ isPlaying = false; continue; } int flags = AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD; if(av_seek_frame(fmt_ctx, -1, seek_target, flags)<0) { cerr << "error while seeking\n" << fileNameAbs << endl; //last_t = 0; //last_pts = 0; } else{ // last_pts = next_seekTarget; if( audio_stream_idx >= 0 ){ //last_t = av_q2d(audio_stream->time_base)*last_pts; } else if( output_setup_called ){ //last_t = last_pts/(double)output_sample_rate; } else if( video_stream_idx >= 0 ){ //last_t = av_q2d(video_stream->time_base)*last_pts; } else{ isPlaying = false; continue; } } // cancel if there was another seek if( requestedSeek ) continue; double want_t; if( audio_stream_idx >= 0 ){ want_t = next_seekTarget*av_q2d(audio_stream->time_base);; } else if( output_setup_called ){ want_t = next_seekTarget/(double)output_sample_rate; } else if( video_stream_idx >= 0 ){ want_t = next_seekTarget*av_q2d(video_stream->time_base);; } else{ isPlaying = false; continue; } double got_t = -1; if( next_seekTarget == 0 ){ needsMoreVideo = true; //last_t = 0; //last_pts = 0; got_t = 0; } else{ decode_until(want_t, got_t); } // cancel if there was another seek if( requestedSeek ) continue; // did we skip within half a frame accuracy? great! if( got_t > want_t+1/getFps()/2.0 ){ cout << "went too far!" << endl; // seek to 0, go forward if( video_stream_idx >= 0 ){ avcodec_flush_buffers(video_context); } if( audio_stream_idx >= 0 ){ avcodec_flush_buffers(audio_context); } if( audio_stream_idx >= 0 ){ seek_target = next_seekTarget*1000000*av_q2d(audio_stream->time_base)-2500000; } else if( output_setup_called ){ seek_target = next_seekTarget*1000000/(double)output_sample_rate-2500000; } else if( video_stream_idx >= 0 ){ seek_target = next_seekTarget*1000000*av_q2d(video_stream->time_base)-2500000; } else{ isPlaying = false; continue; } av_seek_frame(fmt_ctx, -1, seek_target, AVSEEK_FLAG_BACKWARD|AVSEEK_FLAG_ANY); //avformat_seek_file(fmt_ctx, video_stream_idx, 0, 0, 0, AVSEEK_FLAG_BYTE|AVSEEK_FLAG_BACKWARD); if( video_stream_idx >= 0 ){ avcodec_flush_buffers(video_context); } if( audio_stream_idx >= 0 ){ avcodec_flush_buffers(audio_context); } // cancel if there was another seek if( requestedSeek ) continue; decode_until(want_t, got_t); cout << "p2 tried decoding to " << want_t << ", got " << got_t << endl; } if( got_t == -1 ){ // emergency back to 0 av_seek_frame(fmt_ctx, -1, seek_target, AVSEEK_FLAG_BACKWARD|AVSEEK_FLAG_ANY); if( video_stream_idx >= 0 ) avcodec_flush_buffers(video_context); if( audio_stream_idx >= 0 ) avcodec_flush_buffers(audio_context); // alright, jump to 0 :( last_pts = 0; last_t = 0; } else{ last_pts = next_seekTarget; last_t = got_t; } while( audio_queue.size() > 0 ){ ofxAvAudioData * data = audio_queue.front(); delete data; audio_queue.pop(); audio_frames_available = 0; } decoder_last_audio_pts = -1; next_seekTarget = -1; } bool needsMoreAudio = audio_stream_idx >= 0 && output_setup_called && (audio_frames_available < output_sample_rate*0.5); if( (needsMoreAudio && isPlaying) || (needsMoreVideo) ){ AVL_MEASURE(uint64_t time_start = ofGetSystemTime();) decode_next_frame(); AVL_MEASURE(uint64_t time_end = ofGetSystemTime();) AVL_MEASURE(cout << "decode_time = " << (time_end-time_start)/1000.0 << endl;) } else{ ofSleepMillis(1); } } } string ofxAvVideoPlayer::getFile(){ return fileNameAbs; } string ofxAvVideoPlayer::getInfo(){ stringstream info; if( isLoaded() ){ info << "File: " << fileNameBase << endl; if( video_stream_idx >= 0 ){ info << "Video: " << video_context->codec->name << ", " << video_context->width << " x " << video_context->height; float aspect = video_context->width/(float)video_context->height; float eps = 0.001; if( fabsf(aspect-4.0f/3.0f) < eps ) info <<" (4:3)"; else if( fabsf(aspect-16.0f/9.0f) < eps ) info <<" (16:9)"; else if( fabsf(aspect-3.0f/2.0f) < eps ) info <<" (3:2)"; else if( fabsf(aspect-2.35f/1.0f) < eps ) info <<" (2.35:1)"; info << " @ " << av_q2d(video_stream->r_frame_rate) << "fps" << endl; } else{ info << "Video: -" << endl; } if( audio_stream_idx >= 0 ){ info << "Audio: " << audio_context->codec->name << ", " << audio_context->channels << " channels, " << audio_context->sample_rate << "kHz" << endl; } else{ info << "Audio: -" << endl; } } else{ info << "no video loaded"; } return info.str(); } int ofxAvVideoPlayer::getCurrentFrame() { return (int)(round(getPositionMS()/(1000.0/getFps()))); } int ofxAvVideoPlayer::getTotalNumFrames() { if( !isLoaded() ) return 0; return (int)(duration * 1000 * getFps()); } void ofxAvVideoPlayer::firstFrame(){ if(duration>0) { setPositionMS(0.0); } } void ofxAvVideoPlayer::nextFrame(){ if(duration>0) { setPositionMS(getPositionMS() + 1000.0/getFps()); } } void ofxAvVideoPlayer::previousFrame(){ if(duration>0) { setPositionMS(getPositionMS() - 1000.0/getFps()); }} float ofxAvVideoPlayer::getHeight() const { return (float)height; } float ofxAvVideoPlayer::getWidth() const { return (float)width; } void ofxAvVideoPlayer::draw(float _x, float _y, float _w, float _h) { getTexture().draw(_x,_y,_w,_h); } void ofxAvVideoPlayer::draw(float _x, float _y) { draw(_x, _y, getWidth(), getHeight()); } AVCodecID ofxAvVideoPlayer::getVideoCodec(){ if(!fileLoaded || wantsUnload || video_stream_idx<0 || !video_context){ return AV_CODEC_ID_NONE; } else{ return video_context->codec_id; } }
/************************************************************************* * * $RCSfile: services.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: sb $ $Date: 2001-08-20 07:10:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _CPPU_MACROS_HXX_ #include <cppu/macros.hxx> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _UNO_ENVIRONMENT_H_ #include <uno/environment.h> #endif #ifndef UUI_IAHNDL_HXX #include <iahndl.hxx> #endif using namespace com::sun::star; //============================================================================ // // component_getImplementationEnvironment // //============================================================================ extern "C" void SAL_CALL component_getImplementationEnvironment(sal_Char const ** pEnvTypeName, uno_Environment **) { *pEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //============================================================================ // // component_writeInfo // //============================================================================ extern "C" sal_Bool SAL_CALL component_writeInfo(void *, void * pRegistryKey) { bool bSuccess = pRegistryKey != 0; uno::Reference< registry::XRegistryKey > xKey; if (bSuccess) { rtl::OUString aKeyName(rtl::OUString::createFromAscii("/")); aKeyName += rtl::OUString::createFromAscii( UUIInteractionHandler::m_aImplementationName); aKeyName += rtl::OUString::createFromAscii("/UNO/SERVICES"); try { xKey = static_cast< registry::XRegistryKey * >(pRegistryKey)-> createKey(aKeyName); } catch (registry::InvalidRegistryException &) {} bSuccess = xKey.is() != false; } if (bSuccess) { uno::Sequence< rtl::OUString > aServiceNames( UUIInteractionHandler::getSupportedServiceNames_static()); for (sal_Int32 i = 0; i < aServiceNames.getLength(); ++i) try { xKey->createKey(aServiceNames[i]); } catch (registry::InvalidRegistryException &) { bSuccess = false; break; } } return bSuccess; } //============================================================================ // // component_getFactory // //============================================================================ extern "C" void * SAL_CALL component_getFactory(sal_Char const * pImplName, void * pServiceManager, void *) { void * pFactory = 0; if (pServiceManager && rtl_str_compare(pImplName, UUIInteractionHandler::m_aImplementationName) == 0) { uno::Reference< lang::XSingleServiceFactory > xTheFactory( cppu::createSingleFactory( static_cast< lang::XMultiServiceFactory * >( pServiceManager), rtl::OUString::createFromAscii( UUIInteractionHandler::m_aImplementationName), &UUIInteractionHandler::createInstance, UUIInteractionHandler::getSupportedServiceNames_static())); if (xTheFactory.is()) { xTheFactory->acquire(); pFactory = xTheFactory.get(); } } return pFactory; } INTEGRATION: CWS ooo19126 (1.5.246); FILE MERGED 2005/09/05 17:09:52 rt 1.5.246.1: #i54170# Change license header: remove SISSL /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: services.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 10:27:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _CPPU_MACROS_HXX_ #include <cppu/macros.hxx> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _UNO_ENVIRONMENT_H_ #include <uno/environment.h> #endif #ifndef UUI_IAHNDL_HXX #include <iahndl.hxx> #endif using namespace com::sun::star; //============================================================================ // // component_getImplementationEnvironment // //============================================================================ extern "C" void SAL_CALL component_getImplementationEnvironment(sal_Char const ** pEnvTypeName, uno_Environment **) { *pEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //============================================================================ // // component_writeInfo // //============================================================================ extern "C" sal_Bool SAL_CALL component_writeInfo(void *, void * pRegistryKey) { bool bSuccess = pRegistryKey != 0; uno::Reference< registry::XRegistryKey > xKey; if (bSuccess) { rtl::OUString aKeyName(rtl::OUString::createFromAscii("/")); aKeyName += rtl::OUString::createFromAscii( UUIInteractionHandler::m_aImplementationName); aKeyName += rtl::OUString::createFromAscii("/UNO/SERVICES"); try { xKey = static_cast< registry::XRegistryKey * >(pRegistryKey)-> createKey(aKeyName); } catch (registry::InvalidRegistryException &) {} bSuccess = xKey.is() != false; } if (bSuccess) { uno::Sequence< rtl::OUString > aServiceNames( UUIInteractionHandler::getSupportedServiceNames_static()); for (sal_Int32 i = 0; i < aServiceNames.getLength(); ++i) try { xKey->createKey(aServiceNames[i]); } catch (registry::InvalidRegistryException &) { bSuccess = false; break; } } return bSuccess; } //============================================================================ // // component_getFactory // //============================================================================ extern "C" void * SAL_CALL component_getFactory(sal_Char const * pImplName, void * pServiceManager, void *) { void * pFactory = 0; if (pServiceManager && rtl_str_compare(pImplName, UUIInteractionHandler::m_aImplementationName) == 0) { uno::Reference< lang::XSingleServiceFactory > xTheFactory( cppu::createSingleFactory( static_cast< lang::XMultiServiceFactory * >( pServiceManager), rtl::OUString::createFromAscii( UUIInteractionHandler::m_aImplementationName), &UUIInteractionHandler::createInstance, UUIInteractionHandler::getSupportedServiceNames_static())); if (xTheFactory.is()) { xTheFactory->acquire(); pFactory = xTheFactory.get(); } } return pFactory; }
#include <iostream> #include <string> void run_part_one() { } void run_part_two() { } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day18 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } } added runtime code for day 18 part one #include <iostream> #include <string> #include "LightMap.hpp" void print_map(LightMap& light_map) { for (int y=0;y<100;y++) { for(int x=0;x<100;x++) { if (light_map.is_on(x,y)) { std::cout << '#'; } else { std::cout << '.'; } } std::cout << std::endl; } } void run_part_one() { std::string line; LightMap map(100,100); unsigned int current_line = 0; while (std::getline(std::cin,line)) { for (unsigned int i=0; i<100; i++) { if (line[i] == '#') { map.turn_on(i,current_line); } } current_line++; } for (unsigned int i = 0; i<100; i++) { map = map.evolve(); } std::cout << map.get_active_lights() << std::endl; } void run_part_two() { } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day18 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } }
/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY vincent.acary@inrialpes.fr */ #include "Lsodar.h" #include "EventDriven.h" #include "LagrangianLinearTIDS.h" #include "BlockVector.h" #include "NonSmoothDynamicalSystem.h" #include "Model.h" #include "Topology.h" using namespace std; // ===== Out of class objects and functions ===== // global object and wrapping functions -> required for function plug-in and call in fortran routine. Lsodar* global_object; // This first function must have the same signature as argument F (arg 1) in DLSODAR (see opkdmain.f in Numerics) extern "C" void Lsodar_f_wrapper(integer * sizeOfX, doublereal * time, doublereal * x, doublereal * xdot) { return global_object->f(sizeOfX, time, x, xdot); } // Function to wrap g: same signature as argument G (arg 18) in DLSODAR (see opkdmain.f in Numerics) extern "C" void Lsodar_g_wrapper(integer * nEq, doublereal * time, doublereal* x, integer* ng, doublereal * gOut) { return global_object->g(nEq, time, x, ng, gOut); } // Function to wrap jacobianF: same signature as argument JAC (arg 16) in DLSODAR (see opkdmain.f in Numerics) extern "C" void Lsodar_jacobianF_wrapper(integer * sizeOfX, doublereal * time, doublereal * x, integer* ml, integer * mu, doublereal * jacob, integer * nrowpd) { return global_object->jacobianF(sizeOfX, time, x, ml, mu, jacob, nrowpd); } Lsodar::Lsodar(OneStepIntegratorXML* osiXML, Simulation* newS): OneStepIntegrator("Lsodar", osiXML, newS), rtol(NULL), atol(NULL), rwork(NULL), iwork(NULL), jroot(NULL) { // local time discretisation is set by default to those of the simulation. intData.resize(9); sizeMem = 2; } Lsodar::Lsodar(DynamicalSystem* ds, Simulation* newS): OneStepIntegrator("Lsodar", newS), rtol(NULL), atol(NULL), rwork(NULL), iwork(NULL), jroot(NULL) { if (simulationLink == NULL) RuntimeException::selfThrow("Lsodar:: constructor(ds,simulation) - simulation == NULL"); // add ds in the set OSIDynamicalSystems->insert(ds); intData.resize(9); sizeMem = 2; } Lsodar::Lsodar(DynamicalSystemsSet& newDS, Simulation* newS): OneStepIntegrator("Lsodar", newDS, newS), rtol(NULL), atol(NULL), rwork(NULL), iwork(NULL), jroot(NULL) { if (simulationLink == NULL) RuntimeException::selfThrow("Lsodar:: constructor(DSSet,simulation) - simulation == NULL"); intData.resize(9); sizeMem = 2; } Lsodar::~Lsodar() { global_object = NULL; if (rtol != NULL) delete rtol; rtol = NULL; if (atol != NULL) delete atol; atol = NULL; if (rwork != NULL) delete rwork; rwork = NULL; if (iwork != NULL) delete iwork; iwork = NULL; if (xWork != NULL) delete xWork; } void Lsodar::setTol(integer newItol, doublereal* newRtol, doublereal* newAtol) { // The input parameters ITOL, RTOL, and ATOL determine // the error control performed by the solver. The solver will // control the vector E = (E(i)) of estimated local errors // in y, according to an inequality of the form // max-norm of ( E(i)/EWT(i) ) .le. 1, // where EWT = (EWT(i)) is a vector of positive error weights. // The values of RTOL and ATOL should all be non-negative. // The following table gives the types (scalar/array) of // RTOL and ATOL, and the corresponding form of EWT(i). // // ITOL RTOL ATOL EWT(i) // 1 scalar scalar RTOL*ABS(Y(i)) + ATOL // 2 scalar array RTOL*ABS(Y(i)) + ATOL(i) // 3 array scalar RTOL(i)*ABS(Y(i)) + ATOL // 4 array array RTOL(i)*ABS(Y(i)) + ATOL(i) intData[2] = newItol; // itol unsigned int sizeTol = intData[0]; // neq // Memory allocation ... if (rtol != NULL) delete rtol; rtol = new doublereal[sizeTol] ; // rtol, relative tolerance if (atol != NULL) delete atol; atol = new doublereal[sizeTol] ; // atol, absolute tolerance *rtol = *newRtol; *atol = *newRtol; } void Lsodar::updateData() { // Used to update some data (iwork ...) when intData is modified. // Warning: it only checks sizes and possibly reallocate memory, but no values are set. unsigned int sizeTol = intData[0]; // size of rtol, atol ... If itol (intData[0]) = 1 => scalar else, vector of size neq (intData[0]). // if(intData[0]==1) sizeTol = 1; // else sizeTol = intData[0]; if (rtol != NULL) delete rtol; rtol = new doublereal[sizeTol] ; // rtol, relative tolerance if (atol != NULL) delete atol; atol = new doublereal[sizeTol] ; // atol, absolute tolerance if (iwork != NULL) delete iwork; // iwork iwork = new integer[intData[7]]; if (rwork != NULL) delete rwork; // rwork rwork = new doublereal[intData[6]]; if (jroot != NULL) delete jroot; // jroot jroot = new integer[intData[1]]; } void Lsodar::fillXWork(integer* sizeOfX, doublereal * x) { unsigned int sizeX = (unsigned int)(*sizeOfX); for (unsigned int i = 0; i < sizeX ; ++i) (*xWork)(i) = x[i]; } void Lsodar::computeRhs(double t) { DSIterator it; for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) (*it)->computeRhs(t); } void Lsodar::computeJacobianRhs(double t) { DSIterator it; for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) (*it)->computeJacobianXRhs(t); } void Lsodar::f(integer * sizeOfX, doublereal * time, doublereal * x, doublereal * xdot) { static_cast<EventDriven*>(simulationLink)->computeF(this, sizeOfX, time, x, xdot); } void Lsodar::g(integer * nEq, doublereal * time, doublereal* x, integer * ng, doublereal * gOut) { static_cast<EventDriven*>(simulationLink)->computeG(this, nEq, time, x, ng, gOut); } void Lsodar::jacobianF(integer *sizeOfX, doublereal *time, doublereal *x, integer* ml, integer *mu, doublereal *jacob, integer *nrowpd) { static_cast<EventDriven*>(simulationLink)->computeJacobianF(this, sizeOfX, time, x, jacob); } void Lsodar::initialize() { OneStepIntegrator::initialize(); xWork = new BlockVector(); DSIterator it; string type; // initialize xWork with x values of the dynamical systems present in the set. for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) xWork->insertPtr((*it)->getXPtr()); // Integer parameters for LSODAR are saved in vector intParam. // The link with variable names in opkdmain.f is indicated in comments // 1 - Neq; x vector size. intData[0] = xWork->size(); // 2 - Ng, number of constraints: intData[1] = simulationLink->getModelPtr()->getNonSmoothDynamicalSystemPtr()->getTopologyPtr()->getNumberOfConstraints(); // 3 - Itol, itask, iopt intData[2] = 1; // itol, 1 if ATOL is a scalar, else 2 (ATOL array) intData[3] = 1; // itask, an index specifying the task to be performed. 1: normal computation. intData[5] = 0; // iopt: 0 if no optional input else 1. // 4 - Istate intData[4] = 1; // istate, an index used for input and output to specify the state of the calculation. // On input: // 1: first call for the problem (initializations will be done). // 2: means this is not the first call, and the calculation is to continue normally, with no change in any input // parameters except possibly TOUT and ITASK. // 3: means this is not the first call, and the calculation is to continue normally, but with // a change in input parameters other than TOUT and ITASK. // On output: // 1: means nothing was done; TOUT = t and ISTATE = 1 on input. // 2: means the integration was performed successfully, and no roots were found. // 3: means the integration was successful, and one or more roots were found before satisfying the stop condition specified by ITASK. See JROOT. // <0: error. See table below, in integrate function output message. // 5 - lrw, size of rwork intData[6] = 22 + intData[0] * max(16, (int)intData[0] + 9) + 3 * intData[1]; // 6 - liw, size of iwork intData[7] = 20 + intData[0]; // 7 - JT, Jacobian type indicator intData[8] = 2; // jt, Jacobian type indicator. // 1 means a user-supplied full (NEQ by NEQ) Jacobian. // 2 means an internally generated (difference quotient) full Jacobian (using NEQ extra calls to f per df/dx value). // 4 means a user-supplied banded Jacobian. // 5 means an internally generated banded Jacobian (using ML+MU+1 extra calls to f per df/dx evaluation). // memory allocation for doublereal*, according to intData values ... updateData(); // Set atol and rtol values ... rtol[0] = MACHINE_PREC; // rtol atol[0] = MACHINE_PREC; // atol // === Error handling in LSODAR=== // parameters: itol, rtol, atol. // Control vector E = (E(i)) of estimated local errors in y: // max-norm of ( E(i)/EWT(i) )< 1 // EWT = (EWT(i)) vector of positive error weights. // The values of RTOL and ATOL should all be non-negative. // // ITOL RTOL ATOL EWT(i) // 1 scalar scalar RTOL*ABS(Y(i)) + ATOL // 2 scalar array RTOL*ABS(Y(i)) + ATOL(i) // 3 array scalar RTOL(i)*ABS(Y(i)) + ATOL // 4 array array RTOL(i)*ABS(Y(i)) + ATOL(i) } void Lsodar::integrate(double& tinit, double& tend, double& tout, int& istate) { // For details on DLSODAR parameters, see opkdmain.f in Numerics/src/odepack doublereal tend_DR = tend ; // next point where output is desired (different from t!) doublereal tinit_DR = tinit; // current (starting) time // === Pointers to function === // --> definition and initialisation thanks to wrapper: global_object = this; // Warning: global object must be initialized to current one before pointers to function initialisation. // function to compute the righ-hand side of xdot = f(x,t) + Tu fpointer pointerToF = Lsodar_f_wrapper; // function to compute the Jacobian/x of the rhs. jacopointer pointerToJacobianF = Lsodar_jacobianF_wrapper; // function to compute the Jacobian/x of the rhs. // function to compute the constraints gpointer pointerToG; pointerToG = Lsodar_g_wrapper; // function to compute the constraints // === LSODAR CALL === SimpleVector * xtmp = new SimpleVector(*xWork); // A copy of xWork is required since at the time, there are no contiguous values in memory for BlockVectors. if (istate == 3) { istate = 1; // restart TEMPORARY } intData[4] = istate; F77NAME(dlsodar)(pointerToF, &(intData[0]), &(*xtmp)(0), &tinit_DR, &tend_DR, &(intData[2]), rtol, atol, &(intData[3]), &(intData[4]), &(intData[5]), rwork, &(intData[6]), iwork, &(intData[7]), pointerToJacobianF, &(intData[8]), pointerToG, &(intData[1]), jroot); // jroot: jroot[i] = 0 if g(i) has a root at t, else jroot[i] = 0. // === Post === if (intData[4] < 0) // if istate < 0 => LSODAR failed { cout << "LSodar::integrate(...) failed - Istate = " << intData[4] << endl; cout << " -1 means excess work done on this call (perhaps wrong JT)." << endl; cout << " -2 means excess accuracy requested (tolerances too small)." << endl; cout << " -3 means illegal input detected (see printed message)." << endl; cout << " -4 means repeated error test failures (check all inputs)." << endl; cout << " -5 means repeated convergence failures (perhaps bad Jacobian supplied or wrong choice of JT or tolerances)." << endl; cout << " -6 means error weight became zero during problem. (Solution component i vanished, and ATOL or ATOL(i) = 0.)" << endl; cout << " -7 means work space insufficient to finish (see messages)." << endl; RuntimeException::selfThrow("Lsodar, integration failed"); } *xWork = *xtmp; delete xtmp; istate = intData[4]; tout = tinit_DR; // real ouput time tend = tend_DR; // necessary for next start of DLSODAR // tinit = tinit_DR; } void Lsodar::updateState(unsigned int level) { // Compute all required (ie time-dependent) data for the DS of the OSI. DSIterator it; if (level == 1) // ie impact case: compute velocity { for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) { LagrangianDS* lds = static_cast<LagrangianDS*>(*it); lds->computePostImpactVelocity(); } } else if (level == 2)// compute acceleration ie RHS and its jacobian. { double time = simulationLink->getModelPtr()->getCurrentTime(); for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) (*it)->update(time); } else RuntimeException::selfThrow("Lsodar::updateState(index), index is out of range. Index = " + level); } void Lsodar::display() { OneStepIntegrator::display(); cout << " --- > Lsodar specific values: " << endl; cout << "Number of equations: " << intData[0] << endl; cout << "Number of constraints: " << intData[1] << endl; cout << "itol, itask, istate, iopt, lrw, liw, jt: (for details on what are these variables see opkdmain.f)" << endl; cout << intData[2] << ", " << intData[3] << ", " << intData[4] << ", " << intData[5] << ", " << intData[6] << ", " << intData[7] << ", " << intData[8] << endl; cout << "====================================" << endl; } Bug fix in Lsodar::setTol, atol was set with the value of rtol. git-svn-id: de9bbed4c30e0eb58fe8e7d66f5c80b71699a07c@1301 bf01a9d7-0df3-0310-8ad4-b1c94d9ae2d5 /* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY vincent.acary@inrialpes.fr */ #include "Lsodar.h" #include "EventDriven.h" #include "LagrangianLinearTIDS.h" #include "BlockVector.h" #include "NonSmoothDynamicalSystem.h" #include "Model.h" #include "Topology.h" using namespace std; // ===== Out of class objects and functions ===== // global object and wrapping functions -> required for function plug-in and call in fortran routine. Lsodar* global_object; // This first function must have the same signature as argument F (arg 1) in DLSODAR (see opkdmain.f in Numerics) extern "C" void Lsodar_f_wrapper(integer * sizeOfX, doublereal * time, doublereal * x, doublereal * xdot) { return global_object->f(sizeOfX, time, x, xdot); } // Function to wrap g: same signature as argument G (arg 18) in DLSODAR (see opkdmain.f in Numerics) extern "C" void Lsodar_g_wrapper(integer * nEq, doublereal * time, doublereal* x, integer* ng, doublereal * gOut) { return global_object->g(nEq, time, x, ng, gOut); } // Function to wrap jacobianF: same signature as argument JAC (arg 16) in DLSODAR (see opkdmain.f in Numerics) extern "C" void Lsodar_jacobianF_wrapper(integer * sizeOfX, doublereal * time, doublereal * x, integer* ml, integer * mu, doublereal * jacob, integer * nrowpd) { return global_object->jacobianF(sizeOfX, time, x, ml, mu, jacob, nrowpd); } Lsodar::Lsodar(OneStepIntegratorXML* osiXML, Simulation* newS): OneStepIntegrator("Lsodar", osiXML, newS), rtol(NULL), atol(NULL), rwork(NULL), iwork(NULL), jroot(NULL) { // local time discretisation is set by default to those of the simulation. intData.resize(9); sizeMem = 2; } Lsodar::Lsodar(DynamicalSystem* ds, Simulation* newS): OneStepIntegrator("Lsodar", newS), rtol(NULL), atol(NULL), rwork(NULL), iwork(NULL), jroot(NULL) { if (simulationLink == NULL) RuntimeException::selfThrow("Lsodar:: constructor(ds,simulation) - simulation == NULL"); // add ds in the set OSIDynamicalSystems->insert(ds); intData.resize(9); sizeMem = 2; } Lsodar::Lsodar(DynamicalSystemsSet& newDS, Simulation* newS): OneStepIntegrator("Lsodar", newDS, newS), rtol(NULL), atol(NULL), rwork(NULL), iwork(NULL), jroot(NULL) { if (simulationLink == NULL) RuntimeException::selfThrow("Lsodar:: constructor(DSSet,simulation) - simulation == NULL"); intData.resize(9); sizeMem = 2; } Lsodar::~Lsodar() { global_object = NULL; if (rtol != NULL) delete rtol; rtol = NULL; if (atol != NULL) delete atol; atol = NULL; if (rwork != NULL) delete rwork; rwork = NULL; if (iwork != NULL) delete iwork; iwork = NULL; if (xWork != NULL) delete xWork; } void Lsodar::setTol(integer newItol, doublereal* newRtol, doublereal* newAtol) { // The input parameters ITOL, RTOL, and ATOL determine // the error control performed by the solver. The solver will // control the vector E = (E(i)) of estimated local errors // in y, according to an inequality of the form // max-norm of ( E(i)/EWT(i) ) .le. 1, // where EWT = (EWT(i)) is a vector of positive error weights. // The values of RTOL and ATOL should all be non-negative. // The following table gives the types (scalar/array) of // RTOL and ATOL, and the corresponding form of EWT(i). // // ITOL RTOL ATOL EWT(i) // 1 scalar scalar RTOL*ABS(Y(i)) + ATOL // 2 scalar array RTOL*ABS(Y(i)) + ATOL(i) // 3 array scalar RTOL(i)*ABS(Y(i)) + ATOL // 4 array array RTOL(i)*ABS(Y(i)) + ATOL(i) intData[2] = newItol; // itol unsigned int sizeTol = intData[0]; // neq // Memory allocation ... if (rtol != NULL) delete rtol; rtol = new doublereal[sizeTol] ; // rtol, relative tolerance if (atol != NULL) delete atol; atol = new doublereal[sizeTol] ; // atol, absolute tolerance *rtol = *newRtol; *atol = *newAtol; } void Lsodar::updateData() { // Used to update some data (iwork ...) when intData is modified. // Warning: it only checks sizes and possibly reallocate memory, but no values are set. unsigned int sizeTol = intData[0]; // size of rtol, atol ... If itol (intData[0]) = 1 => scalar else, vector of size neq (intData[0]). // if(intData[0]==1) sizeTol = 1; // else sizeTol = intData[0]; if (rtol != NULL) delete rtol; rtol = new doublereal[sizeTol] ; // rtol, relative tolerance if (atol != NULL) delete atol; atol = new doublereal[sizeTol] ; // atol, absolute tolerance if (iwork != NULL) delete iwork; // iwork iwork = new integer[intData[7]]; if (rwork != NULL) delete rwork; // rwork rwork = new doublereal[intData[6]]; if (jroot != NULL) delete jroot; // jroot jroot = new integer[intData[1]]; } void Lsodar::fillXWork(integer* sizeOfX, doublereal * x) { unsigned int sizeX = (unsigned int)(*sizeOfX); for (unsigned int i = 0; i < sizeX ; ++i) (*xWork)(i) = x[i]; } void Lsodar::computeRhs(double t) { DSIterator it; for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) (*it)->computeRhs(t); } void Lsodar::computeJacobianRhs(double t) { DSIterator it; for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) (*it)->computeJacobianXRhs(t); } void Lsodar::f(integer * sizeOfX, doublereal * time, doublereal * x, doublereal * xdot) { static_cast<EventDriven*>(simulationLink)->computeF(this, sizeOfX, time, x, xdot); } void Lsodar::g(integer * nEq, doublereal * time, doublereal* x, integer * ng, doublereal * gOut) { static_cast<EventDriven*>(simulationLink)->computeG(this, nEq, time, x, ng, gOut); } void Lsodar::jacobianF(integer *sizeOfX, doublereal *time, doublereal *x, integer* ml, integer *mu, doublereal *jacob, integer *nrowpd) { static_cast<EventDriven*>(simulationLink)->computeJacobianF(this, sizeOfX, time, x, jacob); } void Lsodar::initialize() { OneStepIntegrator::initialize(); xWork = new BlockVector(); DSIterator it; string type; // initialize xWork with x values of the dynamical systems present in the set. for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) xWork->insertPtr((*it)->getXPtr()); // Integer parameters for LSODAR are saved in vector intParam. // The link with variable names in opkdmain.f is indicated in comments // 1 - Neq; x vector size. intData[0] = xWork->size(); // 2 - Ng, number of constraints: intData[1] = simulationLink->getModelPtr()->getNonSmoothDynamicalSystemPtr()->getTopologyPtr()->getNumberOfConstraints(); // 3 - Itol, itask, iopt intData[2] = 1; // itol, 1 if ATOL is a scalar, else 2 (ATOL array) intData[3] = 1; // itask, an index specifying the task to be performed. 1: normal computation. intData[5] = 0; // iopt: 0 if no optional input else 1. // 4 - Istate intData[4] = 1; // istate, an index used for input and output to specify the state of the calculation. // On input: // 1: first call for the problem (initializations will be done). // 2: means this is not the first call, and the calculation is to continue normally, with no change in any input // parameters except possibly TOUT and ITASK. // 3: means this is not the first call, and the calculation is to continue normally, but with // a change in input parameters other than TOUT and ITASK. // On output: // 1: means nothing was done; TOUT = t and ISTATE = 1 on input. // 2: means the integration was performed successfully, and no roots were found. // 3: means the integration was successful, and one or more roots were found before satisfying the stop condition specified by ITASK. See JROOT. // <0: error. See table below, in integrate function output message. // 5 - lrw, size of rwork intData[6] = 22 + intData[0] * max(16, (int)intData[0] + 9) + 3 * intData[1]; // 6 - liw, size of iwork intData[7] = 20 + intData[0]; // 7 - JT, Jacobian type indicator intData[8] = 2; // jt, Jacobian type indicator. // 1 means a user-supplied full (NEQ by NEQ) Jacobian. // 2 means an internally generated (difference quotient) full Jacobian (using NEQ extra calls to f per df/dx value). // 4 means a user-supplied banded Jacobian. // 5 means an internally generated banded Jacobian (using ML+MU+1 extra calls to f per df/dx evaluation). // memory allocation for doublereal*, according to intData values ... updateData(); // Set atol and rtol values ... rtol[0] = MACHINE_PREC; // rtol atol[0] = MACHINE_PREC; // atol // === Error handling in LSODAR=== // parameters: itol, rtol, atol. // Control vector E = (E(i)) of estimated local errors in y: // max-norm of ( E(i)/EWT(i) )< 1 // EWT = (EWT(i)) vector of positive error weights. // The values of RTOL and ATOL should all be non-negative. // // ITOL RTOL ATOL EWT(i) // 1 scalar scalar RTOL*ABS(Y(i)) + ATOL // 2 scalar array RTOL*ABS(Y(i)) + ATOL(i) // 3 array scalar RTOL(i)*ABS(Y(i)) + ATOL // 4 array array RTOL(i)*ABS(Y(i)) + ATOL(i) } void Lsodar::integrate(double& tinit, double& tend, double& tout, int& istate) { // For details on DLSODAR parameters, see opkdmain.f in Numerics/src/odepack doublereal tend_DR = tend ; // next point where output is desired (different from t!) doublereal tinit_DR = tinit; // current (starting) time // === Pointers to function === // --> definition and initialisation thanks to wrapper: global_object = this; // Warning: global object must be initialized to current one before pointers to function initialisation. // function to compute the righ-hand side of xdot = f(x,t) + Tu fpointer pointerToF = Lsodar_f_wrapper; // function to compute the Jacobian/x of the rhs. jacopointer pointerToJacobianF = Lsodar_jacobianF_wrapper; // function to compute the Jacobian/x of the rhs. // function to compute the constraints gpointer pointerToG; pointerToG = Lsodar_g_wrapper; // function to compute the constraints // === LSODAR CALL === SimpleVector * xtmp = new SimpleVector(*xWork); // A copy of xWork is required since at the time, there are no contiguous values in memory for BlockVectors. if (istate == 3) { istate = 1; // restart TEMPORARY } intData[4] = istate; F77NAME(dlsodar)(pointerToF, &(intData[0]), &(*xtmp)(0), &tinit_DR, &tend_DR, &(intData[2]), rtol, atol, &(intData[3]), &(intData[4]), &(intData[5]), rwork, &(intData[6]), iwork, &(intData[7]), pointerToJacobianF, &(intData[8]), pointerToG, &(intData[1]), jroot); // jroot: jroot[i] = 0 if g(i) has a root at t, else jroot[i] = 0. // === Post === if (intData[4] < 0) // if istate < 0 => LSODAR failed { cout << "LSodar::integrate(...) failed - Istate = " << intData[4] << endl; cout << " -1 means excess work done on this call (perhaps wrong JT)." << endl; cout << " -2 means excess accuracy requested (tolerances too small)." << endl; cout << " -3 means illegal input detected (see printed message)." << endl; cout << " -4 means repeated error test failures (check all inputs)." << endl; cout << " -5 means repeated convergence failures (perhaps bad Jacobian supplied or wrong choice of JT or tolerances)." << endl; cout << " -6 means error weight became zero during problem. (Solution component i vanished, and ATOL or ATOL(i) = 0.)" << endl; cout << " -7 means work space insufficient to finish (see messages)." << endl; RuntimeException::selfThrow("Lsodar, integration failed"); } *xWork = *xtmp; delete xtmp; istate = intData[4]; tout = tinit_DR; // real ouput time tend = tend_DR; // necessary for next start of DLSODAR // tinit = tinit_DR; } void Lsodar::updateState(unsigned int level) { // Compute all required (ie time-dependent) data for the DS of the OSI. DSIterator it; if (level == 1) // ie impact case: compute velocity { for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) { LagrangianDS* lds = static_cast<LagrangianDS*>(*it); lds->computePostImpactVelocity(); } } else if (level == 2)// compute acceleration ie RHS and its jacobian. { double time = simulationLink->getModelPtr()->getCurrentTime(); for (it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it) (*it)->update(time); } else RuntimeException::selfThrow("Lsodar::updateState(index), index is out of range. Index = " + level); } void Lsodar::display() { OneStepIntegrator::display(); cout << " --- > Lsodar specific values: " << endl; cout << "Number of equations: " << intData[0] << endl; cout << "Number of constraints: " << intData[1] << endl; cout << "itol, itask, istate, iopt, lrw, liw, jt: (for details on what are these variables see opkdmain.f)" << endl; cout << intData[2] << ", " << intData[3] << ", " << intData[4] << ", " << intData[5] << ", " << intData[6] << ", " << intData[7] << ", " << intData[8] << endl; cout << "====================================" << endl; }
#define DeutSelector_cxx // The class definition in DeutSelector.h has been generated automatically // by the ROOT utility TTree::MakeSelector(). This class is derived // from the ROOT class TSelector. For more information on the TSelector // framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual. // The following methods are defined in this file: // Begin(): called every time a loop on the tree starts, // a convenient place to create your histograms. // SlaveBegin(): called after Begin(), when on PROOF called only on the // slave servers. // Process(): called for each event, in this function you decide what // to read and fill your histograms. // SlaveTerminate: called at the end of the loop on the tree, when on PROOF // called only on the slave servers. // Terminate(): called at the end of the loop on the tree, // a convenient place to draw/fit your histograms. // // To use this file, try the following session on your Tree T: // // Root > T->Process("DeutSelector.C") // Root > T->Process("DeutSelector.C","some options") // Root > T->Process("DeutSelector.C+") // #include "DeutSelector.h" #include <TH2.h> #include <TH2F.h> #include <TH1D.h> #include <TStyle.h> #include <Riostream.h> #include <TMath.h> #include <TCanvas.h> #include <TAxis.h> #include <TF1.h> #define EPSILON 1E-5 static void BinLogAxis(const TH1 *h) { // // Method for the correct logarithmic binning of histograms // TAxis *axis = const_cast<TAxis*>(h->GetXaxis()); const Int_t bins = axis->GetNbins(); const Double_t from = axis->GetXmin(); const Double_t to = axis->GetXmax(); Double_t *newBins = new Double_t[bins + 1]; newBins[0] = from; Double_t factor = pow(to / from, 1. / bins); for (Int_t i = 1; i <= bins; i++) { newBins[i] = factor * newBins[i - 1]; } axis->Set(bins, newBins); delete [] newBins; } Double_t BetheBlochAleph(Double_t bg, Double_t kp1, Double_t kp2, Double_t kp3, Double_t kp4, Double_t kp5) { Double_t beta = bg/TMath::Sqrt(1.+ bg*bg); Double_t aa = TMath::Power(beta,kp4); Double_t bb = TMath::Power(1./bg,kp5); bb=TMath::Log(kp3+bb); return (kp2-aa-bb)*kp1/aa; } Double_t DeuteronTPC(Double_t *x,Double_t *par) { // Deuteron expected signal in TPC // Double_t fAlephParameters[5]; // fAlephParameters[0] = 0.0283086; // fAlephParameters[1] = 2.63394e+01; // fAlephParameters[2] = 5.04114e-11; // fAlephParameters[3] = 2.12543e+00; // fAlephParameters[4] = 4.88663e+00; // 1.45802,27.4992,4.00313e-15,2.48485,8.31768 return BetheBlochAleph(x[0] / 1.876,1.45802,27.4992,4.00313e-15,2.48485,8.31768); //return BetheBlochAleph(x[0] / 1.876,fAlephParameters[0],fAlephParameters[1],fAlephParameters[2],fAlephParameters[3],fAlephParameters[4]); } void DeutSelector::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); } void DeutSelector::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); fBeta = new TH1D("fBeta",";#beta;Entries",100,0.f,1.f); fGamma = new TH1D("fGamma",";#gamma;Entries",1000,1.f,1000.f); fdEdxTPC = new TH2F("fdEdxTPC",";p (GeV/c);dE/dx (a.u.)",500,0.1,5.,1000,0,2000); fdEdxTPCSignal = new TH2F("fdEdxTPCSignal",";p (GeV/c);dE/dx (a.u.)",500,0.1,5.,2000,0,2000); fdEdxTPCproj = new TH2F("fdEdxTPCproj",";p (GeV/c);dE/dx (a.u.)",93,0.4,3.2,2000,0,2000); BinLogAxis(fdEdxTPC); fSignal = new TH1D("fSignal",";",600,0.1,6.1); GetOutputList()->Add(fdEdxTPC); GetOutputList()->Add(fdEdxTPCSignal); GetOutputList()->Add(fdEdxTPCproj); GetOutputList()->Add(fSignal); GetOutputList()->Add(fBeta); GetOutputList()->Add(fGamma); } Bool_t DeutSelector::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either DeutSelector::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. GetEntry(entry); fdEdxTPC->Fill(pTPC,TPCsignal); fdEdxTPCproj->Fill(pTPC,TPCsignal); if (TOFtime > 0.f && length > 0.f) { Float_t beta = length / (2.99792457999999984e-02 * TOFtime); fBeta->Fill(beta); if (beta < (1.f - EPSILON)) { Float_t gamma = 1 / TMath::Sqrt(1 - (beta * beta)); fGamma->Fill(gamma); fSignal->Fill(p / (beta * gamma)); if (p / (beta * gamma) > 1.5f ) { fdEdxTPCSignal->Fill(pTPC,TPCsignal); } } } return kTRUE; } void DeutSelector::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } void DeutSelector::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. TFile f("final.root","recreate"); TF1 fbb("BBAleph",DeuteronTPC,0.4f,5.f,0); TCanvas c; fdEdxTPC = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPC")); if (fdEdxTPC) { c.cd(); fdEdxTPC->DrawClone(); fbb.DrawClone("same"); f.cd(); c.Write(); fdEdxTPC->Write(); } fdEdxTPCSignal = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPCSignal")); if (fdEdxTPCSignal) { fdEdxTPCSignal->Write(); } fdEdxTPCproj = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPCproj")); if (fdEdxTPCproj) { fdEdxTPCproj->Write(); } fBeta = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fBeta")); if (fBeta) { fBeta->Write(); } fGamma = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fGamma")); if (fGamma) { fGamma->Write(); } fSignal = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fSignal")); if (fSignal) { fSignal->Write(); } f.Close(); } Further rebinding #define DeutSelector_cxx // The class definition in DeutSelector.h has been generated automatically // by the ROOT utility TTree::MakeSelector(). This class is derived // from the ROOT class TSelector. For more information on the TSelector // framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual. // The following methods are defined in this file: // Begin(): called every time a loop on the tree starts, // a convenient place to create your histograms. // SlaveBegin(): called after Begin(), when on PROOF called only on the // slave servers. // Process(): called for each event, in this function you decide what // to read and fill your histograms. // SlaveTerminate: called at the end of the loop on the tree, when on PROOF // called only on the slave servers. // Terminate(): called at the end of the loop on the tree, // a convenient place to draw/fit your histograms. // // To use this file, try the following session on your Tree T: // // Root > T->Process("DeutSelector.C") // Root > T->Process("DeutSelector.C","some options") // Root > T->Process("DeutSelector.C+") // #include "DeutSelector.h" #include <TH2.h> #include <TH2F.h> #include <TH1D.h> #include <TStyle.h> #include <Riostream.h> #include <TMath.h> #include <TCanvas.h> #include <TAxis.h> #include <TF1.h> #define EPSILON 1E-5 static void BinLogAxis(const TH1 *h) { // // Method for the correct logarithmic binning of histograms // TAxis *axis = const_cast<TAxis*>(h->GetXaxis()); const Int_t bins = axis->GetNbins(); const Double_t from = axis->GetXmin(); const Double_t to = axis->GetXmax(); Double_t *newBins = new Double_t[bins + 1]; newBins[0] = from; Double_t factor = pow(to / from, 1. / bins); for (Int_t i = 1; i <= bins; i++) { newBins[i] = factor * newBins[i - 1]; } axis->Set(bins, newBins); delete [] newBins; } Double_t BetheBlochAleph(Double_t bg, Double_t kp1, Double_t kp2, Double_t kp3, Double_t kp4, Double_t kp5) { Double_t beta = bg/TMath::Sqrt(1.+ bg*bg); Double_t aa = TMath::Power(beta,kp4); Double_t bb = TMath::Power(1./bg,kp5); bb=TMath::Log(kp3+bb); return (kp2-aa-bb)*kp1/aa; } Double_t DeuteronTPC(Double_t *x,Double_t *par) { // Deuteron expected signal in TPC // Double_t fAlephParameters[5]; // fAlephParameters[0] = 0.0283086; // fAlephParameters[1] = 2.63394e+01; // fAlephParameters[2] = 5.04114e-11; // fAlephParameters[3] = 2.12543e+00; // fAlephParameters[4] = 4.88663e+00; // 1.45802,27.4992,4.00313e-15,2.48485,8.31768 return BetheBlochAleph(x[0] / 1.876,1.45802,27.4992,4.00313e-15,2.48485,8.31768); //return BetheBlochAleph(x[0] / 1.876,fAlephParameters[0],fAlephParameters[1],fAlephParameters[2],fAlephParameters[3],fAlephParameters[4]); } void DeutSelector::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); } void DeutSelector::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); fBeta = new TH1D("fBeta",";#beta;Entries",100,0.f,1.f); fGamma = new TH1D("fGamma",";#gamma;Entries",1000,1.f,1000.f); fdEdxTPC = new TH2F("fdEdxTPC",";p (GeV/c);dE/dx (a.u.)",500,0.1,5.,500,0,2000); fdEdxTPCSignal = new TH2F("fdEdxTPCSignal",";p (GeV/c);dE/dx (a.u.)",500,0.1,5.,2000,0,2000); fdEdxTPCproj = new TH2F("fdEdxTPCproj",";p (GeV/c);dE/dx (a.u.)",93,0.4,3.2,2000,0,2000); BinLogAxis(fdEdxTPC); fSignal = new TH1D("fSignal",";",600,0.1,6.1); GetOutputList()->Add(fdEdxTPC); GetOutputList()->Add(fdEdxTPCSignal); GetOutputList()->Add(fdEdxTPCproj); GetOutputList()->Add(fSignal); GetOutputList()->Add(fBeta); GetOutputList()->Add(fGamma); } Bool_t DeutSelector::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either DeutSelector::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. GetEntry(entry); fdEdxTPC->Fill(pTPC,TPCsignal); fdEdxTPCproj->Fill(pTPC,TPCsignal); if (TOFtime > 0.f && length > 0.f) { Float_t beta = length / (2.99792457999999984e-02 * TOFtime); fBeta->Fill(beta); if (beta < (1.f - EPSILON)) { Float_t gamma = 1 / TMath::Sqrt(1 - (beta * beta)); fGamma->Fill(gamma); fSignal->Fill(p / (beta * gamma)); if (p / (beta * gamma) > 1.5f ) { fdEdxTPCSignal->Fill(pTPC,TPCsignal); } } } return kTRUE; } void DeutSelector::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } void DeutSelector::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. TFile f("final.root","recreate"); TF1 fbb("BBAleph",DeuteronTPC,0.4f,5.f,0); TCanvas c; fdEdxTPC = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPC")); if (fdEdxTPC) { c.cd(); fdEdxTPC->DrawClone(); fbb.DrawClone("same"); f.cd(); c.Write(); fdEdxTPC->Write(); } fdEdxTPCSignal = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPCSignal")); if (fdEdxTPCSignal) { fdEdxTPCSignal->Write(); } fdEdxTPCproj = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPCproj")); if (fdEdxTPCproj) { fdEdxTPCproj->Write(); } fBeta = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fBeta")); if (fBeta) { fBeta->Write(); } fGamma = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fGamma")); if (fGamma) { fGamma->Write(); } fSignal = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fSignal")); if (fSignal) { fSignal->Write(); } f.Close(); }
//===- Writer.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Writer.h" #include "Config.h" #include "OutputSections.h" #include "SymbolTable.h" #include "Target.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/StringSaver.h" using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; using namespace lld; using namespace lld::elf2; namespace { // The writer writes a SymbolTable result to a file. template <class ELFT> class Writer { public: typedef typename ELFFile<ELFT>::uintX_t uintX_t; typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr; typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr; typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr; typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range; typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela; Writer(SymbolTable<ELFT> &S) : Symtab(S) {} void run(); private: void copyLocalSymbols(); void createSections(); template <bool isRela> void scanRelocs(InputSectionBase<ELFT> &C, iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels); void scanRelocs(InputSection<ELFT> &C); void scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec); void updateRelro(Elf_Phdr *Cur, Elf_Phdr *GnuRelroPhdr, uintX_t VA); void assignAddresses(); void buildSectionMap(); void openFile(StringRef OutputPath); void writeHeader(); void writeSections(); bool isDiscarded(InputSectionBase<ELFT> *IS) const; StringRef getOutputSectionName(StringRef S) const; bool needsInterpSection() const { return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty(); } bool isOutputDynamic() const { return !Symtab.getSharedFiles().empty() || Config->Shared; } int getPhdrsNum() const; OutputSection<ELFT> *getBSS(); void addCommonSymbols(std::vector<DefinedCommon *> &Syms); void addSharedCopySymbols(std::vector<SharedSymbol<ELFT> *> &Syms); std::unique_ptr<llvm::FileOutputBuffer> Buffer; SpecificBumpPtrAllocator<OutputSection<ELFT>> SecAlloc; SpecificBumpPtrAllocator<MergeOutputSection<ELFT>> MSecAlloc; SpecificBumpPtrAllocator<EHOutputSection<ELFT>> EHSecAlloc; SpecificBumpPtrAllocator<MipsReginfoOutputSection<ELFT>> MReginfoSecAlloc; BumpPtrAllocator Alloc; std::vector<OutputSectionBase<ELFT> *> OutputSections; unsigned getNumSections() const { return OutputSections.size() + 1; } void addStartStopSymbols(OutputSectionBase<ELFT> *Sec); void setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, uintX_t FileOff, uintX_t VA, uintX_t Size, uintX_t Align); void copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From); bool HasRelro = false; SymbolTable<ELFT> &Symtab; std::vector<Elf_Phdr> Phdrs; uintX_t FileSize; uintX_t SectionHeaderOff; llvm::StringMap<llvm::StringRef> InputToOutputSection; }; } // anonymous namespace template <class ELFT> static bool shouldUseRela() { ELFKind K = cast<ELFFileBase<ELFT>>(Config->FirstElf)->getELFKind(); return K == ELF64LEKind || K == ELF64BEKind; } template <class ELFT> void lld::elf2::writeResult(SymbolTable<ELFT> *Symtab) { // Initialize output sections that are handled by Writer specially. // Don't reorder because the order of initialization matters. InterpSection<ELFT> Interp; Out<ELFT>::Interp = &Interp; StringTableSection<ELFT> ShStrTab(".shstrtab", false); Out<ELFT>::ShStrTab = &ShStrTab; StringTableSection<ELFT> StrTab(".strtab", false); if (!Config->StripAll) Out<ELFT>::StrTab = &StrTab; StringTableSection<ELFT> DynStrTab(".dynstr", true); Out<ELFT>::DynStrTab = &DynStrTab; GotSection<ELFT> Got; Out<ELFT>::Got = &Got; GotPltSection<ELFT> GotPlt; if (Target->supportsLazyRelocations()) Out<ELFT>::GotPlt = &GotPlt; PltSection<ELFT> Plt; Out<ELFT>::Plt = &Plt; std::unique_ptr<SymbolTableSection<ELFT>> SymTab; if (!Config->StripAll) { SymTab.reset(new SymbolTableSection<ELFT>(*Symtab, *Out<ELFT>::StrTab)); Out<ELFT>::SymTab = SymTab.get(); } SymbolTableSection<ELFT> DynSymTab(*Symtab, *Out<ELFT>::DynStrTab); Out<ELFT>::DynSymTab = &DynSymTab; HashTableSection<ELFT> HashTab; if (Config->SysvHash) Out<ELFT>::HashTab = &HashTab; GnuHashTableSection<ELFT> GnuHashTab; if (Config->GnuHash) Out<ELFT>::GnuHashTab = &GnuHashTab; bool IsRela = shouldUseRela<ELFT>(); RelocationSection<ELFT> RelaDyn(IsRela ? ".rela.dyn" : ".rel.dyn", IsRela); Out<ELFT>::RelaDyn = &RelaDyn; RelocationSection<ELFT> RelaPlt(IsRela ? ".rela.plt" : ".rel.plt", IsRela); if (Target->supportsLazyRelocations()) Out<ELFT>::RelaPlt = &RelaPlt; DynamicSection<ELFT> Dynamic(*Symtab); Out<ELFT>::Dynamic = &Dynamic; Writer<ELFT>(*Symtab).run(); } // The main function of the writer. template <class ELFT> void Writer<ELFT>::run() { buildSectionMap(); if (!Config->DiscardAll) copyLocalSymbols(); createSections(); assignAddresses(); openFile(Config->OutputFile); writeHeader(); writeSections(); error(Buffer->commit()); } namespace { template <bool Is64Bits> struct SectionKey { typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t; StringRef Name; uint32_t Type; uintX_t Flags; uintX_t EntSize; }; } namespace llvm { template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> { static SectionKey<Is64Bits> getEmptyKey() { return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0, 0}; } static SectionKey<Is64Bits> getTombstoneKey() { return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0, 0}; } static unsigned getHashValue(const SectionKey<Is64Bits> &Val) { return hash_combine(Val.Name, Val.Type, Val.Flags, Val.EntSize); } static bool isEqual(const SectionKey<Is64Bits> &LHS, const SectionKey<Is64Bits> &RHS) { return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) && LHS.Type == RHS.Type && LHS.Flags == RHS.Flags && LHS.EntSize == RHS.EntSize; } }; } // The reason we have to do this early scan is as follows // * To mmap the output file, we need to know the size // * For that, we need to know how many dynamic relocs we will have. // It might be possible to avoid this by outputting the file with write: // * Write the allocated output sections, computing addresses. // * Apply relocations, recording which ones require a dynamic reloc. // * Write the dynamic relocations. // * Write the rest of the file. template <class ELFT> template <bool isRela> void Writer<ELFT>::scanRelocs( InputSectionBase<ELFT> &C, iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) { typedef Elf_Rel_Impl<ELFT, isRela> RelType; const ObjectFile<ELFT> &File = *C.getFile(); for (const RelType &RI : Rels) { uint32_t SymIndex = RI.getSymbol(Config->Mips64EL); SymbolBody *Body = File.getSymbolBody(SymIndex); uint32_t Type = RI.getType(Config->Mips64EL); if (Target->isGotRelative(Type)) HasGotOffRel = true; if (Target->isTlsLocalDynamicReloc(Type)) { if (Target->isTlsOptimized(Type, nullptr)) continue; if (Out<ELFT>::Got->addCurrentModuleTlsIndex()) Out<ELFT>::RelaDyn->addReloc({&C, &RI}); continue; } // Set "used" bit for --as-needed. if (Body && Body->isUndefined() && !Body->isWeak()) if (auto *S = dyn_cast<SharedSymbol<ELFT>>(Body->repl())) S->File->IsUsed = true; if (Body) Body = Body->repl(); if (Body && Body->isTls() && Target->isTlsGlobalDynamicReloc(Type)) { bool Opt = Target->isTlsOptimized(Type, Body); if (!Opt && Out<ELFT>::Got->addDynTlsEntry(Body)) { Out<ELFT>::RelaDyn->addReloc({&C, &RI}); Out<ELFT>::RelaDyn->addReloc({nullptr, nullptr}); Body->setUsedInDynamicReloc(); continue; } if (!canBePreempted(Body, true)) continue; } if (Body && Body->isTls() && !Target->isTlsDynReloc(Type, *Body)) continue; if (Target->relocNeedsDynRelative(Type)) { RelType *Rel = new (Alloc) RelType; Rel->setSymbolAndType(0, Target->getRelativeReloc(), Config->Mips64EL); Rel->r_offset = RI.r_offset; Out<ELFT>::RelaDyn->addReloc({&C, Rel}); } bool NeedsGot = false; bool NeedsPlt = false; if (Body) { if (auto *E = dyn_cast<SharedSymbol<ELFT>>(Body)) { if (E->NeedsCopy) continue; if (Target->needsCopyRel(Type, *Body)) E->NeedsCopy = true; } NeedsPlt = Target->relocNeedsPlt(Type, *Body); if (NeedsPlt) { if (Body->isInPlt()) continue; Out<ELFT>::Plt->addEntry(Body); } NeedsGot = Target->relocNeedsGot(Type, *Body); if (NeedsGot) { if (NeedsPlt && Target->supportsLazyRelocations()) { Out<ELFT>::GotPlt->addEntry(Body); } else { if (Body->isInGot()) continue; Out<ELFT>::Got->addEntry(Body); } } } // An STT_GNU_IFUNC symbol always uses a PLT entry, and all references // to the symbol go through the PLT. This is true even for a local // symbol, although local symbols normally do not require PLT entries. if (Body && isGnuIFunc<ELFT>(*Body)) { Body->setUsedInDynamicReloc(); Out<ELFT>::RelaPlt->addReloc({&C, &RI}); continue; } if (Config->EMachine == EM_MIPS && NeedsGot) { // MIPS ABI has special rules to process GOT entries // and doesn't require relocation entries for them. // See "Global Offset Table" in Chapter 5 in the following document // for detailed description: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf Body->setUsedInDynamicReloc(); continue; } bool CBP = canBePreempted(Body, NeedsGot); if (!CBP && (!Config->Shared || Target->isRelRelative(Type))) continue; if (CBP) Body->setUsedInDynamicReloc(); if (NeedsPlt && Target->supportsLazyRelocations()) Out<ELFT>::RelaPlt->addReloc({&C, &RI}); else Out<ELFT>::RelaDyn->addReloc({&C, &RI}); } } template <class ELFT> void Writer<ELFT>::scanRelocs(InputSection<ELFT> &C) { if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC)) return; for (const Elf_Shdr *RelSec : C.RelocSections) scanRelocs(C, *RelSec); } template <class ELFT> void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec) { ELFFile<ELFT> &EObj = S.getFile()->getObj(); if (RelSec.sh_type == SHT_RELA) scanRelocs(S, EObj.relas(&RelSec)); else scanRelocs(S, EObj.rels(&RelSec)); } template <class ELFT> static void reportUndefined(const SymbolTable<ELFT> &S, const SymbolBody &Sym) { if (Config->Shared && !Config->NoUndefined) return; ELFFileBase<ELFT> *SymFile = findFile<ELFT>(S.getObjectFiles(), &Sym); std::string Message = "undefined symbol: " + Sym.getName().str(); if (SymFile) Message += " in " + SymFile->getName().str(); if (Config->NoInhibitExec) warning(Message); else error(Message); } // Local symbols are not in the linker's symbol table. This function scans // each object file's symbol table to copy local symbols to the output. template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { for (const Elf_Sym &Sym : F->getLocalSymbols()) { ErrorOr<StringRef> SymNameOrErr = Sym.getName(F->getStringTable()); error(SymNameOrErr); StringRef SymName = *SymNameOrErr; if (!shouldKeepInSymtab<ELFT>(*F, SymName, Sym)) continue; if (Out<ELFT>::SymTab) Out<ELFT>::SymTab->addLocalSymbol(SymName); } } } // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that // we would like to make sure appear is a specific order to maximize their // coverage by a single signed 16-bit offset from the TOC base pointer. // Conversely, the special .tocbss section should be first among all SHT_NOBITS // sections. This will put it next to the loaded special PPC64 sections (and, // thus, within reach of the TOC base pointer). static int getPPC64SectionRank(StringRef SectionName) { return StringSwitch<int>(SectionName) .Case(".tocbss", 0) .Case(".branch_lt", 2) .Case(".toc", 3) .Case(".toc1", 4) .Case(".opd", 5) .Default(1); } template <class ELFT> static bool isRelroSection(OutputSectionBase<ELFT> *Sec) { typename OutputSectionBase<ELFT>::uintX_t Flags = Sec->getFlags(); if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE)) return false; if (Flags & SHF_TLS) return true; uint32_t Type = Sec->getType(); if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY || Type == SHT_PREINIT_ARRAY) return true; if (Sec == Out<ELFT>::GotPlt) return Config->ZNow; if (Sec == Out<ELFT>::Dynamic || Sec == Out<ELFT>::Got) return true; StringRef S = Sec->getName(); return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" || S == ".eh_frame"; } // Output section ordering is determined by this function. template <class ELFT> static bool compareOutputSections(OutputSectionBase<ELFT> *A, OutputSectionBase<ELFT> *B) { typedef typename ELFFile<ELFT>::uintX_t uintX_t; uintX_t AFlags = A->getFlags(); uintX_t BFlags = B->getFlags(); // Allocatable sections go first to reduce the total PT_LOAD size and // so debug info doesn't change addresses in actual code. bool AIsAlloc = AFlags & SHF_ALLOC; bool BIsAlloc = BFlags & SHF_ALLOC; if (AIsAlloc != BIsAlloc) return AIsAlloc; // We don't have any special requirements for the relative order of // two non allocatable sections. if (!AIsAlloc) return false; // We want the read only sections first so that they go in the PT_LOAD // covering the program headers at the start of the file. bool AIsWritable = AFlags & SHF_WRITE; bool BIsWritable = BFlags & SHF_WRITE; if (AIsWritable != BIsWritable) return BIsWritable; // For a corresponding reason, put non exec sections first (the program // header PT_LOAD is not executable). bool AIsExec = AFlags & SHF_EXECINSTR; bool BIsExec = BFlags & SHF_EXECINSTR; if (AIsExec != BIsExec) return BIsExec; // If we got here we know that both A and B are in the same PT_LOAD. // The TLS initialization block needs to be a single contiguous block in a R/W // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS // sections are placed here as they don't take up virtual address space in the // PT_LOAD. bool AIsTls = AFlags & SHF_TLS; bool BIsTls = BFlags & SHF_TLS; if (AIsTls != BIsTls) return AIsTls; // The next requirement we have is to put nobits sections last. The // reason is that the only thing the dynamic linker will see about // them is a p_memsz that is larger than p_filesz. Seeing that it // zeros the end of the PT_LOAD, so that has to correspond to the // nobits sections. bool AIsNoBits = A->getType() == SHT_NOBITS; bool BIsNoBits = B->getType() == SHT_NOBITS; if (AIsNoBits != BIsNoBits) return BIsNoBits; // We place RelRo section before plain r/w ones. bool AIsRelRo = isRelroSection(A); bool BIsRelRo = isRelroSection(B); if (AIsRelRo != BIsRelRo) return AIsRelRo; // Some architectures have additional ordering restrictions for sections // within the same PT_LOAD. if (Config->EMachine == EM_PPC64) return getPPC64SectionRank(A->getName()) < getPPC64SectionRank(B->getName()); return false; } template <class ELFT> OutputSection<ELFT> *Writer<ELFT>::getBSS() { if (!Out<ELFT>::Bss) { Out<ELFT>::Bss = new (SecAlloc.Allocate()) OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE); OutputSections.push_back(Out<ELFT>::Bss); } return Out<ELFT>::Bss; } // Until this function is called, common symbols do not belong to any section. // This function adds them to end of BSS section. template <class ELFT> void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon *> &Syms) { typedef typename ELFFile<ELFT>::uintX_t uintX_t; if (Syms.empty()) return; // Sort the common symbols by alignment as an heuristic to pack them better. std::stable_sort(Syms.begin(), Syms.end(), [](const DefinedCommon *A, const DefinedCommon *B) { return A->MaxAlignment > B->MaxAlignment; }); uintX_t Off = getBSS()->getSize(); for (DefinedCommon *C : Syms) { uintX_t Align = C->MaxAlignment; Off = RoundUpToAlignment(Off, Align); C->OffsetInBSS = Off; Off += C->Size; } Out<ELFT>::Bss->setSize(Off); } template <class ELFT> void Writer<ELFT>::addSharedCopySymbols( std::vector<SharedSymbol<ELFT> *> &Syms) { typedef typename ELFFile<ELFT>::uintX_t uintX_t; typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr; if (Syms.empty()) return; uintX_t Off = getBSS()->getSize(); for (SharedSymbol<ELFT> *C : Syms) { const Elf_Sym &Sym = C->Sym; const Elf_Shdr *Sec = C->File->getSection(Sym); uintX_t SecAlign = Sec->sh_addralign; unsigned TrailingZeros = std::min(countTrailingZeros(SecAlign), countTrailingZeros((uintX_t)Sym.st_value)); uintX_t Align = 1 << TrailingZeros; Out<ELFT>::Bss->updateAlign(Align); Off = RoundUpToAlignment(Off, Align); C->OffsetInBSS = Off; Off += Sym.st_size; } Out<ELFT>::Bss->setSize(Off); } template <class ELFT> StringRef Writer<ELFT>::getOutputSectionName(StringRef S) const { auto It = InputToOutputSection.find(S); if (It != std::end(InputToOutputSection)) return It->second; if (S.startswith(".text.")) return ".text"; if (S.startswith(".rodata.")) return ".rodata"; if (S.startswith(".data.rel.ro")) return ".data.rel.ro"; if (S.startswith(".data.")) return ".data"; if (S.startswith(".bss.")) return ".bss"; return S; } template <class ELFT> void reportDiscarded(InputSectionBase<ELFT> *IS, const std::unique_ptr<ObjectFile<ELFT>> &File) { if (!Config->PrintGcSections || !IS || IS->isLive()) return; llvm::errs() << "removing unused section from '" << IS->getSectionName() << "' in file '" << File->getName() << "'\n"; } template <class ELFT> bool Writer<ELFT>::isDiscarded(InputSectionBase<ELFT> *IS) const { if (!IS || !IS->isLive() || IS == &InputSection<ELFT>::Discarded) return true; return InputToOutputSection.lookup(IS->getSectionName()) == "/DISCARD/"; } template <class ELFT> static bool compareSections(OutputSectionBase<ELFT> *A, OutputSectionBase<ELFT> *B) { auto ItA = Config->OutputSections.find(A->getName()); auto ItEnd = std::end(Config->OutputSections); if (ItA == ItEnd) return compareOutputSections(A, B); auto ItB = Config->OutputSections.find(B->getName()); if (ItB == ItEnd) return compareOutputSections(A, B); return std::distance(ItA, ItB) > 0; } // A statically linked executable will have rel[a].plt section // to hold R_[*]_IRELATIVE relocations. // The multi-arch libc will use these symbols to locate // these relocations at program startup time. // If RelaPlt is empty then there is no reason to create this symbols. template <class ELFT> static void addIRelocMarkers(SymbolTable<ELFT> &Symtab, bool IsDynamic) { if (IsDynamic || !Out<ELFT>::RelaPlt || !Out<ELFT>::RelaPlt->hasRelocs()) return; bool IsRela = shouldUseRela<ELFT>(); auto AddMarker = [&](StringRef Name, typename Writer<ELFT>::Elf_Sym &Sym) { if (SymbolBody *B = Symtab.find(Name)) if (B->isUndefined()) Symtab.addAbsolute(Name, Sym); }; AddMarker(IsRela ? "__rela_iplt_start" : "__rel_iplt_start", ElfSym<ELFT>::RelaIpltStart); AddMarker(IsRela ? "__rela_iplt_end" : "__rel_iplt_end", ElfSym<ELFT>::RelaIpltEnd); } template <class ELFT> static bool includeInSymtab(const SymbolBody &B) { if (!B.isUsedInRegularObj()) return false; // Don't include synthetic symbols like __init_array_start in every output. if (auto *U = dyn_cast<DefinedRegular<ELFT>>(&B)) if (&U->Sym == &ElfSym<ELFT>::IgnoreUndef) return false; return true; } static bool includeInDynamicSymtab(const SymbolBody &B) { uint8_t V = B.getVisibility(); if (V != STV_DEFAULT && V != STV_PROTECTED) return false; if (Config->ExportDynamic || Config->Shared) return true; return B.isUsedInDynamicReloc(); } // Create output section objects and add them to OutputSections. template <class ELFT> void Writer<ELFT>::createSections() { // .interp needs to be on the first page in the output file. if (needsInterpSection()) OutputSections.push_back(Out<ELFT>::Interp); SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map; std::vector<OutputSectionBase<ELFT> *> RegularSections; for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { for (InputSectionBase<ELFT> *C : F->getSections()) { if (isDiscarded(C)) { reportDiscarded(C, F); continue; } const Elf_Shdr *H = C->getSectionHdr(); uintX_t OutFlags = H->sh_flags & ~SHF_GROUP; // For SHF_MERGE we create different output sections for each sh_entsize. // This makes each output section simple and keeps a single level // mapping from input to output. typename InputSectionBase<ELFT>::Kind K = C->SectionKind; uintX_t EntSize = K != InputSectionBase<ELFT>::Merge ? 0 : H->sh_entsize; uint32_t OutType = H->sh_type; if (OutType == SHT_PROGBITS && C->getSectionName() == ".eh_frame" && Config->EMachine == EM_X86_64) OutType = SHT_X86_64_UNWIND; SectionKey<ELFT::Is64Bits> Key{getOutputSectionName(C->getSectionName()), OutType, OutFlags, EntSize}; OutputSectionBase<ELFT> *&Sec = Map[Key]; if (!Sec) { switch (K) { case InputSectionBase<ELFT>::Regular: Sec = new (SecAlloc.Allocate()) OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags); break; case InputSectionBase<ELFT>::EHFrame: Sec = new (EHSecAlloc.Allocate()) EHOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags); break; case InputSectionBase<ELFT>::Merge: Sec = new (MSecAlloc.Allocate()) MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags); break; case InputSectionBase<ELFT>::MipsReginfo: Sec = new (MReginfoSecAlloc.Allocate()) MipsReginfoOutputSection<ELFT>(); break; } OutputSections.push_back(Sec); RegularSections.push_back(Sec); } switch (K) { case InputSectionBase<ELFT>::Regular: static_cast<OutputSection<ELFT> *>(Sec) ->addSection(cast<InputSection<ELFT>>(C)); break; case InputSectionBase<ELFT>::EHFrame: static_cast<EHOutputSection<ELFT> *>(Sec) ->addSection(cast<EHInputSection<ELFT>>(C)); break; case InputSectionBase<ELFT>::Merge: static_cast<MergeOutputSection<ELFT> *>(Sec) ->addSection(cast<MergeInputSection<ELFT>>(C)); break; case InputSectionBase<ELFT>::MipsReginfo: static_cast<MipsReginfoOutputSection<ELFT> *>(Sec) ->addSection(cast<MipsReginfoInputSection<ELFT>>(C)); break; } } } Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>( Map[{".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE, 0}]); Out<ELFT>::Dynamic->PreInitArraySec = Map.lookup( {".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); Out<ELFT>::Dynamic->InitArraySec = Map.lookup({".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); Out<ELFT>::Dynamic->FiniArraySec = Map.lookup({".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); auto AddStartEnd = [&](StringRef Start, StringRef End, OutputSectionBase<ELFT> *OS) { if (OS) { Symtab.addSynthetic(Start, *OS, 0); Symtab.addSynthetic(End, *OS, OS->getSize()); } else { Symtab.addIgnored(Start); Symtab.addIgnored(End); } }; AddStartEnd("__preinit_array_start", "__preinit_array_end", Out<ELFT>::Dynamic->PreInitArraySec); AddStartEnd("__init_array_start", "__init_array_end", Out<ELFT>::Dynamic->InitArraySec); AddStartEnd("__fini_array_start", "__fini_array_end", Out<ELFT>::Dynamic->FiniArraySec); for (OutputSectionBase<ELFT> *Sec : RegularSections) addStartStopSymbols(Sec); // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For // static linking the linker is required to optimize away any references to // __tls_get_addr, so it's not defined anywhere. Create a hidden definition // to avoid the undefined symbol error. if (!isOutputDynamic()) Symtab.addIgnored("__tls_get_addr"); // If the "_end" symbol is referenced, it is expected to point to the address // right after the data segment. Usually, this symbol points to the end // of .bss section or to the end of .data section if .bss section is absent. // The order of the sections can be affected by linker script, // so it is hard to predict which section will be the last one. // So, if this symbol is referenced, we just add the placeholder here // and update its value later. if (Symtab.find("_end")) Symtab.addAbsolute("_end", ElfSym<ELFT>::End); // If there is an undefined symbol "end", we should initialize it // with the same value as "_end". In any other case it should stay intact, // because it is an allowable name for a user symbol. if (SymbolBody *B = Symtab.find("end")) if (B->isUndefined()) Symtab.addAbsolute("end", ElfSym<ELFT>::End); // Scan relocations. This must be done after every symbol is declared so that // we can correctly decide if a dynamic relocation is needed. for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { for (InputSectionBase<ELFT> *C : F->getSections()) { if (isDiscarded(C)) continue; if (auto *S = dyn_cast<InputSection<ELFT>>(C)) scanRelocs(*S); else if (auto *S = dyn_cast<EHInputSection<ELFT>>(C)) if (S->RelocSection) scanRelocs(*S, *S->RelocSection); } } addIRelocMarkers<ELFT>(Symtab, isOutputDynamic()); std::vector<DefinedCommon *> CommonSymbols; std::vector<SharedSymbol<ELFT> *> SharedCopySymbols; for (auto &P : Symtab.getSymbols()) { SymbolBody *Body = P.second->Body; if (auto *U = dyn_cast<Undefined>(Body)) if (!U->isWeak() && !U->canKeepUndefined()) reportUndefined<ELFT>(Symtab, *Body); if (auto *C = dyn_cast<DefinedCommon>(Body)) CommonSymbols.push_back(C); if (auto *SC = dyn_cast<SharedSymbol<ELFT>>(Body)) if (SC->NeedsCopy) SharedCopySymbols.push_back(SC); if (!includeInSymtab<ELFT>(*Body)) continue; if (Out<ELFT>::SymTab) Out<ELFT>::SymTab->addSymbol(Body); if (isOutputDynamic() && includeInDynamicSymtab(*Body)) Out<ELFT>::DynSymTab->addSymbol(Body); } addCommonSymbols(CommonSymbols); addSharedCopySymbols(SharedCopySymbols); // This order is not the same as the final output order // because we sort the sections using their attributes below. if (Out<ELFT>::SymTab) OutputSections.push_back(Out<ELFT>::SymTab); OutputSections.push_back(Out<ELFT>::ShStrTab); if (Out<ELFT>::StrTab) OutputSections.push_back(Out<ELFT>::StrTab); if (isOutputDynamic()) { OutputSections.push_back(Out<ELFT>::DynSymTab); if (Out<ELFT>::GnuHashTab) OutputSections.push_back(Out<ELFT>::GnuHashTab); if (Out<ELFT>::HashTab) OutputSections.push_back(Out<ELFT>::HashTab); OutputSections.push_back(Out<ELFT>::Dynamic); OutputSections.push_back(Out<ELFT>::DynStrTab); if (Out<ELFT>::RelaDyn->hasRelocs()) OutputSections.push_back(Out<ELFT>::RelaDyn); // This is a MIPS specific section to hold a space within the data segment // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry. // See "Dynamic section" in Chapter 5 in the following document: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf if (Config->EMachine == EM_MIPS && !Config->Shared) { Out<ELFT>::MipsRldMap = new (SecAlloc.Allocate()) OutputSection<ELFT>(".rld_map", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE); Out<ELFT>::MipsRldMap->setSize(ELFT::Is64Bits ? 8 : 4); Out<ELFT>::MipsRldMap->updateAlign(ELFT::Is64Bits ? 8 : 4); OutputSections.push_back(Out<ELFT>::MipsRldMap); } } // We always need to add rel[a].plt to output if it has entries. // Even during static linking it can contain R_[*]_IRELATIVE relocations. if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) { OutputSections.push_back(Out<ELFT>::RelaPlt); Out<ELFT>::RelaPlt->Static = !isOutputDynamic(); } bool needsGot = !Out<ELFT>::Got->empty(); // We add the .got section to the result for dynamic MIPS target because // its address and properties are mentioned in the .dynamic section. if (Config->EMachine == EM_MIPS) needsGot |= isOutputDynamic(); // If we have a relocation that is relative to GOT (such as GOTOFFREL), // we need to emit a GOT even if it's empty. if (HasGotOffRel) needsGot = true; if (needsGot) OutputSections.push_back(Out<ELFT>::Got); if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty()) OutputSections.push_back(Out<ELFT>::GotPlt); if (!Out<ELFT>::Plt->empty()) OutputSections.push_back(Out<ELFT>::Plt); std::stable_sort(OutputSections.begin(), OutputSections.end(), compareSections<ELFT>); for (unsigned I = 0, N = OutputSections.size(); I < N; ++I) { OutputSections[I]->SectionIndex = I + 1; HasRelro |= (Config->ZRelro && isRelroSection(OutputSections[I])); } for (OutputSectionBase<ELFT> *Sec : OutputSections) Out<ELFT>::ShStrTab->add(Sec->getName()); // Finalizers fix each section's size. // .dynamic section's finalizer may add strings to .dynstr, // so finalize that early. // Likewise, .dynsym is finalized early since that may fill up .gnu.hash. Out<ELFT>::Dynamic->finalize(); if (isOutputDynamic()) Out<ELFT>::DynSymTab->finalize(); // Fill other section headers. for (OutputSectionBase<ELFT> *Sec : OutputSections) Sec->finalize(); // If we have a .opd section (used under PPC64 for function descriptors), // store a pointer to it here so that we can use it later when processing // relocations. Out<ELFT>::Opd = Map.lookup({".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC, 0}); } static bool isAlpha(char C) { return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_'; } static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); } // Returns true if S is valid as a C language identifier. static bool isValidCIdentifier(StringRef S) { if (S.empty() || !isAlpha(S[0])) return false; return std::all_of(S.begin() + 1, S.end(), isAlnum); } // If a section name is valid as a C identifier (which is rare because of // the leading '.'), linkers are expected to define __start_<secname> and // __stop_<secname> symbols. They are at beginning and end of the section, // respectively. This is not requested by the ELF standard, but GNU ld and // gold provide the feature, and used by many programs. template <class ELFT> void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) { StringRef S = Sec->getName(); if (!isValidCIdentifier(S)) return; StringSaver Saver(Alloc); StringRef Start = Saver.save("__start_" + S); StringRef Stop = Saver.save("__stop_" + S); if (Symtab.isUndefined(Start)) Symtab.addSynthetic(Start, *Sec, 0); if (Symtab.isUndefined(Stop)) Symtab.addSynthetic(Stop, *Sec, Sec->getSize()); } template <class ELFT> static bool needsPhdr(OutputSectionBase<ELFT> *Sec) { return Sec->getFlags() & SHF_ALLOC; } static uint32_t toPhdrFlags(uint64_t Flags) { uint32_t Ret = PF_R; if (Flags & SHF_WRITE) Ret |= PF_W; if (Flags & SHF_EXECINSTR) Ret |= PF_X; return Ret; } template <class ELFT> void Writer<ELFT>::updateRelro(Elf_Phdr *Cur, Elf_Phdr *GnuRelroPhdr, uintX_t VA) { if (!GnuRelroPhdr->p_type) setPhdr(GnuRelroPhdr, PT_GNU_RELRO, PF_R, Cur->p_offset, Cur->p_vaddr, VA - Cur->p_vaddr, 1 /*p_align*/); GnuRelroPhdr->p_filesz = VA - Cur->p_vaddr; GnuRelroPhdr->p_memsz = VA - Cur->p_vaddr; } // Visits all sections to create PHDRs and to assign incremental, // non-overlapping addresses to output sections. template <class ELFT> void Writer<ELFT>::assignAddresses() { uintX_t VA = Target->getVAStart() + sizeof(Elf_Ehdr); uintX_t FileOff = sizeof(Elf_Ehdr); // Calculate and reserve the space for the program header first so that // the first section can start right after the program header. Phdrs.resize(getPhdrsNum()); size_t PhdrSize = sizeof(Elf_Phdr) * Phdrs.size(); // The first phdr entry is PT_PHDR which describes the program header itself. setPhdr(&Phdrs[0], PT_PHDR, PF_R, FileOff, VA, PhdrSize, /*Align=*/8); FileOff += PhdrSize; VA += PhdrSize; // PT_INTERP must be the second entry if exists. int PhdrIdx = 0; Elf_Phdr *Interp = nullptr; if (needsInterpSection()) Interp = &Phdrs[++PhdrIdx]; // Add the first PT_LOAD segment for regular output sections. setPhdr(&Phdrs[++PhdrIdx], PT_LOAD, PF_R, 0, Target->getVAStart(), FileOff, Target->getPageSize()); Elf_Phdr GnuRelroPhdr = {}; Elf_Phdr TlsPhdr{}; bool RelroAligned = false; uintX_t ThreadBSSOffset = 0; // Create phdrs as we assign VAs and file offsets to all output sections. for (OutputSectionBase<ELFT> *Sec : OutputSections) { Elf_Phdr *PH = &Phdrs[PhdrIdx]; if (needsPhdr<ELFT>(Sec)) { uintX_t Flags = toPhdrFlags(Sec->getFlags()); bool InRelRo = Config->ZRelro && (Flags & PF_W) && isRelroSection(Sec); bool FirstNonRelRo = GnuRelroPhdr.p_type && !InRelRo && !RelroAligned; if (FirstNonRelRo || PH->p_flags != Flags) { VA = RoundUpToAlignment(VA, Target->getPageSize()); FileOff = RoundUpToAlignment(FileOff, Target->getPageSize()); if (FirstNonRelRo) RelroAligned = true; } if (PH->p_flags != Flags) { // Flags changed. Create a new PT_LOAD. PH = &Phdrs[++PhdrIdx]; setPhdr(PH, PT_LOAD, Flags, FileOff, VA, 0, Target->getPageSize()); } if (Sec->getFlags() & SHF_TLS) { if (!TlsPhdr.p_vaddr) setPhdr(&TlsPhdr, PT_TLS, PF_R, FileOff, VA, 0, Sec->getAlign()); if (Sec->getType() != SHT_NOBITS) VA = RoundUpToAlignment(VA, Sec->getAlign()); uintX_t TVA = RoundUpToAlignment(VA + ThreadBSSOffset, Sec->getAlign()); Sec->setVA(TVA); TlsPhdr.p_memsz += Sec->getSize(); if (Sec->getType() == SHT_NOBITS) { ThreadBSSOffset = TVA - VA + Sec->getSize(); } else { TlsPhdr.p_filesz += Sec->getSize(); VA += Sec->getSize(); } TlsPhdr.p_align = std::max<uintX_t>(TlsPhdr.p_align, Sec->getAlign()); } else { VA = RoundUpToAlignment(VA, Sec->getAlign()); Sec->setVA(VA); VA += Sec->getSize(); if (InRelRo) updateRelro(PH, &GnuRelroPhdr, VA); } } FileOff = RoundUpToAlignment(FileOff, Sec->getAlign()); Sec->setFileOffset(FileOff); if (Sec->getType() != SHT_NOBITS) FileOff += Sec->getSize(); if (needsPhdr<ELFT>(Sec)) { PH->p_filesz = FileOff - PH->p_offset; PH->p_memsz = VA - PH->p_vaddr; } } if (TlsPhdr.p_vaddr) { // The TLS pointer goes after PT_TLS. At least glibc will align it, // so round up the size to make sure the offsets are correct. TlsPhdr.p_memsz = RoundUpToAlignment(TlsPhdr.p_memsz, TlsPhdr.p_align); Phdrs[++PhdrIdx] = TlsPhdr; Out<ELFT>::TlsPhdr = &Phdrs[PhdrIdx]; } // Add an entry for .dynamic. if (isOutputDynamic()) { Elf_Phdr *PH = &Phdrs[++PhdrIdx]; PH->p_type = PT_DYNAMIC; copyPhdr(PH, Out<ELFT>::Dynamic); } if (HasRelro) { Elf_Phdr *PH = &Phdrs[++PhdrIdx]; *PH = GnuRelroPhdr; } // PT_GNU_STACK is a special section to tell the loader to make the // pages for the stack non-executable. if (!Config->ZExecStack) { Elf_Phdr *PH = &Phdrs[++PhdrIdx]; PH->p_type = PT_GNU_STACK; PH->p_flags = PF_R | PF_W; } // Fix up PT_INTERP as we now know the address of .interp section. if (Interp) { Interp->p_type = PT_INTERP; copyPhdr(Interp, Out<ELFT>::Interp); } // Add space for section headers. SectionHeaderOff = RoundUpToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4); FileSize = SectionHeaderOff + getNumSections() * sizeof(Elf_Shdr); // Update "_end" and "end" symbols so that they // point to the end of the data segment. ElfSym<ELFT>::End.st_value = VA; // Update __rel_iplt_start/__rel_iplt_end to wrap the // rela.plt section. if (Out<ELFT>::RelaPlt) { uintX_t Start = Out<ELFT>::RelaPlt->getVA(); ElfSym<ELFT>::RelaIpltStart.st_value = Start; ElfSym<ELFT>::RelaIpltEnd.st_value = Start + Out<ELFT>::RelaPlt->getSize(); } // Update MIPS _gp absolute symbol so that it points to the static data. if (Config->EMachine == EM_MIPS) ElfSym<ELFT>::MipsGp.st_value = getMipsGpAddr<ELFT>(); } // Returns the number of PHDR entries. template <class ELFT> int Writer<ELFT>::getPhdrsNum() const { bool Tls = false; int I = 2; // 2 for PT_PHDR and first PT_LOAD if (needsInterpSection()) ++I; if (isOutputDynamic()) ++I; if (!Config->ZExecStack) ++I; uintX_t Last = PF_R; for (OutputSectionBase<ELFT> *Sec : OutputSections) { if (!needsPhdr<ELFT>(Sec)) continue; if (Sec->getFlags() & SHF_TLS) Tls = true; uintX_t Flags = toPhdrFlags(Sec->getFlags()); if (Last != Flags) { Last = Flags; ++I; } } if (Tls) ++I; if (HasRelro) ++I; return I; } static uint32_t getELFFlags() { if (Config->EMachine != EM_MIPS) return 0; // FIXME: In fact ELF flags depends on ELF flags of input object files // and selected emulation. For now just use hadr coded values. uint32_t V = EF_MIPS_ABI_O32 | EF_MIPS_CPIC | EF_MIPS_ARCH_32R2; if (Config->Shared) V |= EF_MIPS_PIC; return V; } template <class ELFT> static typename ELFFile<ELFT>::uintX_t getEntryAddr() { if (Config->EntrySym) { if (SymbolBody *E = Config->EntrySym->repl()) return getSymVA<ELFT>(*E); return 0; } if (Config->EntryAddr != uint64_t(-1)) return Config->EntryAddr; return 0; } template <class ELFT> void Writer<ELFT>::writeHeader() { uint8_t *Buf = Buffer->getBufferStart(); memcpy(Buf, "\177ELF", 4); // Write the ELF header. auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf); EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little ? ELFDATA2LSB : ELFDATA2MSB; EHdr->e_ident[EI_VERSION] = EV_CURRENT; auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf); EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI(); EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC; EHdr->e_machine = FirstObj.getEMachine(); EHdr->e_version = EV_CURRENT; EHdr->e_entry = getEntryAddr<ELFT>(); EHdr->e_phoff = sizeof(Elf_Ehdr); EHdr->e_shoff = SectionHeaderOff; EHdr->e_flags = getELFFlags(); EHdr->e_ehsize = sizeof(Elf_Ehdr); EHdr->e_phentsize = sizeof(Elf_Phdr); EHdr->e_phnum = Phdrs.size(); EHdr->e_shentsize = sizeof(Elf_Shdr); EHdr->e_shnum = getNumSections(); EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex; // Write the program header table. memcpy(Buf + EHdr->e_phoff, &Phdrs[0], Phdrs.size() * sizeof(Phdrs[0])); // Write the section header table. Note that the first table entry is null. auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff); for (OutputSectionBase<ELFT> *Sec : OutputSections) Sec->writeHeaderTo(++SHdrs); } template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) { ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr = FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable); error(BufferOrErr, "failed to open " + Path); Buffer = std::move(*BufferOrErr); } // Write section contents to a mmap'ed file. template <class ELFT> void Writer<ELFT>::writeSections() { uint8_t *Buf = Buffer->getBufferStart(); // PPC64 needs to process relocations in the .opd section before processing // relocations in code-containing sections. if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) { Out<ELFT>::OpdBuf = Buf + Sec->getFileOff(); Sec->writeTo(Buf + Sec->getFileOff()); } for (OutputSectionBase<ELFT> *Sec : OutputSections) if (Sec != Out<ELFT>::Opd) Sec->writeTo(Buf + Sec->getFileOff()); } template <class ELFT> void Writer<ELFT>::setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, uintX_t FileOff, uintX_t VA, uintX_t Size, uintX_t Align) { PH->p_type = Type; PH->p_flags = Flags; PH->p_offset = FileOff; PH->p_vaddr = VA; PH->p_paddr = VA; PH->p_filesz = Size; PH->p_memsz = Size; PH->p_align = Align; } template <class ELFT> void Writer<ELFT>::copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From) { PH->p_flags = toPhdrFlags(From->getFlags()); PH->p_offset = From->getFileOff(); PH->p_vaddr = From->getVA(); PH->p_paddr = From->getVA(); PH->p_filesz = From->getSize(); PH->p_memsz = From->getSize(); PH->p_align = From->getAlign(); } template <class ELFT> void Writer<ELFT>::buildSectionMap() { for (const std::pair<StringRef, std::vector<StringRef>> &OutSec : Config->OutputSections) for (StringRef Name : OutSec.second) InputToOutputSection[Name] = OutSec.first; } template void lld::elf2::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab); template void lld::elf2::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab); template void lld::elf2::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab); template void lld::elf2::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab); Split Writer::createSections(). This function was longer than 250 lines, which is way too long in my own standard. This patch reduces the size. It is still too long, but this patch should be toward the right direction. git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@256411 91177308-0d34-0410-b5e6-96231b3b80d8 //===- Writer.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Writer.h" #include "Config.h" #include "OutputSections.h" #include "SymbolTable.h" #include "Target.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/StringSaver.h" using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; using namespace lld; using namespace lld::elf2; namespace { // The writer writes a SymbolTable result to a file. template <class ELFT> class Writer { public: typedef typename ELFFile<ELFT>::uintX_t uintX_t; typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr; typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr; typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr; typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range; typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela; Writer(SymbolTable<ELFT> &S) : Symtab(S) {} void run(); private: void copyLocalSymbols(); void createSections(); OutputSectionBase<ELFT> *createOutputSection(InputSectionBase<ELFT> *C, StringRef Name, uintX_t Type, uintX_t Flags); template <bool isRela> void scanRelocs(InputSectionBase<ELFT> &C, iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels); void scanRelocs(InputSection<ELFT> &C); void scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec); void updateRelro(Elf_Phdr *Cur, Elf_Phdr *GnuRelroPhdr, uintX_t VA); void assignAddresses(); void buildSectionMap(); void openFile(StringRef OutputPath); void writeHeader(); void writeSections(); bool isDiscarded(InputSectionBase<ELFT> *IS) const; StringRef getOutputSectionName(StringRef S) const; bool needsInterpSection() const { return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty(); } bool isOutputDynamic() const { return !Symtab.getSharedFiles().empty() || Config->Shared; } int getPhdrsNum() const; OutputSection<ELFT> *getBSS(); void addCommonSymbols(std::vector<DefinedCommon *> &Syms); void addSharedCopySymbols(std::vector<SharedSymbol<ELFT> *> &Syms); std::unique_ptr<llvm::FileOutputBuffer> Buffer; SpecificBumpPtrAllocator<OutputSection<ELFT>> SecAlloc; SpecificBumpPtrAllocator<MergeOutputSection<ELFT>> MSecAlloc; SpecificBumpPtrAllocator<EHOutputSection<ELFT>> EHSecAlloc; SpecificBumpPtrAllocator<MipsReginfoOutputSection<ELFT>> MReginfoSecAlloc; BumpPtrAllocator Alloc; std::vector<OutputSectionBase<ELFT> *> OutputSections; unsigned getNumSections() const { return OutputSections.size() + 1; } void addStartStopSymbols(OutputSectionBase<ELFT> *Sec); void setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, uintX_t FileOff, uintX_t VA, uintX_t Size, uintX_t Align); void copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From); bool HasRelro = false; SymbolTable<ELFT> &Symtab; std::vector<Elf_Phdr> Phdrs; uintX_t FileSize; uintX_t SectionHeaderOff; llvm::StringMap<llvm::StringRef> InputToOutputSection; }; } // anonymous namespace template <class ELFT> static bool shouldUseRela() { ELFKind K = cast<ELFFileBase<ELFT>>(Config->FirstElf)->getELFKind(); return K == ELF64LEKind || K == ELF64BEKind; } template <class ELFT> void lld::elf2::writeResult(SymbolTable<ELFT> *Symtab) { // Initialize output sections that are handled by Writer specially. // Don't reorder because the order of initialization matters. InterpSection<ELFT> Interp; Out<ELFT>::Interp = &Interp; StringTableSection<ELFT> ShStrTab(".shstrtab", false); Out<ELFT>::ShStrTab = &ShStrTab; StringTableSection<ELFT> StrTab(".strtab", false); if (!Config->StripAll) Out<ELFT>::StrTab = &StrTab; StringTableSection<ELFT> DynStrTab(".dynstr", true); Out<ELFT>::DynStrTab = &DynStrTab; GotSection<ELFT> Got; Out<ELFT>::Got = &Got; GotPltSection<ELFT> GotPlt; if (Target->supportsLazyRelocations()) Out<ELFT>::GotPlt = &GotPlt; PltSection<ELFT> Plt; Out<ELFT>::Plt = &Plt; std::unique_ptr<SymbolTableSection<ELFT>> SymTab; if (!Config->StripAll) { SymTab.reset(new SymbolTableSection<ELFT>(*Symtab, *Out<ELFT>::StrTab)); Out<ELFT>::SymTab = SymTab.get(); } SymbolTableSection<ELFT> DynSymTab(*Symtab, *Out<ELFT>::DynStrTab); Out<ELFT>::DynSymTab = &DynSymTab; HashTableSection<ELFT> HashTab; if (Config->SysvHash) Out<ELFT>::HashTab = &HashTab; GnuHashTableSection<ELFT> GnuHashTab; if (Config->GnuHash) Out<ELFT>::GnuHashTab = &GnuHashTab; bool IsRela = shouldUseRela<ELFT>(); RelocationSection<ELFT> RelaDyn(IsRela ? ".rela.dyn" : ".rel.dyn", IsRela); Out<ELFT>::RelaDyn = &RelaDyn; RelocationSection<ELFT> RelaPlt(IsRela ? ".rela.plt" : ".rel.plt", IsRela); if (Target->supportsLazyRelocations()) Out<ELFT>::RelaPlt = &RelaPlt; DynamicSection<ELFT> Dynamic(*Symtab); Out<ELFT>::Dynamic = &Dynamic; Writer<ELFT>(*Symtab).run(); } // The main function of the writer. template <class ELFT> void Writer<ELFT>::run() { buildSectionMap(); if (!Config->DiscardAll) copyLocalSymbols(); createSections(); assignAddresses(); openFile(Config->OutputFile); writeHeader(); writeSections(); error(Buffer->commit()); } namespace { template <bool Is64Bits> struct SectionKey { typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t; StringRef Name; uint32_t Type; uintX_t Flags; uintX_t EntSize; }; } namespace llvm { template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> { static SectionKey<Is64Bits> getEmptyKey() { return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0, 0}; } static SectionKey<Is64Bits> getTombstoneKey() { return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0, 0}; } static unsigned getHashValue(const SectionKey<Is64Bits> &Val) { return hash_combine(Val.Name, Val.Type, Val.Flags, Val.EntSize); } static bool isEqual(const SectionKey<Is64Bits> &LHS, const SectionKey<Is64Bits> &RHS) { return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) && LHS.Type == RHS.Type && LHS.Flags == RHS.Flags && LHS.EntSize == RHS.EntSize; } }; } // The reason we have to do this early scan is as follows // * To mmap the output file, we need to know the size // * For that, we need to know how many dynamic relocs we will have. // It might be possible to avoid this by outputting the file with write: // * Write the allocated output sections, computing addresses. // * Apply relocations, recording which ones require a dynamic reloc. // * Write the dynamic relocations. // * Write the rest of the file. template <class ELFT> template <bool isRela> void Writer<ELFT>::scanRelocs( InputSectionBase<ELFT> &C, iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) { typedef Elf_Rel_Impl<ELFT, isRela> RelType; const ObjectFile<ELFT> &File = *C.getFile(); for (const RelType &RI : Rels) { uint32_t SymIndex = RI.getSymbol(Config->Mips64EL); SymbolBody *Body = File.getSymbolBody(SymIndex); uint32_t Type = RI.getType(Config->Mips64EL); if (Target->isGotRelative(Type)) HasGotOffRel = true; if (Target->isTlsLocalDynamicReloc(Type)) { if (Target->isTlsOptimized(Type, nullptr)) continue; if (Out<ELFT>::Got->addCurrentModuleTlsIndex()) Out<ELFT>::RelaDyn->addReloc({&C, &RI}); continue; } // Set "used" bit for --as-needed. if (Body && Body->isUndefined() && !Body->isWeak()) if (auto *S = dyn_cast<SharedSymbol<ELFT>>(Body->repl())) S->File->IsUsed = true; if (Body) Body = Body->repl(); if (Body && Body->isTls() && Target->isTlsGlobalDynamicReloc(Type)) { bool Opt = Target->isTlsOptimized(Type, Body); if (!Opt && Out<ELFT>::Got->addDynTlsEntry(Body)) { Out<ELFT>::RelaDyn->addReloc({&C, &RI}); Out<ELFT>::RelaDyn->addReloc({nullptr, nullptr}); Body->setUsedInDynamicReloc(); continue; } if (!canBePreempted(Body, true)) continue; } if (Body && Body->isTls() && !Target->isTlsDynReloc(Type, *Body)) continue; if (Target->relocNeedsDynRelative(Type)) { RelType *Rel = new (Alloc) RelType; Rel->setSymbolAndType(0, Target->getRelativeReloc(), Config->Mips64EL); Rel->r_offset = RI.r_offset; Out<ELFT>::RelaDyn->addReloc({&C, Rel}); } bool NeedsGot = false; bool NeedsPlt = false; if (Body) { if (auto *E = dyn_cast<SharedSymbol<ELFT>>(Body)) { if (E->NeedsCopy) continue; if (Target->needsCopyRel(Type, *Body)) E->NeedsCopy = true; } NeedsPlt = Target->relocNeedsPlt(Type, *Body); if (NeedsPlt) { if (Body->isInPlt()) continue; Out<ELFT>::Plt->addEntry(Body); } NeedsGot = Target->relocNeedsGot(Type, *Body); if (NeedsGot) { if (NeedsPlt && Target->supportsLazyRelocations()) { Out<ELFT>::GotPlt->addEntry(Body); } else { if (Body->isInGot()) continue; Out<ELFT>::Got->addEntry(Body); } } } // An STT_GNU_IFUNC symbol always uses a PLT entry, and all references // to the symbol go through the PLT. This is true even for a local // symbol, although local symbols normally do not require PLT entries. if (Body && isGnuIFunc<ELFT>(*Body)) { Body->setUsedInDynamicReloc(); Out<ELFT>::RelaPlt->addReloc({&C, &RI}); continue; } if (Config->EMachine == EM_MIPS && NeedsGot) { // MIPS ABI has special rules to process GOT entries // and doesn't require relocation entries for them. // See "Global Offset Table" in Chapter 5 in the following document // for detailed description: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf Body->setUsedInDynamicReloc(); continue; } bool CBP = canBePreempted(Body, NeedsGot); if (!CBP && (!Config->Shared || Target->isRelRelative(Type))) continue; if (CBP) Body->setUsedInDynamicReloc(); if (NeedsPlt && Target->supportsLazyRelocations()) Out<ELFT>::RelaPlt->addReloc({&C, &RI}); else Out<ELFT>::RelaDyn->addReloc({&C, &RI}); } } template <class ELFT> void Writer<ELFT>::scanRelocs(InputSection<ELFT> &C) { if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC)) return; for (const Elf_Shdr *RelSec : C.RelocSections) scanRelocs(C, *RelSec); } template <class ELFT> void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec) { ELFFile<ELFT> &EObj = S.getFile()->getObj(); if (RelSec.sh_type == SHT_RELA) scanRelocs(S, EObj.relas(&RelSec)); else scanRelocs(S, EObj.rels(&RelSec)); } template <class ELFT> static void reportUndefined(const SymbolTable<ELFT> &S, const SymbolBody &Sym) { if (Config->Shared && !Config->NoUndefined) return; ELFFileBase<ELFT> *SymFile = findFile<ELFT>(S.getObjectFiles(), &Sym); std::string Message = "undefined symbol: " + Sym.getName().str(); if (SymFile) Message += " in " + SymFile->getName().str(); if (Config->NoInhibitExec) warning(Message); else error(Message); } // Local symbols are not in the linker's symbol table. This function scans // each object file's symbol table to copy local symbols to the output. template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { for (const Elf_Sym &Sym : F->getLocalSymbols()) { ErrorOr<StringRef> SymNameOrErr = Sym.getName(F->getStringTable()); error(SymNameOrErr); StringRef SymName = *SymNameOrErr; if (!shouldKeepInSymtab<ELFT>(*F, SymName, Sym)) continue; if (Out<ELFT>::SymTab) Out<ELFT>::SymTab->addLocalSymbol(SymName); } } } // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that // we would like to make sure appear is a specific order to maximize their // coverage by a single signed 16-bit offset from the TOC base pointer. // Conversely, the special .tocbss section should be first among all SHT_NOBITS // sections. This will put it next to the loaded special PPC64 sections (and, // thus, within reach of the TOC base pointer). static int getPPC64SectionRank(StringRef SectionName) { return StringSwitch<int>(SectionName) .Case(".tocbss", 0) .Case(".branch_lt", 2) .Case(".toc", 3) .Case(".toc1", 4) .Case(".opd", 5) .Default(1); } template <class ELFT> static bool isRelroSection(OutputSectionBase<ELFT> *Sec) { typename OutputSectionBase<ELFT>::uintX_t Flags = Sec->getFlags(); if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE)) return false; if (Flags & SHF_TLS) return true; uint32_t Type = Sec->getType(); if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY || Type == SHT_PREINIT_ARRAY) return true; if (Sec == Out<ELFT>::GotPlt) return Config->ZNow; if (Sec == Out<ELFT>::Dynamic || Sec == Out<ELFT>::Got) return true; StringRef S = Sec->getName(); return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" || S == ".eh_frame"; } // Output section ordering is determined by this function. template <class ELFT> static bool compareOutputSections(OutputSectionBase<ELFT> *A, OutputSectionBase<ELFT> *B) { typedef typename ELFFile<ELFT>::uintX_t uintX_t; uintX_t AFlags = A->getFlags(); uintX_t BFlags = B->getFlags(); // Allocatable sections go first to reduce the total PT_LOAD size and // so debug info doesn't change addresses in actual code. bool AIsAlloc = AFlags & SHF_ALLOC; bool BIsAlloc = BFlags & SHF_ALLOC; if (AIsAlloc != BIsAlloc) return AIsAlloc; // We don't have any special requirements for the relative order of // two non allocatable sections. if (!AIsAlloc) return false; // We want the read only sections first so that they go in the PT_LOAD // covering the program headers at the start of the file. bool AIsWritable = AFlags & SHF_WRITE; bool BIsWritable = BFlags & SHF_WRITE; if (AIsWritable != BIsWritable) return BIsWritable; // For a corresponding reason, put non exec sections first (the program // header PT_LOAD is not executable). bool AIsExec = AFlags & SHF_EXECINSTR; bool BIsExec = BFlags & SHF_EXECINSTR; if (AIsExec != BIsExec) return BIsExec; // If we got here we know that both A and B are in the same PT_LOAD. // The TLS initialization block needs to be a single contiguous block in a R/W // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS // sections are placed here as they don't take up virtual address space in the // PT_LOAD. bool AIsTls = AFlags & SHF_TLS; bool BIsTls = BFlags & SHF_TLS; if (AIsTls != BIsTls) return AIsTls; // The next requirement we have is to put nobits sections last. The // reason is that the only thing the dynamic linker will see about // them is a p_memsz that is larger than p_filesz. Seeing that it // zeros the end of the PT_LOAD, so that has to correspond to the // nobits sections. bool AIsNoBits = A->getType() == SHT_NOBITS; bool BIsNoBits = B->getType() == SHT_NOBITS; if (AIsNoBits != BIsNoBits) return BIsNoBits; // We place RelRo section before plain r/w ones. bool AIsRelRo = isRelroSection(A); bool BIsRelRo = isRelroSection(B); if (AIsRelRo != BIsRelRo) return AIsRelRo; // Some architectures have additional ordering restrictions for sections // within the same PT_LOAD. if (Config->EMachine == EM_PPC64) return getPPC64SectionRank(A->getName()) < getPPC64SectionRank(B->getName()); return false; } template <class ELFT> OutputSection<ELFT> *Writer<ELFT>::getBSS() { if (!Out<ELFT>::Bss) { Out<ELFT>::Bss = new (SecAlloc.Allocate()) OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE); OutputSections.push_back(Out<ELFT>::Bss); } return Out<ELFT>::Bss; } // Until this function is called, common symbols do not belong to any section. // This function adds them to end of BSS section. template <class ELFT> void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon *> &Syms) { typedef typename ELFFile<ELFT>::uintX_t uintX_t; if (Syms.empty()) return; // Sort the common symbols by alignment as an heuristic to pack them better. std::stable_sort(Syms.begin(), Syms.end(), [](const DefinedCommon *A, const DefinedCommon *B) { return A->MaxAlignment > B->MaxAlignment; }); uintX_t Off = getBSS()->getSize(); for (DefinedCommon *C : Syms) { uintX_t Align = C->MaxAlignment; Off = RoundUpToAlignment(Off, Align); C->OffsetInBSS = Off; Off += C->Size; } Out<ELFT>::Bss->setSize(Off); } template <class ELFT> void Writer<ELFT>::addSharedCopySymbols( std::vector<SharedSymbol<ELFT> *> &Syms) { typedef typename ELFFile<ELFT>::uintX_t uintX_t; typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr; if (Syms.empty()) return; uintX_t Off = getBSS()->getSize(); for (SharedSymbol<ELFT> *C : Syms) { const Elf_Sym &Sym = C->Sym; const Elf_Shdr *Sec = C->File->getSection(Sym); uintX_t SecAlign = Sec->sh_addralign; unsigned TrailingZeros = std::min(countTrailingZeros(SecAlign), countTrailingZeros((uintX_t)Sym.st_value)); uintX_t Align = 1 << TrailingZeros; Out<ELFT>::Bss->updateAlign(Align); Off = RoundUpToAlignment(Off, Align); C->OffsetInBSS = Off; Off += Sym.st_size; } Out<ELFT>::Bss->setSize(Off); } template <class ELFT> StringRef Writer<ELFT>::getOutputSectionName(StringRef S) const { auto It = InputToOutputSection.find(S); if (It != std::end(InputToOutputSection)) return It->second; if (S.startswith(".text.")) return ".text"; if (S.startswith(".rodata.")) return ".rodata"; if (S.startswith(".data.rel.ro")) return ".data.rel.ro"; if (S.startswith(".data.")) return ".data"; if (S.startswith(".bss.")) return ".bss"; return S; } template <class ELFT> void reportDiscarded(InputSectionBase<ELFT> *IS, const std::unique_ptr<ObjectFile<ELFT>> &File) { if (!Config->PrintGcSections || !IS || IS->isLive()) return; llvm::errs() << "removing unused section from '" << IS->getSectionName() << "' in file '" << File->getName() << "'\n"; } template <class ELFT> bool Writer<ELFT>::isDiscarded(InputSectionBase<ELFT> *IS) const { if (!IS || !IS->isLive() || IS == &InputSection<ELFT>::Discarded) return true; return InputToOutputSection.lookup(IS->getSectionName()) == "/DISCARD/"; } template <class ELFT> static bool compareSections(OutputSectionBase<ELFT> *A, OutputSectionBase<ELFT> *B) { auto ItA = Config->OutputSections.find(A->getName()); auto ItEnd = std::end(Config->OutputSections); if (ItA == ItEnd) return compareOutputSections(A, B); auto ItB = Config->OutputSections.find(B->getName()); if (ItB == ItEnd) return compareOutputSections(A, B); return std::distance(ItA, ItB) > 0; } // A statically linked executable will have rel[a].plt section // to hold R_[*]_IRELATIVE relocations. // The multi-arch libc will use these symbols to locate // these relocations at program startup time. // If RelaPlt is empty then there is no reason to create this symbols. template <class ELFT> static void addIRelocMarkers(SymbolTable<ELFT> &Symtab, bool IsDynamic) { if (IsDynamic || !Out<ELFT>::RelaPlt || !Out<ELFT>::RelaPlt->hasRelocs()) return; bool IsRela = shouldUseRela<ELFT>(); auto AddMarker = [&](StringRef Name, typename Writer<ELFT>::Elf_Sym &Sym) { if (SymbolBody *B = Symtab.find(Name)) if (B->isUndefined()) Symtab.addAbsolute(Name, Sym); }; AddMarker(IsRela ? "__rela_iplt_start" : "__rel_iplt_start", ElfSym<ELFT>::RelaIpltStart); AddMarker(IsRela ? "__rela_iplt_end" : "__rel_iplt_end", ElfSym<ELFT>::RelaIpltEnd); } template <class ELFT> static bool includeInSymtab(const SymbolBody &B) { if (!B.isUsedInRegularObj()) return false; // Don't include synthetic symbols like __init_array_start in every output. if (auto *U = dyn_cast<DefinedRegular<ELFT>>(&B)) if (&U->Sym == &ElfSym<ELFT>::IgnoreUndef) return false; return true; } static bool includeInDynamicSymtab(const SymbolBody &B) { uint8_t V = B.getVisibility(); if (V != STV_DEFAULT && V != STV_PROTECTED) return false; if (Config->ExportDynamic || Config->Shared) return true; return B.isUsedInDynamicReloc(); } template <class ELFT> OutputSectionBase<ELFT> * Writer<ELFT>::createOutputSection(InputSectionBase<ELFT> *C, StringRef Name, uintX_t Type, uintX_t Flags) { switch (C->SectionKind) { case InputSectionBase<ELFT>::Regular: return new (SecAlloc.Allocate()) OutputSection<ELFT>(Name, Type, Flags); case InputSectionBase<ELFT>::EHFrame: return new (EHSecAlloc.Allocate()) EHOutputSection<ELFT>(Name, Type, Flags); case InputSectionBase<ELFT>::Merge: return new (MSecAlloc.Allocate()) MergeOutputSection<ELFT>(Name, Type, Flags); case InputSectionBase<ELFT>::MipsReginfo: return new (MReginfoSecAlloc.Allocate()) MipsReginfoOutputSection<ELFT>(); } } // Create output section objects and add them to OutputSections. template <class ELFT> void Writer<ELFT>::createSections() { // .interp needs to be on the first page in the output file. if (needsInterpSection()) OutputSections.push_back(Out<ELFT>::Interp); SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map; std::vector<OutputSectionBase<ELFT> *> RegularSections; for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { for (InputSectionBase<ELFT> *C : F->getSections()) { if (isDiscarded(C)) { reportDiscarded(C, F); continue; } const Elf_Shdr *H = C->getSectionHdr(); uintX_t OutFlags = H->sh_flags & ~SHF_GROUP; // For SHF_MERGE we create different output sections for each sh_entsize. // This makes each output section simple and keeps a single level // mapping from input to output. uintX_t EntSize = isa<MergeInputSection<ELFT>>(C) ? H->sh_entsize : 0; uint32_t OutType = H->sh_type; if (OutType == SHT_PROGBITS && C->getSectionName() == ".eh_frame" && Config->EMachine == EM_X86_64) OutType = SHT_X86_64_UNWIND; SectionKey<ELFT::Is64Bits> Key{getOutputSectionName(C->getSectionName()), OutType, OutFlags, EntSize}; OutputSectionBase<ELFT> *&Sec = Map[Key]; if (!Sec) { Sec = createOutputSection(C, Key.Name, Key.Type, Key.Flags); OutputSections.push_back(Sec); RegularSections.push_back(Sec); } switch (C->SectionKind) { case InputSectionBase<ELFT>::Regular: static_cast<OutputSection<ELFT> *>(Sec) ->addSection(cast<InputSection<ELFT>>(C)); break; case InputSectionBase<ELFT>::EHFrame: static_cast<EHOutputSection<ELFT> *>(Sec) ->addSection(cast<EHInputSection<ELFT>>(C)); break; case InputSectionBase<ELFT>::Merge: static_cast<MergeOutputSection<ELFT> *>(Sec) ->addSection(cast<MergeInputSection<ELFT>>(C)); break; case InputSectionBase<ELFT>::MipsReginfo: static_cast<MipsReginfoOutputSection<ELFT> *>(Sec) ->addSection(cast<MipsReginfoInputSection<ELFT>>(C)); break; } } } Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>( Map[{".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE, 0}]); Out<ELFT>::Dynamic->PreInitArraySec = Map.lookup( {".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); Out<ELFT>::Dynamic->InitArraySec = Map.lookup({".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); Out<ELFT>::Dynamic->FiniArraySec = Map.lookup({".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); auto AddStartEnd = [&](StringRef Start, StringRef End, OutputSectionBase<ELFT> *OS) { if (OS) { Symtab.addSynthetic(Start, *OS, 0); Symtab.addSynthetic(End, *OS, OS->getSize()); } else { Symtab.addIgnored(Start); Symtab.addIgnored(End); } }; AddStartEnd("__preinit_array_start", "__preinit_array_end", Out<ELFT>::Dynamic->PreInitArraySec); AddStartEnd("__init_array_start", "__init_array_end", Out<ELFT>::Dynamic->InitArraySec); AddStartEnd("__fini_array_start", "__fini_array_end", Out<ELFT>::Dynamic->FiniArraySec); for (OutputSectionBase<ELFT> *Sec : RegularSections) addStartStopSymbols(Sec); // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For // static linking the linker is required to optimize away any references to // __tls_get_addr, so it's not defined anywhere. Create a hidden definition // to avoid the undefined symbol error. if (!isOutputDynamic()) Symtab.addIgnored("__tls_get_addr"); // If the "_end" symbol is referenced, it is expected to point to the address // right after the data segment. Usually, this symbol points to the end // of .bss section or to the end of .data section if .bss section is absent. // The order of the sections can be affected by linker script, // so it is hard to predict which section will be the last one. // So, if this symbol is referenced, we just add the placeholder here // and update its value later. if (Symtab.find("_end")) Symtab.addAbsolute("_end", ElfSym<ELFT>::End); // If there is an undefined symbol "end", we should initialize it // with the same value as "_end". In any other case it should stay intact, // because it is an allowable name for a user symbol. if (SymbolBody *B = Symtab.find("end")) if (B->isUndefined()) Symtab.addAbsolute("end", ElfSym<ELFT>::End); // Scan relocations. This must be done after every symbol is declared so that // we can correctly decide if a dynamic relocation is needed. for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { for (InputSectionBase<ELFT> *C : F->getSections()) { if (isDiscarded(C)) continue; if (auto *S = dyn_cast<InputSection<ELFT>>(C)) scanRelocs(*S); else if (auto *S = dyn_cast<EHInputSection<ELFT>>(C)) if (S->RelocSection) scanRelocs(*S, *S->RelocSection); } } addIRelocMarkers<ELFT>(Symtab, isOutputDynamic()); std::vector<DefinedCommon *> CommonSymbols; std::vector<SharedSymbol<ELFT> *> SharedCopySymbols; for (auto &P : Symtab.getSymbols()) { SymbolBody *Body = P.second->Body; if (auto *U = dyn_cast<Undefined>(Body)) if (!U->isWeak() && !U->canKeepUndefined()) reportUndefined<ELFT>(Symtab, *Body); if (auto *C = dyn_cast<DefinedCommon>(Body)) CommonSymbols.push_back(C); if (auto *SC = dyn_cast<SharedSymbol<ELFT>>(Body)) if (SC->NeedsCopy) SharedCopySymbols.push_back(SC); if (!includeInSymtab<ELFT>(*Body)) continue; if (Out<ELFT>::SymTab) Out<ELFT>::SymTab->addSymbol(Body); if (isOutputDynamic() && includeInDynamicSymtab(*Body)) Out<ELFT>::DynSymTab->addSymbol(Body); } addCommonSymbols(CommonSymbols); addSharedCopySymbols(SharedCopySymbols); // This order is not the same as the final output order // because we sort the sections using their attributes below. if (Out<ELFT>::SymTab) OutputSections.push_back(Out<ELFT>::SymTab); OutputSections.push_back(Out<ELFT>::ShStrTab); if (Out<ELFT>::StrTab) OutputSections.push_back(Out<ELFT>::StrTab); if (isOutputDynamic()) { OutputSections.push_back(Out<ELFT>::DynSymTab); if (Out<ELFT>::GnuHashTab) OutputSections.push_back(Out<ELFT>::GnuHashTab); if (Out<ELFT>::HashTab) OutputSections.push_back(Out<ELFT>::HashTab); OutputSections.push_back(Out<ELFT>::Dynamic); OutputSections.push_back(Out<ELFT>::DynStrTab); if (Out<ELFT>::RelaDyn->hasRelocs()) OutputSections.push_back(Out<ELFT>::RelaDyn); // This is a MIPS specific section to hold a space within the data segment // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry. // See "Dynamic section" in Chapter 5 in the following document: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf if (Config->EMachine == EM_MIPS && !Config->Shared) { Out<ELFT>::MipsRldMap = new (SecAlloc.Allocate()) OutputSection<ELFT>(".rld_map", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE); Out<ELFT>::MipsRldMap->setSize(ELFT::Is64Bits ? 8 : 4); Out<ELFT>::MipsRldMap->updateAlign(ELFT::Is64Bits ? 8 : 4); OutputSections.push_back(Out<ELFT>::MipsRldMap); } } // We always need to add rel[a].plt to output if it has entries. // Even during static linking it can contain R_[*]_IRELATIVE relocations. if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) { OutputSections.push_back(Out<ELFT>::RelaPlt); Out<ELFT>::RelaPlt->Static = !isOutputDynamic(); } bool needsGot = !Out<ELFT>::Got->empty(); // We add the .got section to the result for dynamic MIPS target because // its address and properties are mentioned in the .dynamic section. if (Config->EMachine == EM_MIPS) needsGot |= isOutputDynamic(); // If we have a relocation that is relative to GOT (such as GOTOFFREL), // we need to emit a GOT even if it's empty. if (HasGotOffRel) needsGot = true; if (needsGot) OutputSections.push_back(Out<ELFT>::Got); if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty()) OutputSections.push_back(Out<ELFT>::GotPlt); if (!Out<ELFT>::Plt->empty()) OutputSections.push_back(Out<ELFT>::Plt); std::stable_sort(OutputSections.begin(), OutputSections.end(), compareSections<ELFT>); for (unsigned I = 0, N = OutputSections.size(); I < N; ++I) { OutputSections[I]->SectionIndex = I + 1; HasRelro |= (Config->ZRelro && isRelroSection(OutputSections[I])); } for (OutputSectionBase<ELFT> *Sec : OutputSections) Out<ELFT>::ShStrTab->add(Sec->getName()); // Finalizers fix each section's size. // .dynamic section's finalizer may add strings to .dynstr, // so finalize that early. // Likewise, .dynsym is finalized early since that may fill up .gnu.hash. Out<ELFT>::Dynamic->finalize(); if (isOutputDynamic()) Out<ELFT>::DynSymTab->finalize(); // Fill other section headers. for (OutputSectionBase<ELFT> *Sec : OutputSections) Sec->finalize(); // If we have a .opd section (used under PPC64 for function descriptors), // store a pointer to it here so that we can use it later when processing // relocations. Out<ELFT>::Opd = Map.lookup({".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC, 0}); } static bool isAlpha(char C) { return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_'; } static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); } // Returns true if S is valid as a C language identifier. static bool isValidCIdentifier(StringRef S) { if (S.empty() || !isAlpha(S[0])) return false; return std::all_of(S.begin() + 1, S.end(), isAlnum); } // If a section name is valid as a C identifier (which is rare because of // the leading '.'), linkers are expected to define __start_<secname> and // __stop_<secname> symbols. They are at beginning and end of the section, // respectively. This is not requested by the ELF standard, but GNU ld and // gold provide the feature, and used by many programs. template <class ELFT> void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) { StringRef S = Sec->getName(); if (!isValidCIdentifier(S)) return; StringSaver Saver(Alloc); StringRef Start = Saver.save("__start_" + S); StringRef Stop = Saver.save("__stop_" + S); if (Symtab.isUndefined(Start)) Symtab.addSynthetic(Start, *Sec, 0); if (Symtab.isUndefined(Stop)) Symtab.addSynthetic(Stop, *Sec, Sec->getSize()); } template <class ELFT> static bool needsPhdr(OutputSectionBase<ELFT> *Sec) { return Sec->getFlags() & SHF_ALLOC; } static uint32_t toPhdrFlags(uint64_t Flags) { uint32_t Ret = PF_R; if (Flags & SHF_WRITE) Ret |= PF_W; if (Flags & SHF_EXECINSTR) Ret |= PF_X; return Ret; } template <class ELFT> void Writer<ELFT>::updateRelro(Elf_Phdr *Cur, Elf_Phdr *GnuRelroPhdr, uintX_t VA) { if (!GnuRelroPhdr->p_type) setPhdr(GnuRelroPhdr, PT_GNU_RELRO, PF_R, Cur->p_offset, Cur->p_vaddr, VA - Cur->p_vaddr, 1 /*p_align*/); GnuRelroPhdr->p_filesz = VA - Cur->p_vaddr; GnuRelroPhdr->p_memsz = VA - Cur->p_vaddr; } // Visits all sections to create PHDRs and to assign incremental, // non-overlapping addresses to output sections. template <class ELFT> void Writer<ELFT>::assignAddresses() { uintX_t VA = Target->getVAStart() + sizeof(Elf_Ehdr); uintX_t FileOff = sizeof(Elf_Ehdr); // Calculate and reserve the space for the program header first so that // the first section can start right after the program header. Phdrs.resize(getPhdrsNum()); size_t PhdrSize = sizeof(Elf_Phdr) * Phdrs.size(); // The first phdr entry is PT_PHDR which describes the program header itself. setPhdr(&Phdrs[0], PT_PHDR, PF_R, FileOff, VA, PhdrSize, /*Align=*/8); FileOff += PhdrSize; VA += PhdrSize; // PT_INTERP must be the second entry if exists. int PhdrIdx = 0; Elf_Phdr *Interp = nullptr; if (needsInterpSection()) Interp = &Phdrs[++PhdrIdx]; // Add the first PT_LOAD segment for regular output sections. setPhdr(&Phdrs[++PhdrIdx], PT_LOAD, PF_R, 0, Target->getVAStart(), FileOff, Target->getPageSize()); Elf_Phdr GnuRelroPhdr = {}; Elf_Phdr TlsPhdr{}; bool RelroAligned = false; uintX_t ThreadBSSOffset = 0; // Create phdrs as we assign VAs and file offsets to all output sections. for (OutputSectionBase<ELFT> *Sec : OutputSections) { Elf_Phdr *PH = &Phdrs[PhdrIdx]; if (needsPhdr<ELFT>(Sec)) { uintX_t Flags = toPhdrFlags(Sec->getFlags()); bool InRelRo = Config->ZRelro && (Flags & PF_W) && isRelroSection(Sec); bool FirstNonRelRo = GnuRelroPhdr.p_type && !InRelRo && !RelroAligned; if (FirstNonRelRo || PH->p_flags != Flags) { VA = RoundUpToAlignment(VA, Target->getPageSize()); FileOff = RoundUpToAlignment(FileOff, Target->getPageSize()); if (FirstNonRelRo) RelroAligned = true; } if (PH->p_flags != Flags) { // Flags changed. Create a new PT_LOAD. PH = &Phdrs[++PhdrIdx]; setPhdr(PH, PT_LOAD, Flags, FileOff, VA, 0, Target->getPageSize()); } if (Sec->getFlags() & SHF_TLS) { if (!TlsPhdr.p_vaddr) setPhdr(&TlsPhdr, PT_TLS, PF_R, FileOff, VA, 0, Sec->getAlign()); if (Sec->getType() != SHT_NOBITS) VA = RoundUpToAlignment(VA, Sec->getAlign()); uintX_t TVA = RoundUpToAlignment(VA + ThreadBSSOffset, Sec->getAlign()); Sec->setVA(TVA); TlsPhdr.p_memsz += Sec->getSize(); if (Sec->getType() == SHT_NOBITS) { ThreadBSSOffset = TVA - VA + Sec->getSize(); } else { TlsPhdr.p_filesz += Sec->getSize(); VA += Sec->getSize(); } TlsPhdr.p_align = std::max<uintX_t>(TlsPhdr.p_align, Sec->getAlign()); } else { VA = RoundUpToAlignment(VA, Sec->getAlign()); Sec->setVA(VA); VA += Sec->getSize(); if (InRelRo) updateRelro(PH, &GnuRelroPhdr, VA); } } FileOff = RoundUpToAlignment(FileOff, Sec->getAlign()); Sec->setFileOffset(FileOff); if (Sec->getType() != SHT_NOBITS) FileOff += Sec->getSize(); if (needsPhdr<ELFT>(Sec)) { PH->p_filesz = FileOff - PH->p_offset; PH->p_memsz = VA - PH->p_vaddr; } } if (TlsPhdr.p_vaddr) { // The TLS pointer goes after PT_TLS. At least glibc will align it, // so round up the size to make sure the offsets are correct. TlsPhdr.p_memsz = RoundUpToAlignment(TlsPhdr.p_memsz, TlsPhdr.p_align); Phdrs[++PhdrIdx] = TlsPhdr; Out<ELFT>::TlsPhdr = &Phdrs[PhdrIdx]; } // Add an entry for .dynamic. if (isOutputDynamic()) { Elf_Phdr *PH = &Phdrs[++PhdrIdx]; PH->p_type = PT_DYNAMIC; copyPhdr(PH, Out<ELFT>::Dynamic); } if (HasRelro) { Elf_Phdr *PH = &Phdrs[++PhdrIdx]; *PH = GnuRelroPhdr; } // PT_GNU_STACK is a special section to tell the loader to make the // pages for the stack non-executable. if (!Config->ZExecStack) { Elf_Phdr *PH = &Phdrs[++PhdrIdx]; PH->p_type = PT_GNU_STACK; PH->p_flags = PF_R | PF_W; } // Fix up PT_INTERP as we now know the address of .interp section. if (Interp) { Interp->p_type = PT_INTERP; copyPhdr(Interp, Out<ELFT>::Interp); } // Add space for section headers. SectionHeaderOff = RoundUpToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4); FileSize = SectionHeaderOff + getNumSections() * sizeof(Elf_Shdr); // Update "_end" and "end" symbols so that they // point to the end of the data segment. ElfSym<ELFT>::End.st_value = VA; // Update __rel_iplt_start/__rel_iplt_end to wrap the // rela.plt section. if (Out<ELFT>::RelaPlt) { uintX_t Start = Out<ELFT>::RelaPlt->getVA(); ElfSym<ELFT>::RelaIpltStart.st_value = Start; ElfSym<ELFT>::RelaIpltEnd.st_value = Start + Out<ELFT>::RelaPlt->getSize(); } // Update MIPS _gp absolute symbol so that it points to the static data. if (Config->EMachine == EM_MIPS) ElfSym<ELFT>::MipsGp.st_value = getMipsGpAddr<ELFT>(); } // Returns the number of PHDR entries. template <class ELFT> int Writer<ELFT>::getPhdrsNum() const { bool Tls = false; int I = 2; // 2 for PT_PHDR and first PT_LOAD if (needsInterpSection()) ++I; if (isOutputDynamic()) ++I; if (!Config->ZExecStack) ++I; uintX_t Last = PF_R; for (OutputSectionBase<ELFT> *Sec : OutputSections) { if (!needsPhdr<ELFT>(Sec)) continue; if (Sec->getFlags() & SHF_TLS) Tls = true; uintX_t Flags = toPhdrFlags(Sec->getFlags()); if (Last != Flags) { Last = Flags; ++I; } } if (Tls) ++I; if (HasRelro) ++I; return I; } static uint32_t getELFFlags() { if (Config->EMachine != EM_MIPS) return 0; // FIXME: In fact ELF flags depends on ELF flags of input object files // and selected emulation. For now just use hadr coded values. uint32_t V = EF_MIPS_ABI_O32 | EF_MIPS_CPIC | EF_MIPS_ARCH_32R2; if (Config->Shared) V |= EF_MIPS_PIC; return V; } template <class ELFT> static typename ELFFile<ELFT>::uintX_t getEntryAddr() { if (Config->EntrySym) { if (SymbolBody *E = Config->EntrySym->repl()) return getSymVA<ELFT>(*E); return 0; } if (Config->EntryAddr != uint64_t(-1)) return Config->EntryAddr; return 0; } template <class ELFT> void Writer<ELFT>::writeHeader() { uint8_t *Buf = Buffer->getBufferStart(); memcpy(Buf, "\177ELF", 4); // Write the ELF header. auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf); EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little ? ELFDATA2LSB : ELFDATA2MSB; EHdr->e_ident[EI_VERSION] = EV_CURRENT; auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf); EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI(); EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC; EHdr->e_machine = FirstObj.getEMachine(); EHdr->e_version = EV_CURRENT; EHdr->e_entry = getEntryAddr<ELFT>(); EHdr->e_phoff = sizeof(Elf_Ehdr); EHdr->e_shoff = SectionHeaderOff; EHdr->e_flags = getELFFlags(); EHdr->e_ehsize = sizeof(Elf_Ehdr); EHdr->e_phentsize = sizeof(Elf_Phdr); EHdr->e_phnum = Phdrs.size(); EHdr->e_shentsize = sizeof(Elf_Shdr); EHdr->e_shnum = getNumSections(); EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex; // Write the program header table. memcpy(Buf + EHdr->e_phoff, &Phdrs[0], Phdrs.size() * sizeof(Phdrs[0])); // Write the section header table. Note that the first table entry is null. auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff); for (OutputSectionBase<ELFT> *Sec : OutputSections) Sec->writeHeaderTo(++SHdrs); } template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) { ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr = FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable); error(BufferOrErr, "failed to open " + Path); Buffer = std::move(*BufferOrErr); } // Write section contents to a mmap'ed file. template <class ELFT> void Writer<ELFT>::writeSections() { uint8_t *Buf = Buffer->getBufferStart(); // PPC64 needs to process relocations in the .opd section before processing // relocations in code-containing sections. if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) { Out<ELFT>::OpdBuf = Buf + Sec->getFileOff(); Sec->writeTo(Buf + Sec->getFileOff()); } for (OutputSectionBase<ELFT> *Sec : OutputSections) if (Sec != Out<ELFT>::Opd) Sec->writeTo(Buf + Sec->getFileOff()); } template <class ELFT> void Writer<ELFT>::setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, uintX_t FileOff, uintX_t VA, uintX_t Size, uintX_t Align) { PH->p_type = Type; PH->p_flags = Flags; PH->p_offset = FileOff; PH->p_vaddr = VA; PH->p_paddr = VA; PH->p_filesz = Size; PH->p_memsz = Size; PH->p_align = Align; } template <class ELFT> void Writer<ELFT>::copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From) { PH->p_flags = toPhdrFlags(From->getFlags()); PH->p_offset = From->getFileOff(); PH->p_vaddr = From->getVA(); PH->p_paddr = From->getVA(); PH->p_filesz = From->getSize(); PH->p_memsz = From->getSize(); PH->p_align = From->getAlign(); } template <class ELFT> void Writer<ELFT>::buildSectionMap() { for (const std::pair<StringRef, std::vector<StringRef>> &OutSec : Config->OutputSections) for (StringRef Name : OutSec.second) InputToOutputSection[Name] = OutSec.first; } template void lld::elf2::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab); template void lld::elf2::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab); template void lld::elf2::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab); template void lld::elf2::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab);
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/accessors/p9_mvpd_ring_funcs.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ // $Id: p9_mvpd_ring_funcs.C,v 1.12 2014/07/16 19:06:49 cswenson Exp $ /** * @file p9_mvpd_ring_funcs.C * * @brief common routines * */ #include <stdint.h> // fapi2 support #include <fapi2.H> #include <utils.H> #include <mvpd_access.H> #include <p9_mvpd_ring_funcs.H> // pull in CompressedScanData def from proc_slw_build HWP #include <p9_scan_compression.H> #include <p9_ring_identification.H> extern "C" { using namespace fapi2; // functions internal to this file // these functions are common for both mvpdRingFunc and mbvpdRingFunc fapi2::ReturnCode mvpdValidateRingHeader( CompressedScanData* i_pRing, uint8_t i_chipletId, uint8_t i_ringId, uint32_t i_ringBufsize); fapi2::ReturnCode mvpdRingFuncFind( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, const uint8_t i_chipletId, const uint8_t i_ringId, uint8_t* i_pRecordBuf, uint32_t i_recordBufLenfapi, uint8_t*& o_rRingBuf, uint32_t& o_rRingBufsize); fapi2::ReturnCode mvpdRingFuncGet( uint8_t* i_pRing, uint32_t i_ringLen, uint8_t* i_pCallerRingBuf, uint32_t& io_rCallerRingBufLen); fapi2::ReturnCode mvpdRingFuncSet( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, uint8_t* i_pRecordBuf, uint32_t i_recordLen, uint8_t* i_pRing, uint32_t i_ringLen, uint8_t* i_pCallerRingBuf, uint32_t i_callerRingBufLen); // add record/keywords with rings with RS4 header here. struct _supportedRecordKeywords { fapi2::MvpdRecord record; fapi2::MvpdKeyword keyword; } supportedRecordKeywords [] = { { MVPD_RECORD_CP00, MVPD_KEYWORD_PDR }, { MVPD_RECORD_CP00, MVPD_KEYWORD_PDG }, }; /** * @brief Validate Record and Keyword Combination * * @par Detailed Description: * Check for supported combinations of Record and Keyword. * The record needs to contain rings of RS4 header * (CompressedScanData) format. * * @param[in] i_record * Record to validate * * @param[in] i_keyword * Keyword to validate * * @note: "Getting" data not in RS4 header format would likely just * fail to find the ring harmlessly. "Setting" data could * make a mess looking for the end to append a new ring. The * result could be invalid vpd. * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdValidateRecordKeyword( fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword) { fapi2::ReturnCode l_fapirc; bool l_validPair = false; const uint32_t numPairs = sizeof(supportedRecordKeywords) / sizeof(supportedRecordKeywords[0]); for (uint32_t curPair = 0; curPair < numPairs; curPair++ ) { if (supportedRecordKeywords[curPair].record == i_record && supportedRecordKeywords[curPair].keyword == i_keyword) { l_validPair = true; break; } } if ( !l_validPair ) { FAPI_SET_HWP_ERROR(l_fapirc, RC_MVPD_RING_FUNC_INVALID_PARAMETER ); } return l_fapirc; }; /** * @brief MVPD Ring Function * * @par Detailed Description: * The getMvpdRing and setMvpdRing wrappers call this function * to do all the processing. * * @param[in] i_mvpdRingFuncOp * MVPD ring function op to process * * @param[in] i_record * Record in the MVPD * * @param[in] i_keyword * Keyword for the MVPD record * * @param[in] i_fapiTarget * FAPI target for the op * * @param[in] i_chipletId * Chiplet ID for the op * * @param[in] i_ringId * Ring ID for the op * * @param[in] i_pRingBuf * Pointer to ring buffer with set data * * @param[in/out] io_rRingBufsize * Size of ring buffer * * @note: io_rRingBufsize is only an 'output' for get function. * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdRingFunc(const mvpdRingFuncOp i_mvpdRingFuncOp, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, const uint8_t i_chipletId, const uint8_t i_ringId, uint8_t* i_pRingBuf, uint32_t& io_rRingBufsize) { fapi2::ReturnCode l_fapirc = fapi2::FAPI2_RC_SUCCESS; uint32_t l_recordLen = 0; uint8_t* l_recordBuf = NULL; uint8_t* l_pRing = NULL; uint32_t l_ringLen = 0; FAPI_DBG("mvpdRingFunc:entry op=0x%x ringId=0x%x chipletId=0x%x " "size=0x%x", i_mvpdRingFuncOp, i_ringId, i_chipletId, io_rRingBufsize ); // do common get and set input parameter error checks // check for supported combination of Record and Keyword FAPI_TRY(mvpdValidateRecordKeyword(i_record, i_keyword), "mvpdRingFunc: unsupported record keyword pair " "record=0x%x, keyword=0x%x", i_record, i_keyword); // do set specific input parameter checks if (i_mvpdRingFuncOp == MVPD_RING_SET ) { // passing NULL pointer to receive needed size is only for get. FAPI_ASSERT(i_pRingBuf != NULL, fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdRingFunc: NULL ring buffer pointer passed " "to set function chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); // Validate ring header to protect vpd FAPI_TRY(mvpdValidateRingHeader( reinterpret_cast<CompressedScanData*>(i_pRingBuf), i_chipletId, i_ringId, io_rRingBufsize), "mvpdRingFunc: invalid ring header " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); } // call getMvpdField once with a NULL pointer to get the buffer // size no error should be returned. FAPI_TRY(getMvpdField(i_record, i_keyword, i_fapiTarget, NULL, l_recordLen ), "mvpdRingFunc: getMvpdField failed to get buffer size " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_DBG( "mvpdRingFunc: getMvpdField returned record len=0x%x", l_recordLen ); // allocate buffer for the record. Always works l_recordBuf = static_cast<uint8_t*>(malloc((size_t)l_recordLen)); // load ring from MVPD for this target FAPI_TRY(getMvpdField(i_record, i_keyword, i_fapiTarget, l_recordBuf, l_recordLen ), "mvpdRingFunc: getMvpdField failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); // find ring in the record. It is an error if not there for a "get". // Its ok if not there for a "set". The ring will be added. // l_ringLen set to 0 if not there with l_pRing at the start of padding. FAPI_TRY(mvpdRingFuncFind(i_fapiTarget, i_record, i_keyword, i_chipletId, i_ringId, l_recordBuf, l_recordLen, l_pRing, l_ringLen), "mvpdRingFunc: mvpdRingFuncFind failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); // do the get or set specific operations if (i_mvpdRingFuncOp == MVPD_RING_GET ) // do the get operation { // ensure ring was found. Must be there for "get" FAPI_ASSERT(l_ringLen != 0, fapi2::MVPD_RING_NOT_FOUND(). set_CHIP_TARGET(i_fapiTarget). set_RING_ID(i_ringId). set_CHIPLET_ID(i_chipletId), "mvpdRingFunc: mvpdRingFuncFind did not find ring"); // copy ring back to caller's buffer FAPI_TRY(mvpdRingFuncGet(l_pRing, l_ringLen, i_pRingBuf, io_rRingBufsize), "mvpdRingFunc: mvpdRingFuncGet failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); } else // set operation { // update record with caller's ring FAPI_TRY(mvpdRingFuncSet(i_fapiTarget, i_record, i_keyword, l_recordBuf, l_recordLen, l_pRing, l_ringLen, i_pRingBuf, io_rRingBufsize), "mvpdRingFunc: mvpdRingFuncSet failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); // update record back to the mvpd FAPI_TRY(setMvpdField(i_record, i_keyword, i_fapiTarget, l_recordBuf, l_recordLen), "mvpdRingFunc: setMvpdField failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); } fapi_try_exit: // get current error l_fapirc = fapi2::current_err; // unload the repair ring if allocated if(l_recordBuf) { free(static_cast<void*>(l_recordBuf)); l_recordBuf = NULL; } if((i_mvpdRingFuncOp != MVPD_RING_GET) && l_fapirc) { io_rRingBufsize = 0; } FAPI_DBG( "mvpdRingFunc: exit bufsize= 0x%x rc= 0x%x", io_rRingBufsize, static_cast<uint32_t>(l_fapirc) ); return l_fapirc; } /** * @brief MVPD Ring Function Find * * @par Detailed Description: * Step through the record looking at rings for a match. * * @param[in] i_chipletId * Chiplet ID for the op * * @param[in] i_ringId * Ring ID for the op * * @param[in] i_pRecordBuf * Pointer to record buffer * * @param[in] i_recordBufLen * Length of record buffer * * @param[out] o_rpRing * Pointer to the ring in the record, if it is there * Pointer to the start of the padding after the last * ring, if it is not there * * @param[out] o_rRingLen * Number of bytes in the ring (header and data) * Will be 0 if ring not found * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdRingFuncFind(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, const uint8_t i_chipletId, const uint8_t i_ringId, uint8_t* i_pRecordBuf, uint32_t i_recordBufLen, uint8_t*& o_rpRing, uint32_t& o_rRingLen) { fapi2::ReturnCode l_fapirc; uint8_t* l_pRing = NULL; uint32_t l_offset = 0; CompressedScanData* l_pScanData = NULL; bool l_foundflag = false; // initialize return fields in case of an error. o_rpRing = NULL; o_rRingLen = 0; FAPI_DBG("mvpdRingFuncFind: entry chipletId=0x%x, ringId=0x%x ", i_chipletId, i_ringId ); do { // Point to record l_pRing = i_pRecordBuf; // Find first RSA data block in ring (fixed offset defined by // MVPD spec) // // First byte in record should be the version number, skip // over this. // FAPI_DBG( "mvpdRingFuncFind: record version = 0x%x", *l_pRing ); l_pRing++; l_offset = 0; // point to header of first ring in record l_pScanData = reinterpret_cast<CompressedScanData*>( l_pRing + l_offset ); l_foundflag = false; // be sure that data we will look at is within the passed buffer while ( (l_offset + be32toh(l_pScanData->iv_size)) < i_recordBufLen ) { // There's only two valid header words that may appear in the Mvpd record: // - MVPD_END_OF_DATA_MAGIC which indicates end of the data with a record. // - RS4_MAGIC which indicates the beginning of another VPD ring. // - Anything else is a catastrophic failure. // Check for end of data magic word if ((be32toh(l_pScanData->iv_magic) & 0xffffff00) == (MVPD_END_OF_DATA_MAGIC & 0xffffff00)) { FAPI_DBG("mvpdRingFuncFind: Found end of data magic word (=0x%08X): " "offset=0x%x, chipletId=0x%x, ringId=0x%x", be32toh(l_pScanData->iv_magic), l_offset, i_chipletId, i_ringId); break; } // Check magic word to make sure this is valid data. FAPI_ASSERT( (be32toh(l_pScanData->iv_magic) & 0xffffff00) == (RS4_MAGIC & 0xffffff00), fapi2::MVPD_INVALID_RS4_HEADER(). set_CHIP_TARGET(i_fapiTarget). set_MVPD_RECORD(i_record). set_MVPD_KEYWORD(i_keyword), "mvpdRingFuncFind: Couldn't find RS4 or End-of-data magic word in header: " "Header=0x%x, offset=0x%x, ringId=0x%x, chipletId=0x%x", be32toh(l_pScanData->iv_magic), l_offset, i_ringId, i_chipletId ); // We can now assume good data... // Dump record info for debug FAPI_DBG("mvpdRingFuncFind:%d ringId=0x%x chipletId=0x%x" " ringlen=0x%x size=0x%x", l_offset, l_pScanData->iv_ringId, l_pScanData->iv_chipletId, be32toh(l_pScanData->iv_length), be32toh(l_pScanData->iv_size) ); if ( (l_pScanData->iv_ringId == i_ringId) && (l_pScanData->iv_chipletId == i_chipletId) ) { FAPI_DBG( "mvpdRingFuncFind: Found it: ringId=0x%x, " "chiplet=0x%x, ringlen=0x%x", i_ringId, i_chipletId, be32toh(l_pScanData->iv_length) ); // shouldn't happen, but does not all fit FAPI_ASSERT(l_offset + be32toh(l_pScanData->iv_size) <= i_recordBufLen, fapi2::MVPD_INSUFFICIENT_RECORD_SPACE(), "mvpdRingFuncFind: data does not fit " "into record buffer: ringId=0x%x, chipletId=0x%x", i_ringId, i_chipletId ); l_foundflag = true; o_rpRing = l_pRing + l_offset; o_rRingLen = be32toh(l_pScanData->iv_size); // got it, break out of scan loop break; } // being defensive. if ( be32toh(l_pScanData->iv_size) == 0) { // size of 0 is invalid, would loop forever. break; } // bump to next ring l_offset += be32toh(l_pScanData->iv_size) ; // point to header l_pScanData = reinterpret_cast<CompressedScanData*>( l_pRing + l_offset ); } // end while scan loop // if no other error and not found, indicate with 0 size. if ( !l_fapirc && ! l_foundflag ) { o_rpRing = l_pRing + l_offset; //return pointer to end of list //incase needed for appending o_rRingLen = 0; //indicate not found } } while ( 0 ); fapi_try_exit: // get current error l_fapirc = fapi2::current_err; FAPI_DBG("mvpdRingFuncFind: exit *ring= 0x%p", o_rpRing); FAPI_IMP("mvpdRingFuncFind: exit chipletId=0x%x, ringId=0x%x size=0x%x" " rc=0x%x", i_chipletId, i_ringId, o_rRingLen, static_cast<uint32_t>(l_fapirc) ); return l_fapirc; } /** * @brief MVPD Validate Ring Header * * @param[in] i_pRingBuf * Pointer to the ring in the record * * @param[in] i_chipletId * Chiplet ID for the op * * @param[in] i_ringId * Ring ID for the op * * @param[in] i_ringBufsize * Number of bytes in the ring (header and data) * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdValidateRingHeader( CompressedScanData* i_pRingBuf, uint8_t i_chipletId, uint8_t i_ringId, uint32_t i_ringBufsize) { FAPI_ASSERT(i_ringBufsize > sizeof(CompressedScanData), fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_ringBufsize failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_ASSERT((be32toh(i_pRingBuf->iv_magic) & 0xffffff00) == (RS4_MAGIC & 0xffffff00), fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_pRingBuf->iv_magic failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_ASSERT(i_pRingBuf->iv_ringId == i_ringId, fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_pRingBuf->iv_ringId failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_ASSERT(i_pRingBuf->iv_chipletId == i_chipletId, fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_pRingBuf->iv_chipletId failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_ASSERT(be32toh(i_pRingBuf->iv_size) == i_ringBufsize, fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_pRingBuf->iv_size failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); fapi_try_exit: return fapi2::current_err; } /** * @brief MVPD Get Ring Function * * @par Detailed Description: * Copy the ring back to the caller. * * @param[in] i_pRing * Pointer to the ring in the record * * @param[in] i_ringLen * Number of bytes in the ring (header and data) * * * @param[in] i_pCallerRingBuf * Pointer to the caller's ring in the record * * @param[in/out] io_rCallerRingBufLen * Number of bytes in the caller's ring * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdRingFuncGet( uint8_t* i_pRing, uint32_t i_ringLen, uint8_t* i_pCallerRingBuf, uint32_t& io_rCallerRingBufLen) { fapi2::ReturnCode l_fapirc; do { // return buffer pointer is NULL if just looking for the size if ( i_pCallerRingBuf == NULL ) { io_rCallerRingBufLen = i_ringLen; // break out of do block with success rc break; } // check if we have enough space FAPI_ASSERT(io_rCallerRingBufLen >= i_ringLen, fapi2::MVPD_RING_BUFFER_TOO_SMALL(), "mvpdRingFuncGet: output buffer too small: " "0x%x < 0x%x", io_rCallerRingBufLen, i_ringLen); // we're good, copy data into the passed-in buffer FAPI_DBG( "mvpdRingFuncGet: memcpy 0x%p 0x%p 0x%x", i_pCallerRingBuf, i_pRing, i_ringLen ); memcpy( i_pCallerRingBuf, i_pRing, i_ringLen ); io_rCallerRingBufLen = i_ringLen; } while (0); fapi_try_exit: // get current error l_fapirc = fapi2::current_err; if (l_fapirc.isRC(RC_MVPD_RING_BUFFER_TOO_SMALL)) { // return actual size of data, so caller can re-try with // the correct value io_rCallerRingBufLen = i_ringLen; } FAPI_DBG( "mvpdRingFuncGet: exit bufsize= 0x%x rc= 0x%x", io_rCallerRingBufLen, static_cast<uint32_t>(l_fapirc) ); return l_fapirc; } /** * @brief MVPD Set Ring Function * * @par Detailed Description: * Update the record with the caller's ring. * * @param[in] i_pRecordBuf * Pointer to record buffer * * @param[in] i_recordLen * Length of record buffer * * @param[in] i_pRing * Pointer to the ring in the record * * @param[in] i_ringLen * Number of bytes in the ring (header and data) * * @param[in] i_pCallerRingBuf * Pointer to the caller's ring in the record * * @param[in] i_callerRingBufLen * Number of bytes in the caller's ring * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdRingFuncSet( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, uint8_t* i_pRecordBuf, uint32_t i_recordLen, uint8_t* i_pRing, uint32_t i_ringLen, uint8_t* i_pCallerRingBuf, uint32_t i_callerRingBufLen) { fapi2::ReturnCode l_fapirc; uint8_t* l_to = NULL; uint8_t* l_fr = NULL; uint32_t l_len = 0; uint8_t* l_pRingEnd; // pointer into record to start of pad at end FAPI_DBG( "mvpdRingFuncSet: pRing=0x%p rLen=0x%x pCaller=0x%p cLen=0x%x", i_pRing, i_ringLen, i_pCallerRingBuf, i_callerRingBufLen); do { // if exact fit, update in place if (i_callerRingBufLen == i_ringLen) { l_to = i_pRing; l_fr = i_pCallerRingBuf; l_len = i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: update in place-memcpy 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memcpy (l_to, l_fr, l_len); // break out successful break; } // will need the end for shifting... look for something invalid FAPI_TRY(mvpdRingFuncFind(i_fapiTarget, i_record, i_keyword, 0x00, 0x00, i_pRecordBuf, i_recordLen, l_pRingEnd, // find start of padding l_len), "mvpdRingFuncSet: mvpdRingFuncFind failed"); FAPI_DBG( "mvpdRingFuncSet: end= 0x%p", l_pRingEnd); // if not there, then append if it fits if (i_ringLen == 0 ) //is not currently in record (0 len from find) { FAPI_ASSERT(l_pRingEnd + i_callerRingBufLen <= i_pRecordBuf + i_recordLen, fapi2::MVPD_INSUFFICIENT_RECORD_SPACE(), "mvpdRingFuncSet: not enough record space to append"); l_to = i_pRing; l_fr = i_pCallerRingBuf; l_len = i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: append-memcpy 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memcpy (l_to, l_fr, l_len); // break out successful break; } // if smaller, then shift left and zero fill if (i_callerRingBufLen < i_ringLen) { l_to = i_pRing; l_fr = i_pCallerRingBuf; l_len = i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: shrink-memcpy 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memcpy (l_to, l_fr, l_len); l_to = i_pRing + i_callerRingBufLen; l_fr = i_pRing + i_ringLen; l_len = (l_pRingEnd) - (i_pRing + i_ringLen); FAPI_DBG( "mvpdRingFuncSet: shrink-memmove 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memmove (l_to, l_fr, l_len); //use memmove, always overlaps. l_to = (l_pRingEnd) - (i_ringLen - i_callerRingBufLen); l_len = i_ringLen - i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: shrink-memset 0x%p 0x%x 0x%x", l_to, 0x00, l_len); memset (l_to, 0x00, l_len); // break out successful break; } // if larger, then shift right, if it fits if (i_callerRingBufLen > i_ringLen) { // ensure the padding can contain the growth FAPI_ASSERT((l_pRingEnd + (i_callerRingBufLen - i_ringLen)) <= (i_pRecordBuf + i_recordLen), fapi2::MVPD_INSUFFICIENT_RECORD_SPACE(), "mvpdRingFuncSet: not enough record space to insert "); l_to = i_pRing + i_callerRingBufLen; l_fr = i_pRing + i_ringLen; l_len = l_pRingEnd - (i_pRing + i_ringLen); FAPI_DBG( "mvpdRingFuncSet: insert-memmove 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memmove (l_to, l_fr, l_len); l_to = i_pRing; l_fr = i_pCallerRingBuf; l_len = i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: insert-memcpy 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memcpy (l_to, l_fr, l_len); // break out successful break; } FAPI_ERR( "mvpdRingFuncSet: shouldn't get to here" ); } while (0); fapi_try_exit: // get current error l_fapirc = fapi2::current_err; FAPI_DBG( "mvpdRingFuncSet: exit rc= 0x%x", static_cast<uint32_t>(l_fapirc) ); return l_fapirc; } } // extern "C" Mvpd accessor and xip_customize: Quieting down trace noise from RING_NOT_FOUND FFDC capturing (for PowerOn only). Change-Id: I0009676e1a6ecce0f633c50a81594506356ebeb4 Original-Change-Id: I5aa3de25ced5cf90022d75d74e9d64d9ef982e2b Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/28981 Tested-by: Jenkins Server <8e3f934e4c44875bc48d33da3ea13d93ba9a233f@us.ibm.com> Reviewed-by: Martin Gloff <df0a4963746ae04ab678d064fccc7ee68adfd751@us.ibm.com> Tested-by: Hostboot CI <52521565bd8ea18a2b112942dce4f4220a97c2c8@us.ibm.com> Reviewed-by: Kahn C. Evans <88417bcf564329fca88ff3071c3628a57ed3e5c7@us.ibm.com> Reviewed-by: Prachi Gupta <25a72946fc4ec2539bba3cff1fbb2916af6a7649@us.ibm.com> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/accessors/p9_mvpd_ring_funcs.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ // $Id: p9_mvpd_ring_funcs.C,v 1.12 2014/07/16 19:06:49 cswenson Exp $ /** * @file p9_mvpd_ring_funcs.C * * @brief common routines * */ #include <stdint.h> // fapi2 support #include <fapi2.H> #include <utils.H> #include <mvpd_access.H> #include <p9_mvpd_ring_funcs.H> // pull in CompressedScanData def from proc_slw_build HWP #include <p9_scan_compression.H> #include <p9_ring_identification.H> extern "C" { using namespace fapi2; // functions internal to this file // these functions are common for both mvpdRingFunc and mbvpdRingFunc fapi2::ReturnCode mvpdValidateRingHeader( CompressedScanData* i_pRing, uint8_t i_chipletId, uint8_t i_ringId, uint32_t i_ringBufsize); fapi2::ReturnCode mvpdRingFuncFind( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, const uint8_t i_chipletId, const uint8_t i_ringId, uint8_t* i_pRecordBuf, uint32_t i_recordBufLenfapi, uint8_t*& o_rRingBuf, uint32_t& o_rRingBufsize); fapi2::ReturnCode mvpdRingFuncGet( uint8_t* i_pRing, uint32_t i_ringLen, uint8_t* i_pCallerRingBuf, uint32_t& io_rCallerRingBufLen); fapi2::ReturnCode mvpdRingFuncSet( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, uint8_t* i_pRecordBuf, uint32_t i_recordLen, uint8_t* i_pRing, uint32_t i_ringLen, uint8_t* i_pCallerRingBuf, uint32_t i_callerRingBufLen); // add record/keywords with rings with RS4 header here. struct _supportedRecordKeywords { fapi2::MvpdRecord record; fapi2::MvpdKeyword keyword; } supportedRecordKeywords [] = { { MVPD_RECORD_CP00, MVPD_KEYWORD_PDR }, { MVPD_RECORD_CP00, MVPD_KEYWORD_PDG }, }; /** * @brief Validate Record and Keyword Combination * * @par Detailed Description: * Check for supported combinations of Record and Keyword. * The record needs to contain rings of RS4 header * (CompressedScanData) format. * * @param[in] i_record * Record to validate * * @param[in] i_keyword * Keyword to validate * * @note: "Getting" data not in RS4 header format would likely just * fail to find the ring harmlessly. "Setting" data could * make a mess looking for the end to append a new ring. The * result could be invalid vpd. * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdValidateRecordKeyword( fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword) { fapi2::ReturnCode l_fapirc; bool l_validPair = false; const uint32_t numPairs = sizeof(supportedRecordKeywords) / sizeof(supportedRecordKeywords[0]); for (uint32_t curPair = 0; curPair < numPairs; curPair++ ) { if (supportedRecordKeywords[curPair].record == i_record && supportedRecordKeywords[curPair].keyword == i_keyword) { l_validPair = true; break; } } if ( !l_validPair ) { FAPI_SET_HWP_ERROR(l_fapirc, RC_MVPD_RING_FUNC_INVALID_PARAMETER ); } return l_fapirc; }; /** * @brief MVPD Ring Function * * @par Detailed Description: * The getMvpdRing and setMvpdRing wrappers call this function * to do all the processing. * * @param[in] i_mvpdRingFuncOp * MVPD ring function op to process * * @param[in] i_record * Record in the MVPD * * @param[in] i_keyword * Keyword for the MVPD record * * @param[in] i_fapiTarget * FAPI target for the op * * @param[in] i_chipletId * Chiplet ID for the op * * @param[in] i_ringId * Ring ID for the op * * @param[in] i_pRingBuf * Pointer to ring buffer with set data * * @param[in/out] io_rRingBufsize * Size of ring buffer * * @note: io_rRingBufsize is only an 'output' for get function. * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdRingFunc(const mvpdRingFuncOp i_mvpdRingFuncOp, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, const uint8_t i_chipletId, const uint8_t i_ringId, uint8_t* i_pRingBuf, uint32_t& io_rRingBufsize) { fapi2::ReturnCode l_fapirc = fapi2::FAPI2_RC_SUCCESS; uint32_t l_recordLen = 0; uint8_t* l_recordBuf = NULL; uint8_t* l_pRing = NULL; uint32_t l_ringLen = 0; FAPI_DBG("mvpdRingFunc:entry op=0x%x ringId=0x%x chipletId=0x%x " "size=0x%x", i_mvpdRingFuncOp, i_ringId, i_chipletId, io_rRingBufsize ); // do common get and set input parameter error checks // check for supported combination of Record and Keyword FAPI_TRY(mvpdValidateRecordKeyword(i_record, i_keyword), "mvpdRingFunc: unsupported record keyword pair " "record=0x%x, keyword=0x%x", i_record, i_keyword); // do set specific input parameter checks if (i_mvpdRingFuncOp == MVPD_RING_SET ) { // passing NULL pointer to receive needed size is only for get. FAPI_ASSERT(i_pRingBuf != NULL, fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdRingFunc: NULL ring buffer pointer passed " "to set function chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); // Validate ring header to protect vpd FAPI_TRY(mvpdValidateRingHeader( reinterpret_cast<CompressedScanData*>(i_pRingBuf), i_chipletId, i_ringId, io_rRingBufsize), "mvpdRingFunc: invalid ring header " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); } // call getMvpdField once with a NULL pointer to get the buffer // size no error should be returned. FAPI_TRY(getMvpdField(i_record, i_keyword, i_fapiTarget, NULL, l_recordLen ), "mvpdRingFunc: getMvpdField failed to get buffer size " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_DBG( "mvpdRingFunc: getMvpdField returned record len=0x%x", l_recordLen ); // allocate buffer for the record. Always works l_recordBuf = static_cast<uint8_t*>(malloc((size_t)l_recordLen)); // load ring from MVPD for this target FAPI_TRY(getMvpdField(i_record, i_keyword, i_fapiTarget, l_recordBuf, l_recordLen ), "mvpdRingFunc: getMvpdField failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); // find ring in the record. It is an error if not there for a "get". // Its ok if not there for a "set". The ring will be added. // l_ringLen set to 0 if not there with l_pRing at the start of padding. FAPI_TRY(mvpdRingFuncFind(i_fapiTarget, i_record, i_keyword, i_chipletId, i_ringId, l_recordBuf, l_recordLen, l_pRing, l_ringLen), "mvpdRingFunc: mvpdRingFuncFind failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); // do the get or set specific operations if (i_mvpdRingFuncOp == MVPD_RING_GET ) // do the get operation { // Ensure ring was found. Must be there for "get" //@TODO: Uncomment the following after PowerOn. Also, need to come // to agreement whether this should be fatal error or not. // For now, for PO, it's considered benign and noise and is // being commented out... most of it at least. FAPI_ASSERT( l_ringLen != 0, fapi2::MVPD_RING_NOT_FOUND(). set_CHIP_TARGET(i_fapiTarget) ); //FAPI_ASSERT(l_ringLen != 0, // fapi2::MVPD_RING_NOT_FOUND(). // set_CHIP_TARGET(i_fapiTarget). // set_RING_ID(i_ringId). // set_CHIPLET_ID(i_chipletId), // "mvpdRingFunc: mvpdRingFuncFind did not find ring"); // copy ring back to caller's buffer FAPI_TRY(mvpdRingFuncGet(l_pRing, l_ringLen, i_pRingBuf, io_rRingBufsize), "mvpdRingFunc: mvpdRingFuncGet failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); } else // set operation { // update record with caller's ring FAPI_TRY(mvpdRingFuncSet(i_fapiTarget, i_record, i_keyword, l_recordBuf, l_recordLen, l_pRing, l_ringLen, i_pRingBuf, io_rRingBufsize), "mvpdRingFunc: mvpdRingFuncSet failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); // update record back to the mvpd FAPI_TRY(setMvpdField(i_record, i_keyword, i_fapiTarget, l_recordBuf, l_recordLen), "mvpdRingFunc: setMvpdField failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); } fapi_try_exit: // get current error l_fapirc = fapi2::current_err; // unload the repair ring if allocated if(l_recordBuf) { free(static_cast<void*>(l_recordBuf)); l_recordBuf = NULL; } if((i_mvpdRingFuncOp != MVPD_RING_GET) && l_fapirc) { io_rRingBufsize = 0; } FAPI_DBG( "mvpdRingFunc: exit bufsize= 0x%x rc= 0x%x", io_rRingBufsize, static_cast<uint32_t>(l_fapirc) ); return l_fapirc; } /** * @brief MVPD Ring Function Find * * @par Detailed Description: * Step through the record looking at rings for a match. * * @param[in] i_chipletId * Chiplet ID for the op * * @param[in] i_ringId * Ring ID for the op * * @param[in] i_pRecordBuf * Pointer to record buffer * * @param[in] i_recordBufLen * Length of record buffer * * @param[out] o_rpRing * Pointer to the ring in the record, if it is there * Pointer to the start of the padding after the last * ring, if it is not there * * @param[out] o_rRingLen * Number of bytes in the ring (header and data) * Will be 0 if ring not found * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdRingFuncFind(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, const uint8_t i_chipletId, const uint8_t i_ringId, uint8_t* i_pRecordBuf, uint32_t i_recordBufLen, uint8_t*& o_rpRing, uint32_t& o_rRingLen) { fapi2::ReturnCode l_fapirc; uint8_t* l_pRing = NULL; uint32_t l_offset = 0; CompressedScanData* l_pScanData = NULL; bool l_foundflag = false; // initialize return fields in case of an error. o_rpRing = NULL; o_rRingLen = 0; FAPI_DBG("mvpdRingFuncFind: entry chipletId=0x%x, ringId=0x%x ", i_chipletId, i_ringId ); do { // Point to record l_pRing = i_pRecordBuf; // Find first RSA data block in ring (fixed offset defined by // MVPD spec) // // First byte in record should be the version number, skip // over this. // FAPI_DBG( "mvpdRingFuncFind: record version = 0x%x", *l_pRing ); l_pRing++; l_offset = 0; // point to header of first ring in record l_pScanData = reinterpret_cast<CompressedScanData*>( l_pRing + l_offset ); l_foundflag = false; // be sure that data we will look at is within the passed buffer while ( (l_offset + be32toh(l_pScanData->iv_size)) < i_recordBufLen ) { // There's only two valid header words that may appear in the Mvpd record: // - MVPD_END_OF_DATA_MAGIC which indicates end of the data with a record. // - RS4_MAGIC which indicates the beginning of another VPD ring. // - Anything else is a catastrophic failure. // Check for end of data magic word if ((be32toh(l_pScanData->iv_magic) & 0xffffff00) == (MVPD_END_OF_DATA_MAGIC & 0xffffff00)) { FAPI_DBG("mvpdRingFuncFind: Found end of data magic word (=0x%08X): " "offset=0x%x, chipletId=0x%x, ringId=0x%x", be32toh(l_pScanData->iv_magic), l_offset, i_chipletId, i_ringId); break; } // Check magic word to make sure this is valid data. FAPI_ASSERT( (be32toh(l_pScanData->iv_magic) & 0xffffff00) == (RS4_MAGIC & 0xffffff00), fapi2::MVPD_INVALID_RS4_HEADER(). set_CHIP_TARGET(i_fapiTarget). set_MVPD_RECORD(i_record). set_MVPD_KEYWORD(i_keyword), "mvpdRingFuncFind: Couldn't find RS4 or End-of-data magic word in header: " "Header=0x%x, offset=0x%x, ringId=0x%x, chipletId=0x%x", be32toh(l_pScanData->iv_magic), l_offset, i_ringId, i_chipletId ); // We can now assume good data... // Dump record info for debug FAPI_DBG("mvpdRingFuncFind:%d ringId=0x%x chipletId=0x%x" " ringlen=0x%x size=0x%x", l_offset, l_pScanData->iv_ringId, l_pScanData->iv_chipletId, be32toh(l_pScanData->iv_length), be32toh(l_pScanData->iv_size) ); if ( (l_pScanData->iv_ringId == i_ringId) && (l_pScanData->iv_chipletId == i_chipletId) ) { FAPI_DBG( "mvpdRingFuncFind: Found it: ringId=0x%x, " "chiplet=0x%x, ringlen=0x%x", i_ringId, i_chipletId, be32toh(l_pScanData->iv_length) ); // shouldn't happen, but does not all fit FAPI_ASSERT(l_offset + be32toh(l_pScanData->iv_size) <= i_recordBufLen, fapi2::MVPD_INSUFFICIENT_RECORD_SPACE(), "mvpdRingFuncFind: data does not fit " "into record buffer: ringId=0x%x, chipletId=0x%x", i_ringId, i_chipletId ); l_foundflag = true; o_rpRing = l_pRing + l_offset; o_rRingLen = be32toh(l_pScanData->iv_size); // got it, break out of scan loop break; } // being defensive. if ( be32toh(l_pScanData->iv_size) == 0) { // size of 0 is invalid, would loop forever. break; } // bump to next ring l_offset += be32toh(l_pScanData->iv_size) ; // point to header l_pScanData = reinterpret_cast<CompressedScanData*>( l_pRing + l_offset ); } // end while scan loop // if no other error and not found, indicate with 0 size. if ( !l_fapirc && ! l_foundflag ) { o_rpRing = l_pRing + l_offset; //return pointer to end of list //incase needed for appending o_rRingLen = 0; //indicate not found } } while ( 0 ); fapi_try_exit: // get current error l_fapirc = fapi2::current_err; FAPI_DBG("mvpdRingFuncFind: exit *ring= 0x%p", o_rpRing); FAPI_IMP("mvpdRingFuncFind: exit chipletId=0x%x, ringId=0x%x size=0x%x" " rc=0x%x", i_chipletId, i_ringId, o_rRingLen, static_cast<uint32_t>(l_fapirc) ); return l_fapirc; } /** * @brief MVPD Validate Ring Header * * @param[in] i_pRingBuf * Pointer to the ring in the record * * @param[in] i_chipletId * Chiplet ID for the op * * @param[in] i_ringId * Ring ID for the op * * @param[in] i_ringBufsize * Number of bytes in the ring (header and data) * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdValidateRingHeader( CompressedScanData* i_pRingBuf, uint8_t i_chipletId, uint8_t i_ringId, uint32_t i_ringBufsize) { FAPI_ASSERT(i_ringBufsize > sizeof(CompressedScanData), fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_ringBufsize failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_ASSERT((be32toh(i_pRingBuf->iv_magic) & 0xffffff00) == (RS4_MAGIC & 0xffffff00), fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_pRingBuf->iv_magic failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_ASSERT(i_pRingBuf->iv_ringId == i_ringId, fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_pRingBuf->iv_ringId failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_ASSERT(i_pRingBuf->iv_chipletId == i_chipletId, fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_pRingBuf->iv_chipletId failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); FAPI_ASSERT(be32toh(i_pRingBuf->iv_size) == i_ringBufsize, fapi2::MVPD_RING_FUNC_INVALID_PARAMETER(), "mvpdValidateRingHeader: i_pRingBuf->iv_size failed " "chipletId=0x%x, ringId=0x%x", i_chipletId, i_ringId); fapi_try_exit: return fapi2::current_err; } /** * @brief MVPD Get Ring Function * * @par Detailed Description: * Copy the ring back to the caller. * * @param[in] i_pRing * Pointer to the ring in the record * * @param[in] i_ringLen * Number of bytes in the ring (header and data) * * * @param[in] i_pCallerRingBuf * Pointer to the caller's ring in the record * * @param[in/out] io_rCallerRingBufLen * Number of bytes in the caller's ring * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdRingFuncGet( uint8_t* i_pRing, uint32_t i_ringLen, uint8_t* i_pCallerRingBuf, uint32_t& io_rCallerRingBufLen) { fapi2::ReturnCode l_fapirc; do { // return buffer pointer is NULL if just looking for the size if ( i_pCallerRingBuf == NULL ) { io_rCallerRingBufLen = i_ringLen; // break out of do block with success rc break; } // check if we have enough space FAPI_ASSERT(io_rCallerRingBufLen >= i_ringLen, fapi2::MVPD_RING_BUFFER_TOO_SMALL(), "mvpdRingFuncGet: output buffer too small: " "0x%x < 0x%x", io_rCallerRingBufLen, i_ringLen); // we're good, copy data into the passed-in buffer FAPI_DBG( "mvpdRingFuncGet: memcpy 0x%p 0x%p 0x%x", i_pCallerRingBuf, i_pRing, i_ringLen ); memcpy( i_pCallerRingBuf, i_pRing, i_ringLen ); io_rCallerRingBufLen = i_ringLen; } while (0); fapi_try_exit: // get current error l_fapirc = fapi2::current_err; if (l_fapirc.isRC(RC_MVPD_RING_BUFFER_TOO_SMALL)) { // return actual size of data, so caller can re-try with // the correct value io_rCallerRingBufLen = i_ringLen; } FAPI_DBG( "mvpdRingFuncGet: exit bufsize= 0x%x rc= 0x%x", io_rCallerRingBufLen, static_cast<uint32_t>(l_fapirc) ); return l_fapirc; } /** * @brief MVPD Set Ring Function * * @par Detailed Description: * Update the record with the caller's ring. * * @param[in] i_pRecordBuf * Pointer to record buffer * * @param[in] i_recordLen * Length of record buffer * * @param[in] i_pRing * Pointer to the ring in the record * * @param[in] i_ringLen * Number of bytes in the ring (header and data) * * @param[in] i_pCallerRingBuf * Pointer to the caller's ring in the record * * @param[in] i_callerRingBufLen * Number of bytes in the caller's ring * * @return fapi2::ReturnCode */ fapi2::ReturnCode mvpdRingFuncSet( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_fapiTarget, fapi2::MvpdRecord i_record, fapi2::MvpdKeyword i_keyword, uint8_t* i_pRecordBuf, uint32_t i_recordLen, uint8_t* i_pRing, uint32_t i_ringLen, uint8_t* i_pCallerRingBuf, uint32_t i_callerRingBufLen) { fapi2::ReturnCode l_fapirc; uint8_t* l_to = NULL; uint8_t* l_fr = NULL; uint32_t l_len = 0; uint8_t* l_pRingEnd; // pointer into record to start of pad at end FAPI_DBG( "mvpdRingFuncSet: pRing=0x%p rLen=0x%x pCaller=0x%p cLen=0x%x", i_pRing, i_ringLen, i_pCallerRingBuf, i_callerRingBufLen); do { // if exact fit, update in place if (i_callerRingBufLen == i_ringLen) { l_to = i_pRing; l_fr = i_pCallerRingBuf; l_len = i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: update in place-memcpy 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memcpy (l_to, l_fr, l_len); // break out successful break; } // will need the end for shifting... look for something invalid FAPI_TRY(mvpdRingFuncFind(i_fapiTarget, i_record, i_keyword, 0x00, 0x00, i_pRecordBuf, i_recordLen, l_pRingEnd, // find start of padding l_len), "mvpdRingFuncSet: mvpdRingFuncFind failed"); FAPI_DBG( "mvpdRingFuncSet: end= 0x%p", l_pRingEnd); // if not there, then append if it fits if (i_ringLen == 0 ) //is not currently in record (0 len from find) { FAPI_ASSERT(l_pRingEnd + i_callerRingBufLen <= i_pRecordBuf + i_recordLen, fapi2::MVPD_INSUFFICIENT_RECORD_SPACE(), "mvpdRingFuncSet: not enough record space to append"); l_to = i_pRing; l_fr = i_pCallerRingBuf; l_len = i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: append-memcpy 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memcpy (l_to, l_fr, l_len); // break out successful break; } // if smaller, then shift left and zero fill if (i_callerRingBufLen < i_ringLen) { l_to = i_pRing; l_fr = i_pCallerRingBuf; l_len = i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: shrink-memcpy 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memcpy (l_to, l_fr, l_len); l_to = i_pRing + i_callerRingBufLen; l_fr = i_pRing + i_ringLen; l_len = (l_pRingEnd) - (i_pRing + i_ringLen); FAPI_DBG( "mvpdRingFuncSet: shrink-memmove 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memmove (l_to, l_fr, l_len); //use memmove, always overlaps. l_to = (l_pRingEnd) - (i_ringLen - i_callerRingBufLen); l_len = i_ringLen - i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: shrink-memset 0x%p 0x%x 0x%x", l_to, 0x00, l_len); memset (l_to, 0x00, l_len); // break out successful break; } // if larger, then shift right, if it fits if (i_callerRingBufLen > i_ringLen) { // ensure the padding can contain the growth FAPI_ASSERT((l_pRingEnd + (i_callerRingBufLen - i_ringLen)) <= (i_pRecordBuf + i_recordLen), fapi2::MVPD_INSUFFICIENT_RECORD_SPACE(), "mvpdRingFuncSet: not enough record space to insert "); l_to = i_pRing + i_callerRingBufLen; l_fr = i_pRing + i_ringLen; l_len = l_pRingEnd - (i_pRing + i_ringLen); FAPI_DBG( "mvpdRingFuncSet: insert-memmove 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memmove (l_to, l_fr, l_len); l_to = i_pRing; l_fr = i_pCallerRingBuf; l_len = i_callerRingBufLen; FAPI_DBG( "mvpdRingFuncSet: insert-memcpy 0x%p 0x%p 0x%x", l_to, l_fr, l_len); memcpy (l_to, l_fr, l_len); // break out successful break; } FAPI_ERR( "mvpdRingFuncSet: shouldn't get to here" ); } while (0); fapi_try_exit: // get current error l_fapirc = fapi2::current_err; FAPI_DBG( "mvpdRingFuncSet: exit rc= 0x%x", static_cast<uint32_t>(l_fapirc) ); return l_fapirc; } } // extern "C"
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "coretext/common.h" #ifdef MACOSX #include "aqua/salframe.h" #include "coretext/salgdi.h" #else #include <premac.h> #include <UIKit/UIKit.h> #include <postmac.h> #include <basebmp/scanlineformats.hxx> #include "saldatabasic.hxx" #include "headless/svpframe.hxx" #include "headless/svpgdi.hxx" #endif #include "coretext/salcoretextstyle.hxx" #ifdef MACOSX QuartzSalGraphics::QuartzSalGraphics() : mpFrame( NULL ) , mxLayer( NULL ) , mrContext( NULL ) , mpXorEmulation( NULL ) , mnXorMode( 0 ) , mnWidth( 0 ) , mnHeight( 0 ) , mnBitmapDepth( 0 ) , mnRealDPIX( 0 ) , mnRealDPIY( 0 ) , mfFakeDPIScale( 1.0 ) , mxClipPath( NULL ) , maLineColor( COL_WHITE ) , maFillColor( COL_BLACK ) , mbNonAntialiasedText( false ) , mbPrinter( false ) , mbVirDev( false ) , mbWindow( false ) { SAL_INFO( "vcl.coretext.gr", "QuartzSalGraphics::QuartzSalGraphics() " << this ); m_style = new CoreTextStyleInfo(); } QuartzSalGraphics::~QuartzSalGraphics() { SAL_INFO( "vcl.coretext.gr", "~QuartzSalGraphics(" << this << ")" ); if(m_style) { delete m_style; m_style = NULL; } } #endif inline bool QuartzSalGraphics::AddTempDevFont( ImplDevFontList*, const OUString& , const OUString& ) { OSL_ASSERT( FALSE ); return false; } void QuartzSalGraphics::DrawServerFontLayout( const ServerFontLayout& ) { } void QuartzSalGraphics::FreeEmbedFontData( const void* pData, long /*nDataLen*/ ) { // TODO: implementing this only makes sense when the implementation of // QuartzSalGraphics::GetEmbedFontData() returns non-NULL (void)pData; DBG_ASSERT( (pData!=NULL), "QuartzSalGraphics::FreeEmbedFontData() is not implemented\n"); } void QuartzSalGraphics::GetDevFontList( ImplDevFontList* pFontList ) { DBG_ASSERT( pFontList, "QuartzSalGraphics::GetDevFontList(NULL) !"); SalData* pSalData = GetSalData(); if (pSalData->mpFontList == NULL) { pSalData->mpFontList = new SystemFontList(); } // Copy all PhysicalFontFace objects contained in the SystemFontList pSalData->mpFontList->AnnounceFonts( *pFontList ); } void QuartzSalGraphics::ClearDevFontCache() { SalData* pSalData = GetSalData(); delete pSalData->mpFontList; pSalData->mpFontList = NULL; } void QuartzSalGraphics::GetDevFontSubstList( OutputDevice* ) { // nothing to do since there are no device-specific fonts on Aqua } const void* QuartzSalGraphics::GetEmbedFontData( const PhysicalFontFace*, const sal_Ucs* /*pUnicodes*/, sal_Int32* /*pWidths*/, FontSubsetInfo&, long* /*pDataLen*/ ) { return NULL; } const Ucs2SIntMap* QuartzSalGraphics::GetFontEncodingVector(const PhysicalFontFace*, const Ucs2OStrMap** /*ppNonEncoded*/ ) { return NULL; } void QuartzSalGraphics::GetFontMetric( ImplFontMetricData* pMetric, int nFallbackLevel ) { (void)nFallbackLevel; // glyph-fallback on CoreText is done differently -> no fallback level pMetric->mbScalableFont = true; pMetric->mbKernableFont = true; CTFontRef font = m_style->GetFont(); DBG_ASSERT(font, "GetFontMetric without font set in style"); pMetric->mnAscent = static_cast<long>( CTFontGetAscent(font) * mfFakeDPIScale + 0.5); pMetric->mnDescent = static_cast<long>(CTFontGetDescent(font) * mfFakeDPIScale + 0.5); const long nExtDescent = static_cast<long>((CTFontGetLeading(font) + CTFontGetDescent(font)) * mfFakeDPIScale + 0.5); pMetric->mnExtLeading = nExtDescent + pMetric->mnDescent; pMetric->mnIntLeading = 0; pMetric->mnWidth = m_style->GetFontStretchedSize(); SAL_INFO( "vcl.coretext.gr", "GetFontMetric(" << this << ") returning: {ascent=" << pMetric->mnAscent << ",descent=" << pMetric->mnDescent << ",extleading=" << pMetric->mnExtLeading << ",intleading=" << pMetric->mnIntLeading << ",width=" << pMetric->mnWidth << "}" ); } sal_Bool QuartzSalGraphics::GetGlyphBoundRect( sal_GlyphId /*nGlyphId*/, Rectangle& /*rRect*/ ) { /* TODO: create a Ghyph iterator to keep track ot 'state' between call */ return false; } sal_Bool QuartzSalGraphics::GetGlyphOutline( sal_GlyphId /*nGlyphId*/, basegfx::B2DPolyPolygon& /*rPolyPoly*/ ) { /* TODO */ return false; } void QuartzSalGraphics::GetGlyphWidths( const PhysicalFontFace* /*pFontData*/, bool /*bVertical*/, Int32Vector& /*rGlyphWidths*/, Ucs2UIntMap& /*rUnicodeEnc*/ ) { } sal_uLong QuartzSalGraphics::GetKernPairs( sal_uLong, ImplKernPairData* ) { return 0; } bool QuartzSalGraphics::GetImplFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const { if( !m_style ) { return false; } CoreTextPhysicalFontFace* font_face = m_style->GetFontFace(); if( !font_face) { return false; } return font_face->GetImplFontCapabilities(rFontCapabilities); } const ImplFontCharMap* QuartzSalGraphics::GetImplFontCharMap() const { if( !m_style ) { return NULL; } CoreTextPhysicalFontFace* font_face = m_style->GetFontFace(); if( !font_face) { return ImplFontCharMap::GetDefaultMap(); } return font_face->GetImplFontCharMap(); } #ifndef IOS bool QuartzSalGraphics::GetRawFontData( const PhysicalFontFace* pFontFace, std::vector<unsigned char>& rBuffer, bool* pJustCFF ) { const CoreTextPhysicalFontFace* font_face = static_cast<const CoreTextPhysicalFontFace*>(pFontFace); return font_face->GetRawFontData(rBuffer, pJustCFF); } #endif SystemFontData QuartzSalGraphics::GetSysFontData( int /* nFallbacklevel */ ) const { SystemFontData aSysFontData; aSysFontData.nSize = sizeof( SystemFontData ); aSysFontData.bAntialias = true; CTFontRef font = CTFontCreateUIFontForLanguage(kCTFontSystemFontType, 0.0, NULL); font = (CTFontRef)CFRetain(font); aSysFontData.rCTFont = font; CTFontRef italic_font = CTFontCreateCopyWithSymbolicTraits( font, 0.0, NULL, kCTFontItalicTrait, kCTFontItalicTrait + kCTFontBoldTrait); aSysFontData.bFakeItalic = italic_font ? false : true; SafeCFRelease(italic_font); CTFontRef bold_font = CTFontCreateCopyWithSymbolicTraits( font, 0.0, NULL, kCTFontBoldTrait, kCTFontItalicTrait + kCTFontBoldTrait); aSysFontData.bFakeBold = bold_font ? false : true; SafeCFRelease(bold_font); CTFontRef vertical_font = CTFontCreateCopyWithSymbolicTraits( font, 0.0, NULL, kCTFontVerticalTrait, kCTFontVerticalTrait); aSysFontData.bVerticalCharacterType = vertical_font ? true : false; SafeCFRelease(vertical_font); return aSysFontData; } sal_uInt16 QuartzSalGraphics::SetFont( FontSelectPattern* pReqFont, int /*nFallbackLevel*/ ) { m_style->SetFont(pReqFont); return 0; } void QuartzSalGraphics::SetTextColor( SalColor nSalColor ) { m_style->SetColor(nSalColor); } #ifdef IOS // Note that "QuartzSalGraphics" *is* SvpSalGraphics for iOS bool SvpSalGraphics::CheckContext() { const basegfx::B2IVector size = m_aDevice->getSize(); const basegfx::B2IVector bufferSize = m_aDevice->getBufferSize(); const sal_Int32 scanlineStride = m_aDevice->getScanlineStride(); basebmp::RawMemorySharedArray pixelBuffer = m_aDevice->getBuffer(); SAL_INFO( "vcl.ios", "CheckContext: device=" << m_aDevice.get() << " size=" << size.getX() << "x" << size.getY() << (m_aDevice->isTopDown() ? " top-down" : " bottom-up") << " stride=" << scanlineStride << " bufferSize=(" << bufferSize.getX() << "," << bufferSize.getY() << ")" ); switch( m_aDevice->getScanlineFormat() ) { case basebmp::Format::EIGHT_BIT_PAL: mrContext = CGBitmapContextCreate(pixelBuffer.get(), bufferSize.getX(), bufferSize.getY(), 8, scanlineStride, CGColorSpaceCreateDeviceGray(), kCGImageAlphaNone); break; case basebmp::Format::THIRTYTWO_BIT_TC_MASK_RGBA: mrContext = CGBitmapContextCreate(pixelBuffer.get(), bufferSize.getX(), bufferSize.getY(), 8, scanlineStride, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast); break; default: SAL_INFO( "vcl.ios", "CheckContext: unsupported color format " << basebmp::Format::formatName( m_aDevice->getScanlineFormat() ) ); } SAL_WARN_IF( mrContext == NULL, "vcl.ios", "CheckContext() failed" ); // Should we also clip the context? (Then we need to add a // getBounds() function to BitmapDevice.) if( mrContext != NULL && m_aDevice->isTopDown() ) { CGContextTranslateCTM( mrContext, 0, bufferSize.getY() ); CGContextScaleCTM( mrContext, 1, -1 ); } SAL_INFO( "vcl.ios", "CheckContext: context=" << mrContext ); return ( mrContext != NULL ); } CGContextRef SvpSalGraphics::GetContext() { if ( !mrContext ) CheckContext(); return mrContext; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ [coretext] Fix line spacing It should have been nExtDescent + pMetric->mnDescent, but then the whole thing does not make any sense; why add the descent to the leading and then calculate the leading by subtracting the descent! (well, the ATSUI code was doing this but it makes no sense either). Just use CTFontGetLeading() directly. Change-Id: Ia54648f6c02c11359865f4aa6476adf40b27f906 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "coretext/common.h" #ifdef MACOSX #include "aqua/salframe.h" #include "coretext/salgdi.h" #else #include <premac.h> #include <UIKit/UIKit.h> #include <postmac.h> #include <basebmp/scanlineformats.hxx> #include "saldatabasic.hxx" #include "headless/svpframe.hxx" #include "headless/svpgdi.hxx" #endif #include "coretext/salcoretextstyle.hxx" #ifdef MACOSX QuartzSalGraphics::QuartzSalGraphics() : mpFrame( NULL ) , mxLayer( NULL ) , mrContext( NULL ) , mpXorEmulation( NULL ) , mnXorMode( 0 ) , mnWidth( 0 ) , mnHeight( 0 ) , mnBitmapDepth( 0 ) , mnRealDPIX( 0 ) , mnRealDPIY( 0 ) , mfFakeDPIScale( 1.0 ) , mxClipPath( NULL ) , maLineColor( COL_WHITE ) , maFillColor( COL_BLACK ) , mbNonAntialiasedText( false ) , mbPrinter( false ) , mbVirDev( false ) , mbWindow( false ) { SAL_INFO( "vcl.coretext.gr", "QuartzSalGraphics::QuartzSalGraphics() " << this ); m_style = new CoreTextStyleInfo(); } QuartzSalGraphics::~QuartzSalGraphics() { SAL_INFO( "vcl.coretext.gr", "~QuartzSalGraphics(" << this << ")" ); if(m_style) { delete m_style; m_style = NULL; } } #endif inline bool QuartzSalGraphics::AddTempDevFont( ImplDevFontList*, const OUString& , const OUString& ) { OSL_ASSERT( FALSE ); return false; } void QuartzSalGraphics::DrawServerFontLayout( const ServerFontLayout& ) { } void QuartzSalGraphics::FreeEmbedFontData( const void* pData, long /*nDataLen*/ ) { // TODO: implementing this only makes sense when the implementation of // QuartzSalGraphics::GetEmbedFontData() returns non-NULL (void)pData; DBG_ASSERT( (pData!=NULL), "QuartzSalGraphics::FreeEmbedFontData() is not implemented\n"); } void QuartzSalGraphics::GetDevFontList( ImplDevFontList* pFontList ) { DBG_ASSERT( pFontList, "QuartzSalGraphics::GetDevFontList(NULL) !"); SalData* pSalData = GetSalData(); if (pSalData->mpFontList == NULL) { pSalData->mpFontList = new SystemFontList(); } // Copy all PhysicalFontFace objects contained in the SystemFontList pSalData->mpFontList->AnnounceFonts( *pFontList ); } void QuartzSalGraphics::ClearDevFontCache() { SalData* pSalData = GetSalData(); delete pSalData->mpFontList; pSalData->mpFontList = NULL; } void QuartzSalGraphics::GetDevFontSubstList( OutputDevice* ) { // nothing to do since there are no device-specific fonts on Aqua } const void* QuartzSalGraphics::GetEmbedFontData( const PhysicalFontFace*, const sal_Ucs* /*pUnicodes*/, sal_Int32* /*pWidths*/, FontSubsetInfo&, long* /*pDataLen*/ ) { return NULL; } const Ucs2SIntMap* QuartzSalGraphics::GetFontEncodingVector(const PhysicalFontFace*, const Ucs2OStrMap** /*ppNonEncoded*/ ) { return NULL; } void QuartzSalGraphics::GetFontMetric( ImplFontMetricData* pMetric, int nFallbackLevel ) { (void)nFallbackLevel; // glyph-fallback on CoreText is done differently -> no fallback level pMetric->mbScalableFont = true; pMetric->mbKernableFont = true; CTFontRef font = m_style->GetFont(); DBG_ASSERT(font, "GetFontMetric without font set in style"); pMetric->mnAscent = static_cast<long>( CTFontGetAscent(font) * mfFakeDPIScale + 0.5); pMetric->mnDescent = static_cast<long>(CTFontGetDescent(font) * mfFakeDPIScale + 0.5); pMetric->mnExtLeading = static_cast<long>(CTFontGetLeading(font) * mfFakeDPIScale + 0.5); pMetric->mnIntLeading = 0; pMetric->mnWidth = m_style->GetFontStretchedSize(); SAL_INFO( "vcl.coretext.gr", "GetFontMetric(" << this << ") returning: {ascent=" << pMetric->mnAscent << ",descent=" << pMetric->mnDescent << ",extleading=" << pMetric->mnExtLeading << ",intleading=" << pMetric->mnIntLeading << ",width=" << pMetric->mnWidth << "}" ); } sal_Bool QuartzSalGraphics::GetGlyphBoundRect( sal_GlyphId /*nGlyphId*/, Rectangle& /*rRect*/ ) { /* TODO: create a Ghyph iterator to keep track ot 'state' between call */ return false; } sal_Bool QuartzSalGraphics::GetGlyphOutline( sal_GlyphId /*nGlyphId*/, basegfx::B2DPolyPolygon& /*rPolyPoly*/ ) { /* TODO */ return false; } void QuartzSalGraphics::GetGlyphWidths( const PhysicalFontFace* /*pFontData*/, bool /*bVertical*/, Int32Vector& /*rGlyphWidths*/, Ucs2UIntMap& /*rUnicodeEnc*/ ) { } sal_uLong QuartzSalGraphics::GetKernPairs( sal_uLong, ImplKernPairData* ) { return 0; } bool QuartzSalGraphics::GetImplFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const { if( !m_style ) { return false; } CoreTextPhysicalFontFace* font_face = m_style->GetFontFace(); if( !font_face) { return false; } return font_face->GetImplFontCapabilities(rFontCapabilities); } const ImplFontCharMap* QuartzSalGraphics::GetImplFontCharMap() const { if( !m_style ) { return NULL; } CoreTextPhysicalFontFace* font_face = m_style->GetFontFace(); if( !font_face) { return ImplFontCharMap::GetDefaultMap(); } return font_face->GetImplFontCharMap(); } #ifndef IOS bool QuartzSalGraphics::GetRawFontData( const PhysicalFontFace* pFontFace, std::vector<unsigned char>& rBuffer, bool* pJustCFF ) { const CoreTextPhysicalFontFace* font_face = static_cast<const CoreTextPhysicalFontFace*>(pFontFace); return font_face->GetRawFontData(rBuffer, pJustCFF); } #endif SystemFontData QuartzSalGraphics::GetSysFontData( int /* nFallbacklevel */ ) const { SystemFontData aSysFontData; aSysFontData.nSize = sizeof( SystemFontData ); aSysFontData.bAntialias = true; CTFontRef font = CTFontCreateUIFontForLanguage(kCTFontSystemFontType, 0.0, NULL); font = (CTFontRef)CFRetain(font); aSysFontData.rCTFont = font; CTFontRef italic_font = CTFontCreateCopyWithSymbolicTraits( font, 0.0, NULL, kCTFontItalicTrait, kCTFontItalicTrait + kCTFontBoldTrait); aSysFontData.bFakeItalic = italic_font ? false : true; SafeCFRelease(italic_font); CTFontRef bold_font = CTFontCreateCopyWithSymbolicTraits( font, 0.0, NULL, kCTFontBoldTrait, kCTFontItalicTrait + kCTFontBoldTrait); aSysFontData.bFakeBold = bold_font ? false : true; SafeCFRelease(bold_font); CTFontRef vertical_font = CTFontCreateCopyWithSymbolicTraits( font, 0.0, NULL, kCTFontVerticalTrait, kCTFontVerticalTrait); aSysFontData.bVerticalCharacterType = vertical_font ? true : false; SafeCFRelease(vertical_font); return aSysFontData; } sal_uInt16 QuartzSalGraphics::SetFont( FontSelectPattern* pReqFont, int /*nFallbackLevel*/ ) { m_style->SetFont(pReqFont); return 0; } void QuartzSalGraphics::SetTextColor( SalColor nSalColor ) { m_style->SetColor(nSalColor); } #ifdef IOS // Note that "QuartzSalGraphics" *is* SvpSalGraphics for iOS bool SvpSalGraphics::CheckContext() { const basegfx::B2IVector size = m_aDevice->getSize(); const basegfx::B2IVector bufferSize = m_aDevice->getBufferSize(); const sal_Int32 scanlineStride = m_aDevice->getScanlineStride(); basebmp::RawMemorySharedArray pixelBuffer = m_aDevice->getBuffer(); SAL_INFO( "vcl.ios", "CheckContext: device=" << m_aDevice.get() << " size=" << size.getX() << "x" << size.getY() << (m_aDevice->isTopDown() ? " top-down" : " bottom-up") << " stride=" << scanlineStride << " bufferSize=(" << bufferSize.getX() << "," << bufferSize.getY() << ")" ); switch( m_aDevice->getScanlineFormat() ) { case basebmp::Format::EIGHT_BIT_PAL: mrContext = CGBitmapContextCreate(pixelBuffer.get(), bufferSize.getX(), bufferSize.getY(), 8, scanlineStride, CGColorSpaceCreateDeviceGray(), kCGImageAlphaNone); break; case basebmp::Format::THIRTYTWO_BIT_TC_MASK_RGBA: mrContext = CGBitmapContextCreate(pixelBuffer.get(), bufferSize.getX(), bufferSize.getY(), 8, scanlineStride, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast); break; default: SAL_INFO( "vcl.ios", "CheckContext: unsupported color format " << basebmp::Format::formatName( m_aDevice->getScanlineFormat() ) ); } SAL_WARN_IF( mrContext == NULL, "vcl.ios", "CheckContext() failed" ); // Should we also clip the context? (Then we need to add a // getBounds() function to BitmapDevice.) if( mrContext != NULL && m_aDevice->isTopDown() ) { CGContextTranslateCTM( mrContext, 0, bufferSize.getY() ); CGContextScaleCTM( mrContext, 1, -1 ); } SAL_INFO( "vcl.ios", "CheckContext: context=" << mrContext ); return ( mrContext != NULL ); } CGContextRef SvpSalGraphics::GetContext() { if ( !mrContext ) CheckContext(); return mrContext; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sallang.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2007-09-25 10:07:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SALLANG_HXX #define _SALLANG_HXX //#ifndef _TOOLS_LANG_HXX //#include <tools/lang.hxx> //#endif #ifndef INCLUDED_I18NPOOL_MSLANGID_HXX #include <i18npool/mslangid.hxx> #endif // -------------------- // - Language Strings - // -------------------- // --- Key-Namen --- #define LSTR_KEY_SHIFT 0 #define LSTR_KEY_CTRL 1 #define LSTR_KEY_ALT 2 #define LSTR_KEY_UP 3 #define LSTR_KEY_DOWN 4 #define LSTR_KEY_LEFT 5 #define LSTR_KEY_RIGHT 6 #define LSTR_KEY_HOME 7 #define LSTR_KEY_END 8 #define LSTR_KEY_PAGEUP 9 #define LSTR_KEY_PAGEDOWN 10 #define LSTR_KEY_RETURN 11 #define LSTR_KEY_ESC 12 #define LSTR_KEY_TAB 13 #define LSTR_KEY_BACKSPACE 14 #define LSTR_KEY_SPACE 15 #define LSTR_KEY_INSERT 16 #define LSTR_KEY_DELETE 17 // --- Anzahl der Texte --- #define LSTR_COUNT 18 // -------------------------------------------- // - Methoden zum Abfragen der Sprach-Strings - // -------------------------------------------- const sal_Unicode** ImplGetLangTab( LanguageType eLang ); #endif // _SALLANG_HXX INTEGRATION: CWS changefileheader (1.4.178); FILE MERGED 2008/04/01 16:05:24 thb 1.4.178.2: #i85898# Stripping all external header guards 2008/03/28 15:44:27 rt 1.4.178.1: #i87441# Change license header to LPGL v3. /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sallang.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SALLANG_HXX #define _SALLANG_HXX //#ifndef _TOOLS_LANG_HXX //#include <tools/lang.hxx> //#endif #include <i18npool/mslangid.hxx> // -------------------- // - Language Strings - // -------------------- // --- Key-Namen --- #define LSTR_KEY_SHIFT 0 #define LSTR_KEY_CTRL 1 #define LSTR_KEY_ALT 2 #define LSTR_KEY_UP 3 #define LSTR_KEY_DOWN 4 #define LSTR_KEY_LEFT 5 #define LSTR_KEY_RIGHT 6 #define LSTR_KEY_HOME 7 #define LSTR_KEY_END 8 #define LSTR_KEY_PAGEUP 9 #define LSTR_KEY_PAGEDOWN 10 #define LSTR_KEY_RETURN 11 #define LSTR_KEY_ESC 12 #define LSTR_KEY_TAB 13 #define LSTR_KEY_BACKSPACE 14 #define LSTR_KEY_SPACE 15 #define LSTR_KEY_INSERT 16 #define LSTR_KEY_DELETE 17 // --- Anzahl der Texte --- #define LSTR_COUNT 18 // -------------------------------------------- // - Methoden zum Abfragen der Sprach-Strings - // -------------------------------------------- const sal_Unicode** ImplGetLangTab( LanguageType eLang ); #endif // _SALLANG_HXX
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioo_dl_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_fbc_ioo_dl_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; fapi2::ReturnCode p9_fbc_ioo_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0) { { fapi2::ATTR_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_OPTICS_CONFIG_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_OPTICS_CONFIG_MODE)); uint64_t l_def_OBUS_FBC_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == ENUM_ATTR_OPTICS_CONFIG_MODE_SMP); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x901080aull, l_scom_buffer )); if (l_def_OBUS_FBC_ENABLED) { constexpr auto l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON = 0x1; l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON ); } FAPI_TRY(fapi2::putScom(TGT0, 0x901080aull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } p9.fbc.ioo_dl.scom.initfile -- set CONFIG_NVx_NPU_ENABLED Change-Id: I18f107943cf2cfa246d33bb971024e58a7a7eb8e Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/37775 Reviewed-by: Thi N. Tran <25a2bca7ae5a8ea03be09ca8d282480c08c13052@us.ibm.com> Tested-by: Jenkins Server <8e3f934e4c44875bc48d33da3ea13d93ba9a233f@us.ibm.com> Tested-by: Hostboot CI <52521565bd8ea18a2b112942dce4f4220a97c2c8@us.ibm.com> Reviewed-by: Camille R. Mann <b920592808acec58c9833234ce6265ad888f29a6@us.ibm.com> Reviewed-by: Jennifer A. Stofer <ab93eca12e43608f33daa16a67357cd7b7e867ab@us.ibm.com> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioo_dl_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_fbc_ioo_dl_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; fapi2::ReturnCode p9_fbc_ioo_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0) { { fapi2::ATTR_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_OPTICS_CONFIG_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_OPTICS_CONFIG_MODE)); uint64_t l_def_OBUS_FBC_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == ENUM_ATTR_OPTICS_CONFIG_MODE_SMP); uint64_t l_def_OBUS_NV_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == ENUM_ATTR_OPTICS_CONFIG_MODE_NV); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x901080aull, l_scom_buffer )); if (l_def_OBUS_FBC_ENABLED) { constexpr auto l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON = 0x1; l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON ); } FAPI_TRY(fapi2::putScom(TGT0, 0x901080aull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x901080full, l_scom_buffer )); if (l_def_OBUS_NV_ENABLED) { constexpr auto l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON = 0x1; l_scom_buffer.insert<61, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON ); constexpr auto l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON = 0x1; l_scom_buffer.insert<62, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON ); constexpr auto l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON = 0x1; l_scom_buffer.insert<63, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON ); } FAPI_TRY(fapi2::putScom(TGT0, 0x901080full, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; }
vcl quartz: restore old outline front drawing Change-Id: Idc2026ff65dfaf36ea4be21ae9557cf5534e8c6b
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pstate_parameter_block.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pstate_parameter_block.C /// @brief Setup Pstate super structure for PGPE/CME HCode /// /// *HWP HW Owner : Greg Still <stillgs@us.ibm.com> /// *HWP FW Owner : Prasad Bg Ranganath <prasadbgr@in.ibm.com> /// *HWP Team : PM /// *HWP Level : 3 /// *HWP Consumed by : PGPE,CME /// /// @verbatim /// Procedure Summary: /// - Read VPD and attributes to create the Pstate Parameter Block(s) (one each for PGPE,OCC and CMEs). /// @endverbatim // *INDENT-OFF* // // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <fapi2.H> #include <p9_pstate_parameter_block.H> #include <p9_hcd_memmap_base.H> #include "p9_pm_get_poundw_bucket.H" #include "p9_resclk_defines.H" #include <attribute_ids.H> #include <math.h> //the value in this table are in Index format uint8_t g_GreyCodeIndexMapping [] = { /* 0mV 0x00*/ 0, /* - 8mV 0x01*/ 1, /* -24mV 0x02*/ 3, /* -16mV 0x03*/ 2, /* -56mV 0x04*/ 7, /* -48mV 0x05*/ 6, /* -32mV 0x06*/ 4, /* -40mV 0x07*/ 5, /* -96mV 0x08*/ 12, /* -96mV 0x09*/ 12, /* -96mV 0x0a*/ 12, /* -96mV 0x0b*/ 12, /* -64mV 0x0c*/ 8, /* -72mV 0x0d*/ 9, /* -88mV 0x0e*/ 11, /* -80mV 0x0f*/ 10 }; // from above mapping const uint8_t GREYCODE_INDEX_M32MV = 4; // #W version number where no special checks are needed. const uint32_t FULLY_VALID_POUNDW_VERSION = 3; fapi2::vdmData_t g_vpdData = {1, 2, { 0x29, 0x0C, 0x05, 0xC3, 0x61, 0x36, 0x1, 0x3, 0x0, 0x0, //Nominal 0x28, 0xa8, 0x05, 0x5f, 0x21, 0x36, 0x1, 0x3, 0x0, 0x0, //PowerSave 0x29, 0x70, 0x06, 0x27, 0x71, 0x36, 0x1, 0x3, 0x0, 0x0, //Turbo 0x29, 0xD4, 0x06, 0x8b, 0x51, 0x36, 0x1, 0x3, 0x0, 0x0, //UltraTurbo 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0, 0x0, 0x0, 0x0, //Resistance 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0, 0x0, 0x0, 0x0 //Spare } }; uint8_t g_wofData[] = { 0x57, 0x46, 0x54, 0x48 /*MAGIC CODE WFTH*/, 0x00, 0x00, 0x00, 0x01 /*version*/, 0x00, 0x80 /*VFRT block size*/, 0x00, 0x08 /*VFRT header size*/, 0x00, 0x01 /*VFRT data size*/, 0x6 /*Quad value*/, 0x18 /*core count*/, 0x00, 0xFA /*Vdn start*/, 0x00, 0x64 /*Vdn step*/, 0x00, 0x08 /*Vdn size*/, 0x00, 0x00 /*Vdd start*/, 0x00, 0x32 /*Vdd step*/, 0x00, 0x15 /*Vdd size*/, 0x03, 0xE8 /*Vratio start*/, 0x00, 0x53 /*Vratio step*/, 0x00, 0x18 /*Vratio size*/, 0x03, 0xE8 /*Fratio start*/, 0x00, 0x64 /*Fratio step*/, 0x00, 0x5 /*Fratio size*/, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*Vdn percent*/, 0x00, 0x64 /*Socket power Watts*/, 0x07, 0x4a /*nest freq*/, 0x09, 0x60 /*nominl freq*/, 0x00, 0x00 /*RDP capacity*/, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* WOF table source tag*/, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*package name*/, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*Pad to 128B*/ }; // uint8_t g_sysvfrtData[] = {0x56, 0x54, 0x00, 0x00, 0x02, 0x01, 0x01, 0x06, /// VFRT header values // // Magic_codea(2B) // // reserved(2B) // // type(4b),version(4b) // // vdn(1B),vdd(1B) // // quad id(1B) // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D, // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D, // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D, // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D, // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D // }; const uint8_t VDN_PERCENT_KEY = 35; const uint8_t QID_KEY = 6; uint8_t g_sysvfrtData[] = {0x56, 0x54, // Magic_code 2B) 0x00, 0x00, // reserved (2B) 0x02, // type(4b),version(4b) VDN_PERCENT_KEY, // vdn percentage(1B), 0x05, // vdd percentage(1B) QID_KEY, // quad id(1B) 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A }; #define VALIDATE_VID_VALUES(w,x,y,z,state) \ if (!((w <= x) && (x <= y) && (y <= z))) \ {state = 0;} #define VALIDATE_THRESHOLD_VALUES(w,x,y,z,state) \ if ((w > 0x7 && w != 0xC) || /* overvolt */ \ (x == 8) || (x == 9) || (x > 0xF) || \ (y == 8) || (y == 9) || (y > 0xF) || \ (z == 8) || (z == 9) || (z > 0xF) ) \ {state = 0;} //w => N_L (w > 7 is invalid) //x => N_S (x > N_L is invalid) //y => L_S (y > (N_L - S_N) is invalid) //z => S_N (z > N_S is invalid #define VALIDATE_FREQUENCY_DROP_VALUES(w,x,y,z,state) \ if ((w > 7) || \ (x > w) || \ (y > (w - z)) || \ (z > x) || \ ((w | x | y | z) == 0)) \ {state = 0; } #define VALIDATE_WOF_HEADER_DATA(a,b,c,d,e,f,g,state) \ if ( ((!a) || (!b) || (!c) || (!d) || (!e) || (!f) || (!g))) \ {state = 0; } double internal_ceil(double x) { if ((x-(int)(x))>0) return (int)x+1; return ((int)x); } double internal_floor(double x) { if(x>=0)return (int)x; return (int)(x-0.9999999999999999); } // Struct Variable for all attributes AttributeList attr; // Strings used in traces char const* vpdSetStr[NUM_VPD_PTS_SET] = VPD_PT_SET_ORDER_STR; char const* region_names[] = { "REGION_POWERSAVE_NOMINAL", "REGION_NOMINAL_TURBO", "REGION_TURBO_ULTRA" }; char const* prt_region_names[] = VPD_OP_SLOPES_REGION_ORDER_STR; ///-------------------------------------- /// @brief Check wof is enabled or not /// @param[in] pstate attribute state /// @return true or false ///-------------------------------------- bool is_wof_enabled(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PSTATE_attribute_state* i_state) { uint8_t attr_dd_wof_not_supported; uint8_t attr_system_wof_disable; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_WOF_DISABLE, FAPI_SYSTEM, attr_system_wof_disable); FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_WOF_NOT_SUPPORTED, i_target, attr_dd_wof_not_supported); return (!(attr_system_wof_disable) && !(attr_dd_wof_not_supported) && i_state->iv_wof_enabled) ? true : false; } ///-------------------------------------- /// @brief Check vdm is enabled or not /// @param[in] pstate attribute state /// @return true or false ///-------------------------------------- bool is_vdm_enabled(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PSTATE_attribute_state* i_state) { const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; uint8_t attr_dd_vdm_not_supported; uint8_t attr_system_vdm_disable; FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_VDM_DISABLE, FAPI_SYSTEM, attr_system_vdm_disable); FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_VDM_NOT_SUPPORTED, i_target, attr_dd_vdm_not_supported); return (!(attr_system_vdm_disable) && !(attr_dd_vdm_not_supported) && i_state->iv_vdm_enabled) ? true : false; } void load_gppb_attrs(const AttributeList* i_attr, GlobalPstateParmBlock* o_globalppb) { //Variables for Loadline, Distribution loss and offset SysPowerDistParms l_vdd_sysparm; memset(&l_vdd_sysparm,0x00,sizeof(SysPowerDistParms)); SysPowerDistParms l_vcs_sysparm; memset(&l_vcs_sysparm,0x00,sizeof(SysPowerDistParms)); SysPowerDistParms l_vdn_sysparm; memset(&l_vdn_sysparm,0x00,sizeof(SysPowerDistParms)); // Frequency step variable double l_frequency_step_khz; // ----------------------------------------------- // System power distribution parameters // ----------------------------------------------- // VDD rail l_vdd_sysparm.loadline_uohm = revle32(i_attr->attr_proc_r_loadline_vdd_uohm); l_vdd_sysparm.distloss_uohm = revle32(i_attr->attr_proc_r_distloss_vdd_uohm); l_vdd_sysparm.distoffset_uv = revle32(i_attr->attr_proc_vrm_voffset_vdd_uv); // VCS rail l_vcs_sysparm.loadline_uohm = revle32(i_attr->attr_proc_r_loadline_vcs_uohm); l_vcs_sysparm.distloss_uohm = revle32(i_attr->attr_proc_r_distloss_vcs_uohm); l_vcs_sysparm.distoffset_uv = revle32(i_attr->attr_proc_vrm_voffset_vcs_uv); // VDN rail l_vdn_sysparm.loadline_uohm = revle32(i_attr->attr_proc_r_loadline_vdn_uohm); l_vdn_sysparm.distloss_uohm = revle32(i_attr->attr_proc_r_distloss_vdn_uohm); l_vdn_sysparm.distoffset_uv = revle32(i_attr->attr_proc_vrm_voffset_vdn_uv); o_globalppb->vdd_sysparm = l_vdd_sysparm; o_globalppb->vcs_sysparm = l_vcs_sysparm; o_globalppb->vdn_sysparm = l_vdn_sysparm; // frequency_step_khz l_frequency_step_khz = (i_attr->attr_freq_proc_refclock_khz / i_attr->attr_proc_dpll_divider); o_globalppb->frequency_step_khz = revle32((uint32_t)l_frequency_step_khz); o_globalppb->nest_frequency_mhz = revle32(i_attr->attr_nest_frequency_mhz); // External VRM parameters o_globalppb->ext_vrm_transition_start_ns = revle32(i_attr->attr_ext_vrm_transition_start_ns); o_globalppb->ext_vrm_transition_rate_inc_uv_per_us = revle32(i_attr->attr_ext_vrm_transition_rate_inc_uv_per_us); o_globalppb->ext_vrm_transition_rate_dec_uv_per_us = revle32(i_attr->attr_ext_vrm_transition_rate_dec_uv_per_us); o_globalppb->ext_vrm_stabilization_time_us = revle32(i_attr->attr_ext_vrm_stabilization_time_us); o_globalppb->ext_vrm_step_size_mv = revle32(i_attr->attr_ext_vrm_step_size_mv); // load the biases // Note: all are uint8_t so no endianess correction is necessary for (auto p = 0; p < NUM_OP_POINTS; p++) { switch (p) { case POWERSAVE: o_globalppb->ext_biases[p].frequency_hp = i_attr->attr_freq_bias_powersave; o_globalppb->ext_biases[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_powersave; o_globalppb->int_biases[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_powersave; break; case NOMINAL: o_globalppb->ext_biases[p].frequency_hp = i_attr->attr_freq_bias_nominal; o_globalppb->ext_biases[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_nominal; o_globalppb->int_biases[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_nominal; break; case TURBO: o_globalppb->ext_biases[p].frequency_hp = i_attr->attr_freq_bias_turbo; o_globalppb->ext_biases[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_turbo; o_globalppb->int_biases[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_turbo; break; case ULTRA: o_globalppb->ext_biases[p].frequency_hp = i_attr->attr_freq_bias_ultraturbo; o_globalppb->ext_biases[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_ultraturbo; o_globalppb->int_biases[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_ultraturbo; } o_globalppb->ext_biases[p].vdn_ext_hp = i_attr->attr_voltage_ext_vdn_bias; o_globalppb->ext_biases[p].vcs_ext_hp = i_attr->attr_voltage_ext_vcs_bias; } } // START OF PSTATE PARAMETER BLOCK function fapi2::ReturnCode p9_pstate_parameter_block( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PstateSuperStructure* io_pss, uint8_t* o_buf, uint32_t& io_size) { FAPI_DBG("> p9_pstate_parameter_block"); const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ReturnCode l_rc = 0; io_size = 0; const uint8_t pv_op_order[NUM_OP_POINTS] = VPD_PV_ORDER; const char* pv_op_str[NUM_OP_POINTS] = VPD_PV_ORDER_STR; do { // ----------------------------------------------------------- // Clear the PstateSuperStructure and install the magic number //---------------------------------------------------------- memset(io_pss, 0, sizeof(PstateSuperStructure)); FAPI_INF("Populating magic number in Pstate Parameter block structure"); (*io_pss).magic = revle64(PSTATE_PARMSBLOCK_MAGIC); //Local variables for Global,local and OCC parameter blocks // PGPE content GlobalPstateParmBlock l_globalppb; memset (&l_globalppb, 0, sizeof(GlobalPstateParmBlock)); // CME content LocalPstateParmBlock l_localppb; memset (&l_localppb, 0, sizeof(LocalPstateParmBlock)); // OCC content OCCPstateParmBlock l_occppb; memset (&l_occppb , 0, sizeof (OCCPstateParmBlock)); PSTATE_attribute_state l_state; l_state.iv_pstates_enabled = true; l_state.iv_resclk_enabled = true; l_state.iv_vdm_enabled = true; l_state.iv_ivrm_enabled = true; l_state.iv_wof_enabled = true; // Enablement state PoundW_data l_poundw_data; memset (&l_poundw_data,0,sizeof(l_poundw_data)); // MVPD #V variables uint32_t attr_mvpd_poundv[PV_D][PV_W]; uint32_t attr_mvpd_poundv_biased[PV_D][PV_W]; uint8_t present_chiplets = 0; uint32_t valid_pdv_points = 0; // Local IDDQ table variable IddqTable l_iddqt; memset( & l_iddqt, 0x00, sizeof(IddqTable)); //VDM Parm block GP_VDMParmBlock l_gp_vdmpb; memset (&l_gp_vdmpb,0x00,sizeof(GP_VDMParmBlock)); LP_VDMParmBlock l_lp_vdmpb; memset (&l_lp_vdmpb, 0x00, sizeof(LP_VDMParmBlock)); //Resonant Clocking setup ResonantClockingSetup l_resclk_setup; memset (&l_resclk_setup,0x00, sizeof(ResonantClockingSetup)); //IVRM Parm block IvrmParmBlock l_ivrmpb; memset (&l_ivrmpb, 0x00,sizeof(IvrmParmBlock)); // VPD voltage and frequency biases VpdBias l_vpdbias[NUM_OP_POINTS]; memset (l_vpdbias,0,sizeof(VpdBias)); // ------------------------- // Get all attributes needed // ------------------------- FAPI_INF("Getting Attributes to build Pstate Superstructure"); FAPI_TRY(proc_get_attributes(i_target, &attr), "Get attributes function failed"); // Put attr driven content into GPPB load_gppb_attrs(&attr, &l_globalppb); //if PSTATES_MODE is off then we dont need to execute further to collect //the data. if (attr.attr_pstate_mode == fapi2::ENUM_ATTR_SYSTEM_PSTATES_MODE_OFF) { FAPI_INF("Pstate mode is to not boot the PGPE. Thus, none of the parameter blocks will be constructed"); // Set the io_size to 0 so that memory allocation issues won't be // detected by the caller. io_size = 0; break; } // ---------------- // get #V data // ---------------- FAPI_IMP("Getting #V Data"); uint8_t l_poundv_bucketId = 0; // clear MVPD arrays memset(attr_mvpd_poundv, 0, sizeof(attr_mvpd_poundv)); memset(attr_mvpd_poundv_biased, 0, sizeof(attr_mvpd_poundv_biased)); fapi2::voltageBucketData_t l_poundv_data; FAPI_TRY(proc_get_mvpd_data(i_target, attr_mvpd_poundv, &valid_pdv_points, &present_chiplets, l_poundv_bucketId, &l_poundv_data, &l_state), "proc_get_mvpd_data function failed to retrieve pound V data"); for (int i = 0; i <= NUM_OP_POINTS - 1; i++) { FAPI_DBG("Raw #V operating point (%s) f=%u v=%u i=%u v=%u i=%u", pv_op_str[pv_op_order[i]], attr_mvpd_poundv[pv_op_order[i]][0], attr_mvpd_poundv[pv_op_order[i]][1], attr_mvpd_poundv[pv_op_order[i]][2], attr_mvpd_poundv[pv_op_order[i]][3], attr_mvpd_poundv[pv_op_order[i]][4]); } if (!present_chiplets) { FAPI_IMP("**** WARNING : There are no EQ chiplets present which means there is no valid #V VPD"); FAPI_IMP("**** WARNING : Pstates and all related functions will NOT be enabled."); l_state.iv_pstates_enabled = false; l_state.iv_resclk_enabled = false; l_state.iv_resclk_enabled = false; l_state.iv_wof_enabled = false; // Set the io_size to 0 so that memory allocation issues won't be // detected by the caller. io_size = 0; break; } FAPI_DBG("Pstate Base Frequency - Raw %X (%d)", attr_mvpd_poundv[ULTRA][0] * 1000, attr_mvpd_poundv[ULTRA][0] * 1000); VpdOperatingPoint l_raw_operating_points[NUM_OP_POINTS]; FAPI_INF("Load RAW VPD"); FAPI_TRY(load_mvpd_operating_point(attr_mvpd_poundv, l_raw_operating_points, revle32(l_globalppb.frequency_step_khz)), "Loading MVPD operating point failed"); // --------------------------------------------- // process external and internal bias attributes // --------------------------------------------- FAPI_IMP("Apply Biasing to #V"); // Copy to Bias array for (int i = 0; i <= NUM_OP_POINTS - 1; i++) { for (int d = 0; d < PV_D; ++d) { for (int w = 0; w < PV_W; ++w) { attr_mvpd_poundv_biased[d][w] = attr_mvpd_poundv[d][w]; } } FAPI_DBG("Biased #V operating point (%s) f=%u v=%u i=%u v=%u i=%u", pv_op_str[pv_op_order[i]], attr_mvpd_poundv_biased[pv_op_order[i]][0], attr_mvpd_poundv_biased[pv_op_order[i]][1], attr_mvpd_poundv_biased[pv_op_order[i]][2], attr_mvpd_poundv_biased[pv_op_order[i]][3], attr_mvpd_poundv_biased[pv_op_order[i]][4]); } FAPI_TRY(proc_get_extint_bias(attr_mvpd_poundv_biased, &attr, l_vpdbias), "Bias application function failed"); //Validating Bias values FAPI_INF("Validate Biasd Voltage and Frequency values"); FAPI_TRY(proc_chk_valid_poundv( i_target, attr_mvpd_poundv_biased, &valid_pdv_points, i_target.getChipletNumber(), l_poundv_bucketId, &l_state,true)); FAPI_DBG("Pstate Base Frequency - after bias %X (%d)", attr_mvpd_poundv_biased[ULTRA][0] * 1000, attr_mvpd_poundv_biased[ULTRA][0] * 1000); //if wof is disabled.. don't call IQ function if (is_wof_enabled(i_target,&l_state)) { // ---------------- // get IQ (IDDQ) data // ---------------- FAPI_INF("Getting IQ (IDDQ) Data"); l_rc = proc_get_mvpd_iddq(i_target, &l_iddqt, &l_state); if (l_rc) { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_IQ_ACCESS_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_FAPI_RC(l_rc), "Pstate Parameter Block proc_get_mvpd_iddq function failed"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } } else { FAPI_INF("Skipping IQ (IDDQ) Data as WOF is disabled"); l_state.iv_wof_enabled = false; } // ---------------- // get VDM Parameters data // ---------------- FAPI_INF("Getting VDM Parameters Data"); FAPI_TRY(proc_get_vdm_parms(i_target, &attr, &l_gp_vdmpb)); // Note: the proc_get_mvpd_poundw has the conditional checking for VDM // and WOF enablement as #W has both VDM and WOF content l_rc = proc_get_mvpd_poundw(i_target, l_poundv_bucketId, &l_lp_vdmpb, &l_poundw_data, l_poundv_data, &l_state); if (l_rc) { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_ACCESS_FAIL(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_FAPI_RC(l_rc), "Pstate Parameter Block proc_get_mvpd_poundw function failed"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } // ---------------- // get IVRM Parameters data // ---------------- FAPI_INF("Getting IVRM Parameters Data"); FAPI_TRY(proc_get_ivrm_parms(i_target, &attr, &l_ivrmpb, &l_state)); // ----------------------------------------------- // Global parameter block // ----------------------------------------------- // Needs to be Endianness corrected going into the block l_globalppb.magic = revle64(PSTATE_PARMSBLOCK_MAGIC); l_globalppb.options.options = 0; // until options get defined. // ----------------------------------------------- // populate VpdOperatingPoint with biased MVPD attributes // ----------------------------------------------- FAPI_INF("Load VPD"); // VPD operating point FAPI_TRY(load_mvpd_operating_point(attr_mvpd_poundv, l_globalppb.operating_points, revle32(l_globalppb.frequency_step_khz)), "Loading MVPD operating point failed"); VpdOperatingPoint l_operating_points[NUM_VPD_PTS_SET][NUM_OP_POINTS]; // Compute VPD pointsp9_pstate_compute_PStateV_slope p9_pstate_compute_vpd_pts(l_operating_points, &l_globalppb, l_raw_operating_points); memcpy(l_globalppb.operating_points_set, l_operating_points, sizeof(l_operating_points)); FAPI_INF("Pstate Base Frequency %X (%d)", revle32(l_globalppb.reference_frequency_khz), revle32(l_globalppb.reference_frequency_khz)); // VpdBias External and Internal Biases for Global and Local parameter // block for (uint8_t i = 0; i < NUM_OP_POINTS; i++) { l_globalppb.ext_biases[i] = l_vpdbias[i]; l_globalppb.int_biases[i] = l_vpdbias[i]; l_localppb.ext_biases[i] = l_vpdbias[i]; l_localppb.int_biases[i] = l_vpdbias[i]; } // VpdBias External and Internal Biases for Global and Local parameter // block for (uint8_t i = 0; i < NUM_OP_POINTS; i++) { l_globalppb.ext_biases[i] = l_vpdbias[i]; l_globalppb.int_biases[i] = l_vpdbias[i]; l_localppb.ext_biases[i] = l_vpdbias[i]; l_localppb.int_biases[i] = l_vpdbias[i]; } // safe_voltage_mv l_globalppb.safe_voltage_mv = revle32(attr.attr_pm_safe_voltage_mv); // safe_frequency_khz l_globalppb.safe_frequency_khz = revle32(attr.attr_pm_safe_frequency_mhz * 1000); FAPI_INF("Safe Mode Frequency %d (0x%X) kHz; Voltage %d (0x%X) mV", revle32(l_globalppb.safe_frequency_khz), revle32(l_globalppb.safe_frequency_khz), revle32(l_globalppb.safe_voltage_mv), revle32(l_globalppb.safe_voltage_mv)); // ---------------- // get Resonant clocking attributes // ---------------- { if (attr.attr_resclk_disable == fapi2::ENUM_ATTR_SYSTEM_RESCLK_DISABLE_OFF) { FAPI_TRY(proc_set_resclk_table_attrs(i_target, &l_state), "proc_set_resclk_table_attrs failed"); if (l_state.iv_resclk_enabled) { FAPI_TRY(proc_res_clock_setup(i_target, &l_resclk_setup, &l_globalppb)); l_localppb.resclk = l_resclk_setup; l_globalppb.resclk = l_resclk_setup; } FAPI_INF("Resonant Clocks are enabled"); } else { l_state.iv_resclk_enabled = false; FAPI_INF("Resonant Clocks are disabled. Skipping setup."); } } // VDMParmBlock vdm l_globalppb.vdm = l_gp_vdmpb; // IvrmParmBlock l_globalppb.ivrm = l_ivrmpb; // Calculate pre-calculated slopes p9_pstate_compute_PsV_slopes(l_operating_points, &l_globalppb); //Remote this RTC: 174743 p9_pstate_compute_PStateV_slope(l_operating_points, &l_globalppb); l_globalppb.dpll_pstate0_value = revle32(revle32(l_globalppb.reference_frequency_khz) / revle32(l_globalppb.frequency_step_khz)); FAPI_INF("l_globalppb.dpll_pstate0_value %X (%d)", revle32(l_globalppb.dpll_pstate0_value), revle32(l_globalppb.dpll_pstate0_value)); // ----------------------------------------------- // Local parameter block // ----------------------------------------------- l_localppb.magic = revle64(LOCAL_PARMSBLOCK_MAGIC); // VPD operating point FAPI_TRY(load_mvpd_operating_point(attr_mvpd_poundv_biased, l_localppb.operating_points, revle32(l_globalppb.frequency_step_khz)), "Loading MVPD operating point failed"); l_localppb.vdd_sysparm = l_globalppb.vdd_sysparm; // IvrmParmBlock l_localppb.ivrm = l_ivrmpb; // VDMParmBlock l_localppb.vdm = l_lp_vdmpb; l_localppb.dpll_pstate0_value = revle32(revle32(l_globalppb.reference_frequency_khz) / revle32(l_globalppb.frequency_step_khz)); FAPI_INF("l_localppb.dpll_pstate0_value %X (%d)", revle32(l_localppb.dpll_pstate0_value), revle32(l_localppb.dpll_pstate0_value)); uint8_t l_biased_pstate[NUM_OP_POINTS]; for (uint8_t i = 0; i < NUM_OP_POINTS; ++i) { l_biased_pstate[i] = l_operating_points[VPD_PT_SET_BIASED][i].pstate; FAPI_INF ("l_biased_pstate %d ", l_biased_pstate[i]); } if (attr.attr_system_vdm_disable == fapi2::ENUM_ATTR_SYSTEM_VDM_DISABLE_OFF) { p9_pstate_compute_vdm_threshold_pts(l_poundw_data, &l_localppb); // VID slope calculation p9_pstate_compute_PsVIDCompSlopes_slopes(l_poundw_data, &l_localppb, l_biased_pstate); // VDM threshold slope calculation p9_pstate_compute_PsVDMThreshSlopes(&l_localppb, l_biased_pstate); // VDM Jump slope calculation p9_pstate_compute_PsVDMJumpSlopes (&l_localppb, l_biased_pstate); //Initializing threshold and jump values for GPPB memcpy ( l_globalppb.vid_point_set, l_localppb.vid_point_set, sizeof(l_localppb.vid_point_set)); memcpy ( l_globalppb.threshold_set, l_localppb.threshold_set, sizeof(l_localppb.threshold_set)); memcpy ( l_globalppb.jump_value_set, l_localppb.jump_value_set, sizeof(l_localppb.jump_value_set)); memcpy ( l_globalppb.PsVIDCompSlopes, l_localppb.PsVIDCompSlopes, sizeof(l_localppb.PsVIDCompSlopes)); memcpy ( l_globalppb.PsVDMThreshSlopes, l_localppb.PsVDMThreshSlopes, sizeof(l_localppb.PsVDMThreshSlopes)); memcpy ( l_globalppb.PsVDMJumpSlopes, l_localppb.PsVDMJumpSlopes, sizeof(l_localppb.PsVDMJumpSlopes)); } // ----------------------------------------------- // OCC parameter block // ----------------------------------------------- l_occppb.magic = revle64(OCC_PARMSBLOCK_MAGIC); // VPD operating point FAPI_TRY(load_mvpd_operating_point(attr_mvpd_poundv_biased, l_occppb.operating_points, l_globalppb.frequency_step_khz), "Loading MVPD operating point failed"); l_occppb.vdd_sysparm = l_globalppb.vdd_sysparm; l_occppb.vcs_sysparm = l_globalppb.vcs_sysparm; l_occppb.vdn_sysparm = l_globalppb.vdn_sysparm; // frequency_min_khz - Value from Power safe operating point after biases Pstate l_ps; //Translate safe mode frequency to pstate freq2pState(&l_globalppb, revle32(attr.attr_pm_safe_frequency_mhz * 1000), &l_ps, ROUND_FAST); //Compute real frequency l_occppb.frequency_min_khz = l_globalppb.reference_frequency_khz - (l_ps * l_globalppb.frequency_step_khz); // frequency_max_khz - Value from Ultra Turbo operating point after biases l_occppb.frequency_max_khz = l_globalppb.reference_frequency_khz; // frequency_step_khz l_occppb.frequency_step_khz = l_globalppb.frequency_step_khz; //Power bus nest freq uint16_t l_pbus_nest_freq = revle16(l_poundv_data.pbFreq); FAPI_INF("l_pbus_nest_freq 0x%x", (l_pbus_nest_freq)); // I- VDN PB current uint16_t l_vpd_idn_100ma = revle16(l_poundv_data.IdnPbCurr); FAPI_INF("l_vpd_idn_100ma 0x%x", (l_vpd_idn_100ma)); if (is_wof_enabled(i_target,&l_state)) { // Iddq Table l_occppb.iddq = l_iddqt; l_occppb.wof.tdp_rdp_factor = revle32(attr.attr_tdp_rdp_current_factor); FAPI_INF("l_occppb.wof.tdp_rdp_factor 0x%x", revle32(l_occppb.wof.tdp_rdp_factor)); // nest leakage percent l_occppb.nest_leakage_percent = attr.attr_nest_leakage_percent; FAPI_INF("l_occppb.nest_leakage_percent 0x%x", l_occppb.nest_leakage_percent); l_occppb.lac_tdp_vdd_turbo_10ma = revle16(l_poundw_data.poundw[TURBO].ivdd_tdp_ac_current_10ma); l_occppb.lac_tdp_vdd_nominal_10ma = revle16(l_poundw_data.poundw[NOMINAL].ivdd_tdp_ac_current_10ma); FAPI_INF("l_occppb.lac_tdp_vdd_turbo_10ma 0x%x", l_occppb.lac_tdp_vdd_turbo_10ma); FAPI_INF("l_occppb.lac_tdp_vdd_nominal_10ma 0x%x",l_occppb.lac_tdp_vdd_nominal_10ma); //Power bus vdn voltage uint16_t l_vpd_vdn_mv = revle16(l_poundv_data.VdnPbVltg); FAPI_INF("l_vpd_vdn_mv 0x%x (%d)", l_vpd_vdn_mv, l_vpd_vdn_mv); uint8_t l_nest_leakage_for_occ = 75; uint16_t l_iac_tdp_vdn = get_iac_vdn_value ( l_vpd_vdn_mv, l_iddqt, l_nest_leakage_for_occ, l_vpd_idn_100ma); if (!l_iac_tdp_vdn) { l_state.iv_wof_enabled = false; } else { l_occppb.ceff_tdp_vdn = revle16( pstate_calculate_effective_capacitance(l_iac_tdp_vdn, l_vpd_vdn_mv * 1000, l_pbus_nest_freq) ); } FAPI_INF("l_iac_tdp_vdn 0x%x", l_iac_tdp_vdn); FAPI_INF("l_occppb.ceff_tdp_vdn 0x%x", revle16(l_occppb.ceff_tdp_vdn)); // Put the good_normal_cores value into the GPPB for PGPE // This is done as a union overlay so that the inter-platform headers // are not touched. GPPBOptionsPadUse pad; pad.fields.good_cores_in_sort = l_iddqt.good_normal_cores_per_sort; l_globalppb.options.pad = pad.value; // Note: the following is presently accurate as the first 3 bytes // are reserved. FAPI_INF("good normal cores per sort %d 0x%X", revle32(l_globalppb.options.pad), revle32(l_globalppb.options.pad)); } else { l_state.iv_wof_enabled = false; } //Update nest frequency in OPPB l_occppb.nest_frequency_mhz = l_globalppb.nest_frequency_mhz; // The minimum Pstate must be rounded FAST so that core floor // constraints are not violated. Pstate pstate_min; int rc = freq2pState(&l_globalppb, revle32(l_occppb.frequency_min_khz), &pstate_min, ROUND_FAST); switch (rc) { case -PSTATE_LT_PSTATE_MIN: FAPI_INF("OCC Minimum Frequency was clipped to Pstate 0"); break; case -PSTATE_GT_PSTATE_MAX: FAPI_INF("OCC Minimum Frequency %d KHz is outside the range that can be represented" " by a Pstate with a base frequency of %d KHz and step size %d KHz", revle32(l_occppb.frequency_min_khz), revle32(l_globalppb.reference_frequency_khz), revle32(l_globalppb.frequency_step_khz)); FAPI_INF("Pstate is set to %X (%d)", pstate_min); break; } l_occppb.pstate_min = pstate_min; FAPI_INF("l_occppb.pstate_min 0x%x (%u)", pstate_min, pstate_min); //Check WOF is enabled or not io_size = 0; if (is_wof_enabled(i_target,&l_state)) { FAPI_TRY(p9_pstate_wof_initialization( i_target, &l_globalppb, o_buf, io_size, &l_state, attr_mvpd_poundv_biased[VPD_PV_ULTRA][0]), "WOF initialization failure"); } else { FAPI_INF("WOF is not enabled"); l_state.iv_wof_enabled = false; } l_occppb.wof.wof_enabled = l_state.iv_wof_enabled; // QuadManagerFlags QuadManagerFlags l_qm_flags; FAPI_TRY(p9_pstate_set_global_feature_attributes(i_target, l_state, &l_qm_flags)); l_localppb.qmflags = l_qm_flags; // Put out the Parmater Blocks to the trace gppb_print(&(l_globalppb)); oppb_print(&(l_occppb)); // Populate Global,local and OCC parameter blocks into Pstate super structure (*io_pss).globalppb = l_globalppb; (*io_pss).localppb = l_localppb; (*io_pss).occppb = l_occppb; } while(0); fapi_try_exit: FAPI_DBG("< p9_pstate_parameter_block"); return fapi2::current_err; } // END OF PSTATE PARAMETER BLOCK function fapi2::ReturnCode p9_pstate_wof_initialization (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const GlobalPstateParmBlock* i_gppb, uint8_t* o_buf, uint32_t& io_size, PSTATE_attribute_state* o_state, const uint32_t i_base_state_frequency) { FAPI_DBG(">> WOF initialization"); fapi2::ReturnCode l_rc = 0; uint16_t l_vdd_size = 0; uint16_t l_vdn_size = 0; //this structure has VFRT header + data HomerVFRTLayout_t l_vfrt; memset (&l_vfrt, 0, sizeof(l_vfrt)); // Use new to avoid over-running the stack fapi2::ATTR_WOF_TABLE_DATA_Type* l_wof_table_data = (fapi2::ATTR_WOF_TABLE_DATA_Type*)new fapi2::ATTR_WOF_TABLE_DATA_Type; FAPI_DBG("l_wof_table_data addr = %p size = %d", l_wof_table_data, sizeof(fapi2::ATTR_WOF_TABLE_DATA_Type)); do { // If this attribute is set, fill in l_wof_table_data with the VFRT data // from the internal, static table. const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_SYS_VFRT_STATIC_DATA_ENABLE_Type l_sys_vfrt_static_data = 0; FAPI_ATTR_GET(fapi2::ATTR_SYS_VFRT_STATIC_DATA_ENABLE, FAPI_SYSTEM, l_sys_vfrt_static_data); if (l_sys_vfrt_static_data) { FAPI_DBG("ATTR_SYS_VFRT_STATIC_DATA_ENABLE is SET"); // Copy WOF header data memcpy (l_wof_table_data, g_wofData, sizeof(g_wofData)); uint32_t l_index = sizeof(g_wofData); WofTablesHeader_t* p_wfth; p_wfth = reinterpret_cast<WofTablesHeader_t*>(l_wof_table_data); FAPI_INF("WFTH: %X", revle32(p_wfth->magic_number)); l_vdn_size = revle16(p_wfth->vdn_size); l_vdd_size = revle16(p_wfth->vdd_size); if (l_sys_vfrt_static_data == fapi2::ENUM_ATTR_SYS_VFRT_STATIC_DATA_ENABLE_VDN_STEP_OFF) { l_vdn_size = 1; } FAPI_INF("STATIC WOF: l_vdn_size %04x, l_vdd_size %04x",l_vdn_size,l_vdd_size); memcpy(&l_vfrt, &g_sysvfrtData, sizeof (g_sysvfrtData)); for (uint32_t vdn = 0; vdn < l_vdn_size; ++vdn) { // This creates a VDN percentage value can that can test the trace // filtering. l_vfrt.vfrtHeader.res_vdnId = (vdn+1)*VDN_PERCENT_KEY; for (uint32_t vdd = 0; vdd < l_vdd_size; ++vdd) { for (uint32_t qid = 0; qid < ACTIVE_QUADS; ++qid) { l_vfrt.vfrtHeader.VddId_QAId = vdd << 4 | qid; FAPI_DBG(" l_vfrt.vfrtHeader res_vdnId = %1X VddId_QAId = 0x%2X", l_vfrt.vfrtHeader.res_vdnId, l_vfrt.vfrtHeader.VddId_QAId); memcpy((*l_wof_table_data) + l_index, &l_vfrt, sizeof (l_vfrt)); l_index += sizeof (g_sysvfrtData); } } } io_size = l_index; FAPI_DBG(" io_size = %d", io_size); } else { FAPI_DBG("ATTR_SYS_VFRT_STATIC_DATA_ENABLE is not SET"); // Read System VFRT data l_rc = FAPI_ATTR_GET(fapi2::ATTR_WOF_TABLE_DATA, FAPI_SYSTEM, (*l_wof_table_data)); if (l_rc) { FAPI_INF("Pstate Parameter Block ATTR_WOF_TABLE_DATA attribute failed. Disabling WOF"); o_state->iv_wof_enabled = false; // Write the returned error content to the error log fapi2::logError(l_rc,fapi2::FAPI2_ERRL_SEV_UNRECOVERABLE); break; } } // Copy WOF header data memcpy (o_buf, (*l_wof_table_data), sizeof(WofTablesHeader_t)); uint32_t l_wof_table_index = sizeof(WofTablesHeader_t); uint32_t l_index = sizeof(WofTablesHeader_t); //Validate WOF header part WofTablesHeader_t* p_wfth; p_wfth = reinterpret_cast<WofTablesHeader_t*>(o_buf); FAPI_INF("WFTH: %X", revle32(p_wfth->magic_number)); bool l_wof_header_data_state = 1; VALIDATE_WOF_HEADER_DATA(p_wfth->magic_number, p_wfth->reserved_version, p_wfth->vfrt_block_size, p_wfth->vfrt_block_header_size, p_wfth->vfrt_data_size, p_wfth->quads_active_size, p_wfth->core_count, l_wof_header_data_state); if (!l_wof_header_data_state) { o_state->iv_wof_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_WOF_HEADER_DATA_INVALID(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(FAPI_SYSTEM) .set_MAGIC_NUMBER(p_wfth->magic_number) .set_VERSION(p_wfth->reserved_version) .set_VFRT_BLOCK_SIZE(p_wfth->vfrt_block_size) .set_VFRT_HEADER_SIZE(p_wfth->vfrt_block_header_size) .set_VFRT_DATA_SIZE(p_wfth->vfrt_data_size) .set_QUADS_ACTIVE_SIZE(p_wfth->quads_active_size) .set_CORE_COUNT(p_wfth->core_count), "Pstate Parameter Block WOF Header validation failed"); break; } l_vdn_size = revle16(p_wfth->vdn_size) ? revle16(p_wfth->vdn_size) : 1; l_vdd_size = revle16(p_wfth->vdd_size) ? revle16(p_wfth->vdd_size) : 1; FAPI_INF("WOF: l_vdn_size %04x, l_vdd_size %04x",l_vdn_size,l_vdd_size); // Convert system vfrt to homer vfrt for (auto vfrt_index = 0; vfrt_index < (l_vdn_size * l_vdd_size * ACTIVE_QUADS); ++vfrt_index) { l_rc = p9_pstate_update_vfrt (i_target, i_gppb, ((*l_wof_table_data) + l_wof_table_index), &l_vfrt, i_base_state_frequency); if (l_rc) { o_state->iv_wof_enabled = false; FAPI_TRY(l_rc); // Exit the function as a fail } // Check for "VT" at the start of the magic number if (revle16(l_vfrt.vfrtHeader.magic_number) != 0x5654) { o_state->iv_wof_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_VFRT_HEADER_DATA_INVALID(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(FAPI_SYSTEM) .set_MAGIC_NUMBER(l_vfrt.vfrtHeader.magic_number) .set_VFRT_INDEX(vfrt_index), "Pstate Parameter Block: Invalid VFRT Magic word"); break; } l_wof_table_index += 128; //System vFRT size is 128B..hence need to jump after each VFRT entry memcpy(o_buf + l_index, &l_vfrt, sizeof (l_vfrt)); l_index += sizeof (l_vfrt); } io_size = l_index; } while(0); // This is for the case that the magic number didn't match and we don't // want to fail; rather, we just disable WOF. fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: delete l_wof_table_data; FAPI_DBG("<< WOF initialization"); return fapi2::current_err; } // START OF GET ATTRIBUTES fapi2::ReturnCode proc_get_attributes ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, AttributeList* io_attr) { const uint32_t EXT_VRM_TRANSITION_START_NS = 8000; const uint32_t EXT_VRM_TRANSITION_RATE_INC_UV_PER_US = 10000; const uint32_t EXT_VRM_TRANSITION_RATE_DEC_UV_PER_US = 10000; const uint32_t EXT_VRM_STABILIZATION_TIME_NS = 5; const uint32_t EXT_VRM_STEPSIZE_MV = 50; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; // -------------------------- // attributes not yet defined // -------------------------- io_attr->attr_dpll_bias = 0; io_attr->attr_undervolting = 0; // --------------------------------------------------------------- // set ATTR_PROC_DPLL_DIVIDER // --------------------------------------------------------------- FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_DPLL_DIVIDER, i_target, io_attr->attr_proc_dpll_divider), "fapiGetAttribute of ATTR_PROC_DPLL_DIVIDER failed"); FAPI_DBG("ATTR_PROC_DPLL_DIVIDER - get to %x", io_attr->attr_proc_dpll_divider); // If value is 0, set a default if (!io_attr->attr_proc_dpll_divider) { FAPI_DBG("ATTR_PROC_DPLL_DIVIDER - setting default to %x", io_attr->attr_proc_dpll_divider); io_attr->attr_proc_dpll_divider = 8; FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_DPLL_DIVIDER, i_target, io_attr->attr_proc_dpll_divider), "fapiSetAttribute of ATTR_PROC_DPLL_DIVIDER failed"); } FAPI_INF("ATTR_PROC_DPLL_DIVIDER - %x", io_attr->attr_proc_dpll_divider); // ---------------------------- // attributes currently defined // ---------------------------- #define DATABLOCK_GET_ATTR(attr_name, target, attr_assign) \ FAPI_TRY(FAPI_ATTR_GET(fapi2::attr_name, target, io_attr->attr_assign),"Attribute read failed"); \ FAPI_INF("%-60s = 0x%08x %d", #attr_name, io_attr->attr_assign, io_attr->attr_assign); // Frequency Bias attributes DATABLOCK_GET_ATTR(ATTR_FREQ_BIAS_ULTRATURBO, i_target, attr_freq_bias_ultraturbo); DATABLOCK_GET_ATTR(ATTR_FREQ_BIAS_TURBO, i_target, attr_freq_bias_turbo); DATABLOCK_GET_ATTR(ATTR_FREQ_BIAS_NOMINAL, i_target, attr_freq_bias_nominal); DATABLOCK_GET_ATTR(ATTR_FREQ_BIAS_POWERSAVE, i_target, attr_freq_bias_powersave); // Voltage Bias attributes DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDD_BIAS_ULTRATURBO, i_target, attr_voltage_ext_vdd_bias_ultraturbo); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDD_BIAS_TURBO, i_target, attr_voltage_ext_vdd_bias_turbo); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDD_BIAS_NOMINAL, i_target, attr_voltage_ext_vdd_bias_nominal); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDD_BIAS_POWERSAVE, i_target, attr_voltage_ext_vdd_bias_powersave); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VCS_BIAS, i_target, attr_voltage_ext_vcs_bias); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDN_BIAS, i_target, attr_voltage_ext_vdn_bias); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_INT_VDD_BIAS_ULTRATURBO, i_target, attr_voltage_int_vdd_bias_ultraturbo); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_INT_VDD_BIAS_TURBO, i_target, attr_voltage_int_vdd_bias_turbo); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_INT_VDD_BIAS_NOMINAL, i_target, attr_voltage_int_vdd_bias_nominal); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_INT_VDD_BIAS_POWERSAVE, i_target, attr_voltage_int_vdd_bias_powersave); // Frequency attributes DATABLOCK_GET_ATTR(ATTR_FREQ_PROC_REFCLOCK_KHZ, FAPI_SYSTEM, attr_freq_proc_refclock_khz); DATABLOCK_GET_ATTR(ATTR_FREQ_PB_MHZ, FAPI_SYSTEM, attr_nest_frequency_mhz); DATABLOCK_GET_ATTR(ATTR_FREQ_CORE_CEILING_MHZ, FAPI_SYSTEM, attr_freq_core_ceiling_mhz); DATABLOCK_GET_ATTR(ATTR_SAFE_MODE_FREQUENCY_MHZ, i_target, attr_pm_safe_frequency_mhz); DATABLOCK_GET_ATTR(ATTR_SAFE_MODE_VOLTAGE_MV, i_target, attr_pm_safe_voltage_mv); DATABLOCK_GET_ATTR(ATTR_FREQ_CORE_FLOOR_MHZ, FAPI_SYSTEM, attr_freq_core_floor_mhz); // Loadline, Distribution loss and Distribution offset attributes DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VDD_UOHM, i_target, attr_proc_r_loadline_vdd_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VDD_UOHM, i_target, attr_proc_r_distloss_vdd_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VDD_UV, i_target, attr_proc_vrm_voffset_vdd_uv); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VDN_UOHM, i_target, attr_proc_r_loadline_vdn_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VDN_UOHM, i_target, attr_proc_r_distloss_vdn_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VDN_UV, i_target, attr_proc_vrm_voffset_vdn_uv); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VCS_UOHM, i_target, attr_proc_r_loadline_vcs_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VCS_UOHM, i_target, attr_proc_r_distloss_vcs_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VCS_UV, i_target, attr_proc_vrm_voffset_vcs_uv); // Read IVRM,WOF and DPLL attributes DATABLOCK_GET_ATTR(ATTR_SYSTEM_IVRM_DISABLE, FAPI_SYSTEM, attr_system_ivrm_disable); DATABLOCK_GET_ATTR(ATTR_SYSTEM_WOF_DISABLE, FAPI_SYSTEM, attr_system_wof_disable); DATABLOCK_GET_ATTR(ATTR_SYSTEM_VDM_DISABLE, FAPI_SYSTEM, attr_system_vdm_disable); DATABLOCK_GET_ATTR(ATTR_DPLL_VDM_RESPONSE, FAPI_SYSTEM, attr_dpll_vdm_response); DATABLOCK_GET_ATTR(ATTR_SYSTEM_RESCLK_DISABLE, FAPI_SYSTEM, attr_resclk_disable); DATABLOCK_GET_ATTR(ATTR_CHIP_EC_FEATURE_WOF_NOT_SUPPORTED, i_target, attr_dd_wof_not_supported); DATABLOCK_GET_ATTR(ATTR_CHIP_EC_FEATURE_VDM_NOT_SUPPORTED, i_target, attr_dd_vdm_not_supported); DATABLOCK_GET_ATTR(ATTR_SYSTEM_PSTATES_MODE, FAPI_SYSTEM, attr_pstate_mode); DATABLOCK_GET_ATTR(ATTR_TDP_RDP_CURRENT_FACTOR, i_target, attr_tdp_rdp_current_factor); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_TRANSITION_START_NS, FAPI_SYSTEM, attr_ext_vrm_transition_start_ns); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_TRANSITION_RATE_INC_UV_PER_US, FAPI_SYSTEM, attr_ext_vrm_transition_rate_inc_uv_per_us); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_TRANSITION_RATE_DEC_UV_PER_US, FAPI_SYSTEM, attr_ext_vrm_transition_rate_dec_uv_per_us); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_TRANSITION_STABILIZATION_TIME_NS, FAPI_SYSTEM, attr_ext_vrm_stabilization_time_us); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_STEPSIZE, FAPI_SYSTEM, attr_ext_vrm_step_size_mv); DATABLOCK_GET_ATTR(ATTR_NEST_LEAKAGE_PERCENT, FAPI_SYSTEM, attr_nest_leakage_percent); // AVSBus ... needed by p9_setup_evid DATABLOCK_GET_ATTR(ATTR_VDD_AVSBUS_BUSNUM, i_target,vdd_bus_num); DATABLOCK_GET_ATTR(ATTR_VDD_AVSBUS_RAIL, i_target,vdd_rail_select); DATABLOCK_GET_ATTR(ATTR_VDN_AVSBUS_BUSNUM, i_target,vdn_bus_num); DATABLOCK_GET_ATTR(ATTR_VDN_AVSBUS_RAIL, i_target,vdn_rail_select); DATABLOCK_GET_ATTR(ATTR_VCS_AVSBUS_BUSNUM, i_target,vcs_bus_num); DATABLOCK_GET_ATTR(ATTR_VCS_AVSBUS_RAIL, i_target,vcs_rail_select); DATABLOCK_GET_ATTR(ATTR_VCS_BOOT_VOLTAGE, i_target,vcs_voltage_mv); DATABLOCK_GET_ATTR(ATTR_VDD_BOOT_VOLTAGE, i_target,vdd_voltage_mv); DATABLOCK_GET_ATTR(ATTR_VDN_BOOT_VOLTAGE, i_target,vdn_voltage_mv); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VDD_UOHM, i_target,r_loadline_vdd_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VDD_UOHM, i_target,r_distloss_vdd_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VDD_UV, i_target,vrm_voffset_vdd_uv ); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VDN_UOHM, i_target,r_loadline_vdn_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VDN_UOHM, i_target,r_distloss_vdn_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VDN_UV, i_target,vrm_voffset_vdn_uv ); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VCS_UOHM, i_target,r_loadline_vcs_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VCS_UOHM, i_target,r_distloss_vcs_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VCS_UV, i_target,vrm_voffset_vcs_uv); DATABLOCK_GET_ATTR(ATTR_FREQ_PROC_REFCLOCK_KHZ, FAPI_SYSTEM, freq_proc_refclock_khz); DATABLOCK_GET_ATTR(ATTR_PROC_DPLL_DIVIDER, i_target, proc_dpll_divider); // AVSBus ... needed by p9_setup_evid // Deal with defaults if attributes are not set #define SET_DEFAULT(_attr_name, _attr_default) \ if (!(io_attr->_attr_name)) \ { \ io_attr->_attr_name = _attr_default; \ FAPI_INF("Setting %-44s = 0x%08x %d (internal default)", \ #_attr_name, io_attr->_attr_name, io_attr->_attr_name); \ } SET_DEFAULT(attr_freq_proc_refclock_khz, 133333); SET_DEFAULT(freq_proc_refclock_khz, 133333); // Future: collapse this out SET_DEFAULT(attr_ext_vrm_transition_start_ns, EXT_VRM_TRANSITION_START_NS) SET_DEFAULT(attr_ext_vrm_transition_rate_inc_uv_per_us, EXT_VRM_TRANSITION_RATE_INC_UV_PER_US) SET_DEFAULT(attr_ext_vrm_transition_rate_dec_uv_per_us, EXT_VRM_TRANSITION_RATE_DEC_UV_PER_US) SET_DEFAULT(attr_ext_vrm_stabilization_time_us, EXT_VRM_STABILIZATION_TIME_NS) SET_DEFAULT(attr_ext_vrm_step_size_mv, EXT_VRM_STEPSIZE_MV) // Deal with crital attributes that are not set and that any defaults chosen // could well be very wrong FAPI_ASSERT(io_attr->attr_nest_frequency_mhz, fapi2::PSTATE_PB_NEST_FREQ_EQ_ZERO() .set_CHIP_TARGET(i_target), "ATTR_FREQ_PB_MHZ has a zero value"); fapi_try_exit: return fapi2::current_err; } /// END OF GET ATTRIBUTES function /// START OF MVPD DATA FUNCTION fapi2::ReturnCode proc_get_mvpd_data(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint32_t o_attr_mvpd_data[PV_D][PV_W], uint32_t* o_valid_pdv_points, uint8_t* o_present_chiplets, uint8_t& o_bucketId, fapi2::voltageBucketData_t* o_poundv_data, PSTATE_attribute_state* o_state) { std::vector<fapi2::Target<fapi2::TARGET_TYPE_EQ>> l_eqChiplets; fapi2::voltageBucketData_t l_poundv_data; fapi2::Target<fapi2::TARGET_TYPE_EQ> l_firstEqChiplet; uint8_t* l_buffer = reinterpret_cast<uint8_t*>(malloc(sizeof(l_poundv_data)) ); uint8_t* l_buffer_inc; uint32_t chiplet_mvpd_data[PV_D][PV_W]; uint8_t j = 0; uint8_t i = 0; uint8_t ii = 0; uint8_t first_chplt = 1; uint8_t bucket_id = 0; do { // initialize FAPI_TRY(proc_get_attributes(i_target, &attr), "proc_get_mvpd_data: Get attributes function failed"); *o_present_chiplets = 0; // ----------------------------------------------------------------- // get list of quad chiplets and loop over each and get #V data from each // ----------------------------------------------------------------- // check that frequency is the same per chiplet // for voltage, get the max for use for the chip l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ>(fapi2::TARGET_STATE_FUNCTIONAL); *o_present_chiplets = l_eqChiplets.size(); FAPI_INF("Number of EQ chiplets present => %u", *o_present_chiplets); for (j = 0; j < l_eqChiplets.size(); j++) { uint8_t l_chipNum = 0xFF; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_eqChiplets[j], l_chipNum)); FAPI_INF("Chip Number => %u", l_chipNum); // clear out buffer to known value before calling fapiGetMvpdField memset(l_buffer, 0, sizeof(o_poundv_data)); FAPI_TRY(p9_pm_get_poundv_bucket(l_eqChiplets[j], l_poundv_data)); memcpy(l_buffer, &l_poundv_data, sizeof(l_poundv_data)); memcpy(o_poundv_data, &l_poundv_data, sizeof(l_poundv_data)); // clear array memset(chiplet_mvpd_data, 0, sizeof(chiplet_mvpd_data)); // fill chiplet_mvpd_data 2d array with data iN buffer (skip first byte - bucket id) #define UINT16_GET(__uint8_ptr) ((uint16_t)( ( (*((const uint8_t *)(__uint8_ptr)) << 8) | *((const uint8_t *)(__uint8_ptr) + 1) ) )) l_buffer_inc = l_buffer; bucket_id = *l_buffer_inc; l_buffer_inc++; FAPI_INF("#V chiplet = %u bucket id = %u", l_chipNum, bucket_id); for (i = 0; i <= 4; i++) { for (ii = 0; ii <= 4; ii++) { chiplet_mvpd_data[i][ii] = (uint32_t) UINT16_GET(l_buffer_inc); FAPI_INF("#V data = 0x%04X %-6d", chiplet_mvpd_data[i][ii], chiplet_mvpd_data[i][ii]); // increment to next MVPD value in buffer l_buffer_inc += 2; } } FAPI_TRY(proc_chk_valid_poundv( i_target, chiplet_mvpd_data, o_valid_pdv_points, l_chipNum, bucket_id, o_state)); // on first chiplet put each bucket's data into attr_mvpd_voltage_control if (first_chplt) { l_firstEqChiplet = l_eqChiplets[j]; o_bucketId = bucket_id; for (i = 0; i <= 4; i++) { for (ii = 0; ii <= 4; ii++) { o_attr_mvpd_data[i][ii] = chiplet_mvpd_data[i][ii]; } } first_chplt = 0; } else { // on subsequent chiplets, check that frequencies are same for each operating point for each chiplet if ( (o_attr_mvpd_data[0][0] != chiplet_mvpd_data[0][0]) || (o_attr_mvpd_data[1][0] != chiplet_mvpd_data[1][0]) || (o_attr_mvpd_data[2][0] != chiplet_mvpd_data[2][0]) || (o_attr_mvpd_data[3][0] != chiplet_mvpd_data[3][0]) || (o_attr_mvpd_data[4][0] != chiplet_mvpd_data[4][0]) ) { o_state->iv_pstates_enabled = false; // Error out has Pstate and all dependent functions are suspious. FAPI_ASSERT(false, fapi2::PSTATE_MVPD_CHIPLET_VOLTAGE_NOT_EQUAL() .set_CHIP_TARGET(i_target) .set_CURRENT_EQ_CHIPLET_TARGET(l_eqChiplets[j]) .set_FIRST_EQ_CHIPLET_TARGET(l_firstEqChiplet) .set_BUCKET(bucket_id), "frequencies are not the same for each operating point for each chiplet"); } } // check each bucket for max voltage and if max, put bucket's data into attr_mvpd_voltage_control for (i = 0; i <= 4; i++) { if (o_attr_mvpd_data[i][1] < chiplet_mvpd_data[i][1]) { o_attr_mvpd_data[i][0] = chiplet_mvpd_data[i][0]; o_attr_mvpd_data[i][1] = chiplet_mvpd_data[i][1]; o_attr_mvpd_data[i][2] = chiplet_mvpd_data[i][2]; o_attr_mvpd_data[i][3] = chiplet_mvpd_data[i][3]; o_attr_mvpd_data[i][4] = chiplet_mvpd_data[i][4]; o_bucketId = bucket_id; } } } // end for loop } while(0); fapi_try_exit: if (fapi2::current_err != fapi2::FAPI2_RC_SUCCESS) { o_state->iv_pstates_enabled = false; } free (l_buffer); return fapi2::current_err; } // end proc_get_mvpd_data /// END OF MVPD DATA FUNCTION /// START OF IDDQ READ FUNCTION fapi2::ReturnCode proc_get_mvpd_iddq( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, IddqTable* io_iddqt, PSTATE_attribute_state* o_state) { uint8_t* l_buffer_iq_c = reinterpret_cast<uint8_t*>(malloc(IQ_BUFFER_ALLOC)); uint32_t l_record = 0; uint32_t l_bufferSize_iq = IQ_BUFFER_ALLOC; // -------------------------------------------- // Process IQ Keyword (IDDQ) Data // -------------------------------------------- // clear out buffer to known value before calling fapiGetMvpdField memset(l_buffer_iq_c, 0, IQ_BUFFER_ALLOC); // set l_record to appropriate cprx record l_record = (uint32_t)fapi2::MVPD_RECORD_CRP0; l_bufferSize_iq = IQ_BUFFER_ALLOC; //First read is to get size of vpd record, note the o_buffer is NULL FAPI_TRY( getMvpdField((fapi2::MvpdRecord)l_record, fapi2::MVPD_KEYWORD_IQ, i_target, NULL, l_bufferSize_iq) ); //Allocate memory for vpd data l_buffer_iq_c = reinterpret_cast<uint8_t*>(malloc(l_bufferSize_iq)); // Get Chip IQ MVPD data from the CRPx records FAPI_TRY(getMvpdField((fapi2::MvpdRecord)l_record, fapi2::MVPD_KEYWORD_IQ, i_target, l_buffer_iq_c, l_bufferSize_iq)); //copy VPD data to IQ structure table memcpy(io_iddqt, l_buffer_iq_c, l_bufferSize_iq); //Verify Payload header data. if ( !(io_iddqt->iddq_version) || !(io_iddqt->good_quads_per_sort) || !(io_iddqt->good_normal_cores_per_sort) || !(io_iddqt->good_caches_per_sort)) { o_state->iv_wof_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_IQ_VPD_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_VERSION(io_iddqt->iddq_version) .set_GOOD_QUADS_PER_SORT(io_iddqt->good_quads_per_sort) .set_GOOD_NORMAL_CORES_PER_SORT(io_iddqt->good_normal_cores_per_sort) .set_GOOD_CACHES_PER_SORT(io_iddqt->good_caches_per_sort), "Pstate Parameter Block IQ Payload data error being logged"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } //Verify ivdd_all_cores_off_caches_off has MSB bit is set //if yes then initialized to 0 for (int i = 0; i < IDDQ_MEASUREMENTS; ++i) { if ( io_iddqt->ivdd_all_cores_off_caches_off[i] & 0x8000) { io_iddqt->ivdd_all_cores_off_caches_off[i] = 0; } } // Put out the structure to the trace iddq_print(io_iddqt); fapi_try_exit: // Free up memory buffer free(l_buffer_iq_c); if (fapi2::current_err != fapi2::FAPI2_RC_SUCCESS) { o_state->iv_wof_enabled = false; } return fapi2::current_err; } // proc_get_mvdp_iddq /// END OF IDDQ READ FUNCTION /// START OF BIAS APPLICATION FUNCTION // Bias multiplier helper function // NOTE: BIAS_PCT_UNIT is a multipler on the percentage that the value represents double calc_bias(const int8_t i_value) { double temp = 1.0 + ((BIAS_PCT_UNIT/100) * (double)i_value); FAPI_DBG(" calc_bias: input bias (in 1/2 percent) = %d; percent = %4.1f%% biased multiplier = %6.3f", i_value, (i_value*BIAS_PCT_UNIT), temp); return temp; } fapi2::ReturnCode proc_get_extint_bias( uint32_t io_attr_mvpd_data[PV_D][PV_W], const AttributeList* i_attr, VpdBias o_vpdbias[NUM_OP_POINTS] ) { double freq_bias[NUM_OP_POINTS]; double voltage_ext_vdd_bias[NUM_OP_POINTS]; double voltage_ext_vcs_bias; double voltage_ext_vdn_bias; // Calculate the frequency multiplers and load the biases into the exported // structure for (auto p = 0; p < NUM_OP_POINTS; p++) { switch (p) { case POWERSAVE: o_vpdbias[p].frequency_hp = i_attr->attr_freq_bias_powersave; o_vpdbias[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_powersave; o_vpdbias[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_powersave; break; case NOMINAL: o_vpdbias[p].frequency_hp = i_attr->attr_freq_bias_nominal; o_vpdbias[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_nominal; o_vpdbias[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_nominal; break; case TURBO: o_vpdbias[p].frequency_hp = i_attr->attr_freq_bias_turbo; o_vpdbias[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_turbo; o_vpdbias[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_turbo; break; case ULTRA: o_vpdbias[p].frequency_hp = i_attr->attr_freq_bias_ultraturbo; o_vpdbias[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_ultraturbo; o_vpdbias[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_ultraturbo; } o_vpdbias[p].vdn_ext_hp = i_attr->attr_voltage_ext_vdn_bias; o_vpdbias[p].vcs_ext_hp = i_attr->attr_voltage_ext_vcs_bias; freq_bias[p] = calc_bias(o_vpdbias[p].frequency_hp); voltage_ext_vdd_bias[p] = calc_bias(o_vpdbias[p].vdd_ext_hp); FAPI_DBG(" Biases[%d](bias): Freq=%f (%f%%); VDD=%f (%f%%)", p, freq_bias[p], o_vpdbias[p].frequency_hp/2, voltage_ext_vdd_bias[p], o_vpdbias[p].vdd_ext_hp/2); } // VCS bias applied to all operating points voltage_ext_vcs_bias = calc_bias(i_attr->attr_voltage_ext_vcs_bias); // VDN bias applied to all operating points voltage_ext_vdn_bias = calc_bias(i_attr->attr_voltage_ext_vdn_bias); // Change the VPD frequency, VDD and VCS values with the bias multiplers for (auto p = 0; p < NUM_OP_POINTS; p++) { FAPI_DBG(" Orig values[%d](bias): Freq=%d (%f); VDD=%d (%f), VCS=%d (%f)", p, io_attr_mvpd_data[p][VPD_PV_CORE_FREQ_MHZ], freq_bias[p], io_attr_mvpd_data[p][VPD_PV_VDD_MV], voltage_ext_vdd_bias[p], io_attr_mvpd_data[p][VPD_PV_VCS_MV], voltage_ext_vcs_bias); double freq_mhz = (( (double)io_attr_mvpd_data[p][VPD_PV_CORE_FREQ_MHZ]) * freq_bias[p]); double vdd_mv = (( (double)io_attr_mvpd_data[p][VPD_PV_VDD_MV]) * voltage_ext_vdd_bias[p]); double vcs_mv = (( (double)io_attr_mvpd_data[p][VPD_PV_VCS_MV]) * voltage_ext_vcs_bias); io_attr_mvpd_data[p][VPD_PV_CORE_FREQ_MHZ] = (uint32_t)internal_floor(freq_mhz); io_attr_mvpd_data[p][VPD_PV_VDD_MV] = (uint32_t)internal_ceil(vdd_mv); io_attr_mvpd_data[p][VPD_PV_VCS_MV] = (uint32_t)(vcs_mv); FAPI_DBG(" Biased values[%d]: Freq=%f %d; VDD=%f %d, VCS=%f %d ", p, freq_mhz, io_attr_mvpd_data[p][VPD_PV_CORE_FREQ_MHZ], vdd_mv, io_attr_mvpd_data[p][VPD_PV_VDD_MV], vcs_mv, io_attr_mvpd_data[p][VPD_PV_VCS_MV]); } // Power bus operating point double vdn_mv = (( (double)io_attr_mvpd_data[VPD_PV_POWERBUS][VPD_PV_VDN_MV]) * voltage_ext_vdn_bias); io_attr_mvpd_data[VPD_PV_POWERBUS][VPD_PV_VDN_MV] = (uint32_t)internal_ceil(vdn_mv); return fapi2::FAPI2_RC_SUCCESS; } // end proc_get_extint_bias /// END OF BIAS APPLICATION FUNCTION fapi2::ReturnCode proc_chk_valid_poundv(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint32_t i_chiplet_mvpd_data[PV_D][PV_W], uint32_t* o_valid_pdv_points, const uint8_t i_chiplet_num, const uint8_t i_bucket_id, PSTATE_attribute_state* o_state, const bool i_biased_state) { const uint8_t pv_op_order[NUM_OP_POINTS] = VPD_PV_ORDER; const char* pv_op_str[NUM_OP_POINTS] = VPD_PV_ORDER_STR; uint8_t i = 0; bool suspend_ut_check = false; FAPI_DBG(">> proc_chk_valid_poundv for %s values", (i_biased_state) ? "biased" : "non-biased" ); const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_SYSTEM_POUNDV_VALIDITY_HALT_DISABLE_Type attr_poundv_validity_halt_disable; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_POUNDV_VALIDITY_HALT_DISABLE, FAPI_SYSTEM, attr_poundv_validity_halt_disable)); fapi2::ATTR_CHIP_EC_FEATURE_POUNDV_VALIDATE_DISABLE_Type attr_poundv_validate_ec_disable; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_POUNDV_VALIDATE_DISABLE, i_target, attr_poundv_validate_ec_disable)); if (attr_poundv_validate_ec_disable) { o_state->iv_pstates_enabled = false; FAPI_INF("**** WARNING : #V zero value checking is not being performed on this chip EC level"); FAPI_INF("**** WARNING : Pstates are not enabled"); } else { // check for non-zero freq, voltage, or current in valid operating points for (i = 0; i <= NUM_OP_POINTS - 1; i++) { FAPI_INF("Checking for Zero valued %s data in each #V operating point (%s) f=%u v=%u i=%u v=%u i=%u", (i_biased_state) ? "biased" : "non-biased", pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][0], i_chiplet_mvpd_data[pv_op_order[i]][1], i_chiplet_mvpd_data[pv_op_order[i]][2], i_chiplet_mvpd_data[pv_op_order[i]][3], i_chiplet_mvpd_data[pv_op_order[i]][4]); if (is_wof_enabled(i_target,o_state) && (strcmp(pv_op_str[pv_op_order[i]], "UltraTurbo") == 0)) { if (i_chiplet_mvpd_data[pv_op_order[i]][0] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][1] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][2] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][3] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][4] == 0 ) { FAPI_INF("**** WARNING: WOF is enabled but zero valued data found in #V (chiplet = %u bucket id = %u op point = %s)", i_chiplet_num, i_bucket_id, pv_op_str[pv_op_order[i]]); FAPI_INF("**** WARNING: Disabling WOF and continuing"); suspend_ut_check = true; // Set ATTR_WOF_ENABLED so the caller can set header flags o_state->iv_wof_enabled = false; // Take out an informational error log and then keep going. if (i_biased_state) { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_BIASED_POUNDV_WOF_UT_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block WOF Biased #V UT error being logged"); } else { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUNDV_WOF_UT_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block WOF #V UT error being logged"); } fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } } else if ((!is_wof_enabled(i_target,o_state)) && (strcmp(pv_op_str[pv_op_order[i]], "UltraTurbo") == 0)) { FAPI_INF("**** NOTE: WOF is disabled so the UltraTurbo VPD is not being checked"); suspend_ut_check = true; } else { if (i_chiplet_mvpd_data[pv_op_order[i]][0] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][1] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][2] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][3] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][4] == 0 ) { o_state->iv_pstates_enabled = false; if (attr_poundv_validity_halt_disable) { FAPI_IMP("**** WARNING : halt on #V validity checking has been disabled and errors were found"); FAPI_IMP("**** WARNING : Zero valued data found in #V (chiplet = %u bucket id = %u op point = %s)", i_chiplet_num, i_bucket_id, pv_op_str[pv_op_order[i]]); FAPI_IMP("**** WARNING : Pstates are not enabled but continuing on."); // Log errors based on biased inputs or not if (i_biased_state) { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_BIASED_POUNDV_ZERO_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block Biased #V Zero contents error being logged"); } else { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUNDV_ZERO_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block #V Zero contents error being logged"); } fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } else { FAPI_ERR("**** ERROR : Zero valued data found in #V (chiplet = %u bucket id = %u op point = %s)", i_chiplet_num, i_bucket_id, pv_op_str[pv_op_order[i]]); // Error out has Pstate and all dependent functions are suspious. if (i_biased_state) { FAPI_ASSERT(false, fapi2::PSTATE_PB_BIASED_POUNDV_ZERO_ERROR() .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block Biased #V Zero contents error being logged"); } else { FAPI_ASSERT(false, fapi2::PSTATE_PB_POUNDV_ZERO_ERROR() .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block #V Zero contents error being logged"); } } // Halt disable } // #V point zero check } // WOF and UT conditions } // Operating poing loop } // validate #V EC // Adjust the valid operating point based on UltraTurbo presence // and WOF enablement *o_valid_pdv_points = NUM_OP_POINTS; if (suspend_ut_check) { (*o_valid_pdv_points)--; } FAPI_DBG("o_valid_pdv_points = %d", *o_valid_pdv_points); #define POUNDV_SLOPE_CHECK(x,y) x > y ? " is GREATER (ERROR!) than " : " is less than " if (attr_poundv_validate_ec_disable) { o_state->iv_pstates_enabled = false; FAPI_INF("**** WARNING : #V relationship checking is not being performed on this chip EC level"); FAPI_INF("**** WARNING : Pstates are not enabled"); } else { // check valid operating points' values have this relationship (power save <= nominal <= turbo <= ultraturbo) for (i = 1; i <= (*o_valid_pdv_points) - 1; i++) { FAPI_INF("Checking for relationship between #V operating point (%s <= %s)", pv_op_str[pv_op_order[i - 1]], pv_op_str[pv_op_order[i]]); // Only skip checkinug for WOF not enabled and UltraTurbo. if ( is_wof_enabled(i_target,o_state) || (!( !is_wof_enabled(i_target,o_state) && (strcmp(pv_op_str[pv_op_order[i]], "UltraTurbo") == 0))) ) { if (i_chiplet_mvpd_data[pv_op_order[i - 1]][0] > i_chiplet_mvpd_data[pv_op_order[i]][0] || i_chiplet_mvpd_data[pv_op_order[i - 1]][1] > i_chiplet_mvpd_data[pv_op_order[i]][1] || i_chiplet_mvpd_data[pv_op_order[i - 1]][2] > i_chiplet_mvpd_data[pv_op_order[i]][2] || i_chiplet_mvpd_data[pv_op_order[i - 1]][3] > i_chiplet_mvpd_data[pv_op_order[i]][3] || i_chiplet_mvpd_data[pv_op_order[i - 1]][4] > i_chiplet_mvpd_data[pv_op_order[i]][4] ) { o_state->iv_pstates_enabled = false; if (attr_poundv_validity_halt_disable) { FAPI_IMP("**** WARNING : halt on #V validity checking has been disabled and relationship errors were found"); FAPI_IMP("**** WARNING : Relationship error between #V operating point (%s > %s)(power save <= nominal <= turbo <= ultraturbo) (chiplet = %u bucket id = %u op point = %u)", pv_op_str[pv_op_order[i - 1]], pv_op_str[pv_op_order[i]], i_chiplet_num, i_bucket_id, pv_op_order[i]); FAPI_IMP("**** WARNING : Pstates are not enabled but continuing on."); } else { FAPI_ERR("**** ERROR : Relation../../xml/attribute_info/pm_plat_attributes.xmlship error between #V operating point (%s > %s)(power save <= nominal <= turbo <= ultraturbo) (chiplet = %u bucket id = %u op point = %u)", pv_op_str[pv_op_order[i - 1]], pv_op_str[pv_op_order[i]], i_chiplet_num, i_bucket_id, pv_op_order[i]); } FAPI_INF("%s Frequency value %u is %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][0], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][0], i_chiplet_mvpd_data[pv_op_order[i]][0]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][0]); FAPI_INF("%s VDD voltage value %u is %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][1], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][1], i_chiplet_mvpd_data[pv_op_order[i]][1]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][1]); FAPI_INF("%s VDD current value %u is %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][2], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][2], i_chiplet_mvpd_data[pv_op_order[i]][2]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][2]); FAPI_INF("%s VCS voltage value %u is %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][3], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][3], i_chiplet_mvpd_data[pv_op_order[i]][3]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][3]); FAPI_INF("%s VCS current value %u i../../xml/attribute_info/pm_plat_attributes.xmls %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][4], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][4], i_chiplet_mvpd_data[pv_op_order[i]][4]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][4]); if (i_biased_state) { if (attr_poundv_validity_halt_disable) { // Log the error only. FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_BIASED_POUNDV_SLOPE_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][0]) .set_VDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][1]) .set_IDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][2]) .set_VCS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][3]) .set_ICS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][4]) .set_FREQUENCY_B(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD_B(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD_B(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS_B(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS_B(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block Biased #V disorder contents error being logged"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } else { // Error out has Pstate and all dependent functions are suspious. FAPI_ASSERT(false, fapi2::PSTATE_PB_BIASED_POUNDV_SLOPE_ERROR() .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][0]) .set_VDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][1]) .set_IDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][2]) .set_VCS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][3]) .set_ICS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][4]) .set_FREQUENCY_B(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD_B(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD_B(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS_B(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS_B(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block Biased #V disorder contents error being logged"); } } else { if (attr_poundv_validity_halt_disable) { // Log the error only. FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUNDV_SLOPE_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][0]) .set_VDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][1]) .set_IDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][2]) .set_VCS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][3]) .set_ICS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][4]) .set_FREQUENCY_B(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD_B(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD_B(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS_B(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS_B(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block #V disorder contents error being logged"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } else { // Error out has Pstate and all dependent functions are suspious. FAPI_ASSERT(false, fapi2::PSTATE_PB_POUNDV_SLOPE_ERROR() .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][0]) .set_VDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][1]) .set_IDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][2]) .set_VCS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][3]) .set_ICS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][4]) .set_FREQUENCY_B(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD_B(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD_B(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS_B(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS_B(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block #V disorder contents error being logged"); } } } // validity failed } // Skip UT check } // point loop } // validity disabled fapi_try_exit: FAPI_DBG("<< proc_chk_valid_poundv"); return fapi2::current_err; } /// ------------------------------------------------------------ /// \brief Copy VPD operating point into destination in assending order /// \param[in] &src[NUM_OP_POINTS] => reference to source VPD structure (array) /// \param[out] *dest[NUM_OP_POINTS] => pointer to destination VpdOperatingPoint structure // \param[in] i_frequency_step_khz => Base frequency value for pstate calculation /// ------------------------------------------------------------ /// \note: this routine reads the keyword information in "VPD order" (eg Nominal, /// PowerSave, Turbo, UltraTurbo) into the data structures in "Natural Order" /// (eg (eg PowerSave, Nominal, Turbo, UltraTurbo) /// fapi2::ReturnCode load_mvpd_operating_point ( const uint32_t i_src[PV_D][PV_W], VpdOperatingPoint* o_dest, uint32_t i_frequency_step_khz) { FAPI_DBG(">> load_mvpd_operating_point"); const uint8_t pv_op_order[NUM_OP_POINTS] = VPD_PV_ORDER; for (uint32_t i = 0; i < NUM_OP_POINTS; i++) { o_dest[i].frequency_mhz = revle32(i_src[pv_op_order[i]][0]); o_dest[i].vdd_mv = revle32(i_src[pv_op_order[i]][1]); o_dest[i].idd_100ma = revle32(i_src[pv_op_order[i]][2]); o_dest[i].vcs_mv = revle32(i_src[pv_op_order[i]][3]); o_dest[i].ics_100ma = revle32(i_src[pv_op_order[i]][4]); o_dest[i].pstate = (i_src[ULTRA][0] - i_src[pv_op_order[i]][0]) * 1000 / i_frequency_step_khz; } FAPI_DBG("<< load_mvpd_operating_point"); return fapi2::FAPI2_RC_SUCCESS; } // end load_mvpd_operating_point /// ------------------------------------------------------------ /// @brief Copy out of operating point set into a destination operating point /// @param[in] &i_op_pt_set => reference to array of VpdOperatingPoint sets /// @param[out] *dest[NUM_OP_POINTS] => pointer to destination VpdOperatingPoint structure /// @param[in] i_frequency_step_khz => Base frequency value for pstate calculation /// ------------------------------------------------------------ fapi2::ReturnCode get_operating_point ( const VpdOperatingPoint i_op_pt_set[NUM_VPD_PTS_SET][NUM_OP_POINTS], uint32_t i_set, VpdOperatingPoint* o_op_pt) { FAPI_DBG(">> get_operating_point"); for (uint32_t i = 0; i < NUM_OP_POINTS; i++) { o_op_pt[i].frequency_mhz = i_op_pt_set[i_set][i].frequency_mhz; o_op_pt[i].vdd_mv = i_op_pt_set[i_set][i].vdd_mv; o_op_pt[i].idd_100ma = i_op_pt_set[i_set][i].idd_100ma; o_op_pt[i].vcs_mv = i_op_pt_set[i_set][i].vcs_mv; o_op_pt[i].ics_100ma = i_op_pt_set[i_set][i].ics_100ma; o_op_pt[i].pstate = i_op_pt_set[i_set][i].pstate; } FAPI_DBG("<< get_operating_point"); return fapi2::FAPI2_RC_SUCCESS; } // end load_mvpd_operating_point fapi2::ReturnCode proc_get_vdm_parms (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const AttributeList* i_attr, GP_VDMParmBlock* o_vdmpb) { FAPI_DBG(">> proc_get_vdm_parms"); if (i_attr->attr_system_vdm_disable == fapi2::ENUM_ATTR_SYSTEM_VDM_DISABLE_OFF) { const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_DROOP_SMALL_OVERRIDE, FAPI_SYSTEM, o_vdmpb->droop_small_override)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_DROOP_LARGE_OVERRIDE, FAPI_SYSTEM, o_vdmpb->droop_large_override)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_DROOP_EXTREME_OVERRIDE, FAPI_SYSTEM, o_vdmpb->droop_extreme_override)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_OVERVOLT_OVERRIDE, FAPI_SYSTEM, o_vdmpb->overvolt_override)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_FMIN_OVERRIDE_KHZ, FAPI_SYSTEM, o_vdmpb->fmin_override_khz)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_FMAX_OVERRIDE_KHZ, FAPI_SYSTEM, o_vdmpb->fmax_override_khz)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_VID_COMPARE_OVERRIDE_MV, FAPI_SYSTEM, o_vdmpb->vid_compare_override_mv)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DPLL_VDM_RESPONSE, FAPI_SYSTEM, o_vdmpb->vdm_response)); } else { FAPI_DBG(" VDM is disabled. Skipping VDM attribute accesses"); } fapi_try_exit: FAPI_DBG("<< proc_get_vdm_parms"); return fapi2::current_err; } fapi2::ReturnCode proc_res_clock_setup ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, ResonantClockingSetup* o_resclk_setup, const GlobalPstateParmBlock* i_gppb) { FAPI_DBG(">> proc_res_clock_setup"); uint8_t l_resclk_freq_index[RESCLK_FREQ_REGIONS]; uint16_t l_step_delay_ns; uint16_t l_l3_threshold_mv; uint16_t l_steparray[RESCLK_STEPS]; uint16_t l_resclk_freq_regions[RESCLK_FREQ_REGIONS]; uint32_t l_ultra_turbo_freq_khz = revle32(i_gppb->reference_frequency_khz); const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_SYSTEM_RESCLK_STEP_DELAY, FAPI_SYSTEM, l_step_delay_ns)); o_resclk_setup->step_delay_ns = revle16(l_step_delay_ns); // Resonant Clocking Frequency and Index arrays FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGIONS, i_target, l_resclk_freq_regions)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGION_INDEX, i_target, l_resclk_freq_index)); // Convert frequencies to pstates for (uint8_t i = 0; i < RESCLK_FREQ_REGIONS; ++i) { Pstate pstate; // Frequencies are given in MHz, convert to KHz uint32_t freq_khz = static_cast<uint32_t>(l_resclk_freq_regions[i]) * 1000; uint8_t idx = l_resclk_freq_index[i]; // Frequencies need to be capped at Ultra-Turbo, frequencies less-than // the Minimum can be ignored (because this table is walked from // end-begin, and the frequencies are stored in ascending order, // the "walk" will never pass the minimum frequency). if (freq_khz > l_ultra_turbo_freq_khz) { freq_khz = l_ultra_turbo_freq_khz; // Need to walk the table backwards to find the index for this frequency for (uint8_t j = i; j >= 0; --j) { if (freq_khz >= (l_resclk_freq_regions[j] * 1000)) { idx = l_resclk_freq_index[j]; break; } } } int rc = freq2pState(i_gppb, freq_khz, &pstate); switch (rc) { case -PSTATE_LT_PSTATE_MIN: FAPI_INF("Resonant clock frequency %d KHz was clipped to Pstate 0", freq_khz); break; case -PSTATE_GT_PSTATE_MAX: FAPI_INF("Resonant clock Frequency %d KHz is outside the range that can be represented" " by a Pstate with a base frequency of %d KHz and step size %d KHz", freq_khz, l_ultra_turbo_freq_khz, revle32(i_gppb->frequency_step_khz)); FAPI_INF("Pstate is set to %X (%d)", pstate); break; } o_resclk_setup->resclk_freq[i] = pstate; o_resclk_setup->resclk_index[i] = idx; FAPI_DBG("Resclk: freq = %d kHz; pstate = %d; idx = %d", freq_khz, pstate, idx); } FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_L3_VALUE, i_target, o_resclk_setup->l3_steparray)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_L3_VOLTAGE_THRESHOLD_MV, i_target, l_l3_threshold_mv)); o_resclk_setup->l3_threshold_mv = revle16(l_l3_threshold_mv); // Resonant Clocking Step array FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_VALUE, i_target, l_steparray)); for (uint8_t i = 0; i < RESCLK_STEPS; i++) { o_resclk_setup->steparray[i].value = revle16(l_steparray[i]); } fapi_try_exit: FAPI_DBG("<< proc_res_clock_setup"); return fapi2::current_err; } fapi2::ReturnCode proc_get_ivrm_parms ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const AttributeList* i_attr, IvrmParmBlock* o_ivrmpb, PSTATE_attribute_state* o_state) { FAPI_DBG(">> proc_get_ivrm_parms"); if (i_attr->attr_system_ivrm_disable == fapi2::ENUM_ATTR_SYSTEM_IVRM_DISABLE_OFF) { const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF(">> proc_get_ivrm_parms"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_STRENGTH_LOOKUP, FAPI_SYSTEM, o_ivrmpb->strength_lookup)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_VIN_MULTIPLIER, FAPI_SYSTEM, o_ivrmpb->vin_multiplier)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_VIN_MAX_MV, FAPI_SYSTEM, o_ivrmpb->vin_max_mv)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_STEP_DELAY_NS, FAPI_SYSTEM, o_ivrmpb->step_delay_ns)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_STABILIZATION_DELAY_NS, FAPI_SYSTEM, o_ivrmpb->stablization_delay_ns)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_DEADZONE_MV, FAPI_SYSTEM, o_ivrmpb->deadzone_mv)); // This is presently hardcoded to FALSE until validation code is in // place to ensure turning IVRM on is a good thing. This attribute write is // needed to allocate the HWP attribute in Cronus. // Indicate that IVRM is good to be enabled (or not) FAPI_INF(" NOTE: This level of code is forcing the iVRM to OFF"); { fapi2::ATTR_IVRM_ENABLED_Type l_ivrm_enabled = (fapi2::ATTR_IVRM_ENABLED_Type)fapi2::ENUM_ATTR_IVRM_ENABLED_FALSE; FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_IVRM_ENABLED, i_target, l_ivrm_enabled)); } } else { FAPI_DBG(" IVRM is disabled. Skipping IVRM attribute accesses"); o_state->iv_ivrm_enabled = false; } fapi_try_exit: FAPI_DBG("<< proc_get_ivrm_parms"); return fapi2::current_err; } // Apply system parameters to a VPD value uint32_t sysparm_uplift(const uint32_t i_vpd_mv, const uint32_t i_vpd_ma, const uint32_t i_loadline_uohm, const uint32_t i_distloss_uohm, const uint32_t i_distoffset_uohm) { double l_mv = ((double)i_vpd_mv + // mV ( // mA*uOhm/1000 -> uV ((double)(i_vpd_ma * (i_loadline_uohm + i_distloss_uohm)) / 1000 + // uv (double)i_distoffset_uohm) ) / 1000); // uV -> mV uint32_t l_result = (uint32_t)l_mv; FAPI_DBG(" system_uplift_mv: i_vpd_mv=%d; i_vpd_ma=%d; i_loadline_uohm=%d " "i_distloss_uohm = %d i_distoffset_uohm = %d l_mv = %5.3f l_result = %d" , i_vpd_mv, i_vpd_ma, i_loadline_uohm, i_distloss_uohm, i_distoffset_uohm, l_mv, l_result); return revle32(l_result); } // Bias Adjust a voltage data value using a 1/2 percent bias amount. Value // is always taken to the higher integer value. uint32_t bias_adjust_mv(const uint32_t i_value, const int32_t i_bias_0p5pct) { double l_mult = calc_bias(i_bias_0p5pct); double l_biased_value = (double)i_value * l_mult; double l_ceiling = internal_ceil(l_biased_value); uint32_t l_result = (uint32_t)l_ceiling; FAPI_DBG(" bias_adjust_mv: i_value=%d; mult=%5.3f; biased value=%3.0f ceiling = %3.0f result = %d", i_value, l_mult, l_biased_value, l_ceiling, l_result); return revle32(l_result); } // Bias Adjust a frequency data value using a 1/2 percent bias amount. Value // is always taken to the lower integer value. uint32_t bias_adjust_mhz(const uint32_t i_value, const int32_t i_bias_0p5pct) { double l_mult = calc_bias(i_bias_0p5pct); double l_biased_value = (double)i_value * l_mult; FAPI_DBG(" bias_adjust_mhz: i_value=%d; mult=%5.3f; biased value=%3.0f", i_value, l_mult, l_biased_value); return revle32((uint32_t)internal_floor(l_biased_value)); } // // p9_pstate_compute_vpd_pts // void p9_pstate_compute_vpd_pts(VpdOperatingPoint (*o_operating_points)[NUM_OP_POINTS], GlobalPstateParmBlock* i_gppb, VpdOperatingPoint* i_raw_vpd_pts) { int p = 0; uint32_t l_vdd_loadline_uohm = revle32(i_gppb->vdd_sysparm.loadline_uohm); uint32_t l_vdd_distloss_uohm = revle32(i_gppb->vdd_sysparm.distloss_uohm); uint32_t l_vdd_distoffset_uv = revle32(i_gppb->vdd_sysparm.distoffset_uv); uint32_t l_vcs_loadline_uohm = revle32(i_gppb->vcs_sysparm.loadline_uohm); uint32_t l_vcs_distloss_uohm = revle32(i_gppb->vcs_sysparm.distloss_uohm); uint32_t l_vcs_distoffset_uv = revle32(i_gppb->vcs_sysparm.distoffset_uv); //RAW POINTS. We just copy them as is for (p = 0; p < NUM_OP_POINTS; p++) { o_operating_points[VPD_PT_SET_RAW][p].vdd_mv = i_raw_vpd_pts[p].vdd_mv; o_operating_points[VPD_PT_SET_RAW][p].vcs_mv = i_raw_vpd_pts[p].vcs_mv; o_operating_points[VPD_PT_SET_RAW][p].idd_100ma = i_raw_vpd_pts[p].idd_100ma; o_operating_points[VPD_PT_SET_RAW][p].ics_100ma = i_raw_vpd_pts[p].ics_100ma; o_operating_points[VPD_PT_SET_RAW][p].frequency_mhz = i_raw_vpd_pts[p].frequency_mhz; o_operating_points[VPD_PT_SET_RAW][p].pstate = i_raw_vpd_pts[p].pstate; FAPI_DBG("GP: OpPoint=[%d][%d], PS=%3d, Freq=%3X (%4d), Vdd=%3X (%4d)", VPD_PT_SET_RAW, p, o_operating_points[VPD_PT_SET_RAW][p].pstate, revle32(o_operating_points[VPD_PT_SET_RAW][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_RAW][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_RAW][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_RAW][p].vdd_mv)); } //SYSTEM PARAMS APPLIED POINTS for (p = 0; p < NUM_OP_POINTS; p++) { uint32_t l_vdd_mv = revle32(i_gppb->operating_points[p].vdd_mv); uint32_t l_idd_ma = revle32(i_gppb->operating_points[p].idd_100ma * 100); uint32_t l_vcs_mv = revle32(i_gppb->operating_points[p].vcs_mv); uint32_t l_ics_ma = revle32(i_gppb->operating_points[p].ics_100ma * 100); o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv = sysparm_uplift(l_vdd_mv, l_idd_ma, l_vdd_loadline_uohm, l_vdd_distloss_uohm, l_vdd_distoffset_uv); o_operating_points[VPD_PT_SET_SYSP][p].vcs_mv = sysparm_uplift(l_vcs_mv, l_ics_ma, l_vcs_loadline_uohm, l_vcs_distloss_uohm, l_vcs_distoffset_uv); o_operating_points[VPD_PT_SET_SYSP][p].idd_100ma = i_gppb->operating_points[p].idd_100ma; o_operating_points[VPD_PT_SET_SYSP][p].ics_100ma = i_gppb->operating_points[p].ics_100ma; o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz = i_gppb->operating_points[p].frequency_mhz; o_operating_points[VPD_PT_SET_SYSP][p].pstate = i_gppb->operating_points[p].pstate; FAPI_DBG("SP: OpPoint=[%d][%d], PS=%3d, Freq=%3X (%4d), Vdd=%3X (%4d)", VPD_PT_SET_RAW, p, o_operating_points[VPD_PT_SET_SYSP][p].pstate, revle32(o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv)); } //BIASED POINTS for (p = 0; p < NUM_OP_POINTS; p++) { uint32_t l_frequency_mhz = revle32(i_gppb->operating_points[p].frequency_mhz); uint32_t l_vdd_mv = revle32(i_gppb->operating_points[p].vdd_mv); uint32_t l_vcs_mv = revle32(i_gppb->operating_points[p].vcs_mv); o_operating_points[VPD_PT_SET_BIASED][p].vdd_mv = bias_adjust_mv(l_vdd_mv, i_gppb->ext_biases[p].vdd_ext_hp); o_operating_points[VPD_PT_SET_BIASED][p].vcs_mv = bias_adjust_mv(l_vcs_mv, i_gppb->ext_biases[p].vcs_ext_hp); o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz = bias_adjust_mhz(l_frequency_mhz, i_gppb->ext_biases[p].frequency_hp); o_operating_points[VPD_PT_SET_BIASED][p].idd_100ma = i_gppb->operating_points[p].idd_100ma; o_operating_points[VPD_PT_SET_BIASED][p].ics_100ma = i_gppb->operating_points[p].ics_100ma; } // As this is memory to memory, Endianess correction is not necessary. uint32_t l_ref_freq_khz = revle32(o_operating_points[VPD_PT_SET_BIASED][ULTRA].frequency_mhz) * 1000; i_gppb->reference_frequency_khz = revle32(l_ref_freq_khz); FAPI_DBG("Reference into GPPB: LE local Freq=%X (%d); Freq=%X (%d)", l_ref_freq_khz, l_ref_freq_khz, revle32(i_gppb->reference_frequency_khz), revle32(i_gppb->reference_frequency_khz)); // Now that the ULTRA frequency is known, Pstates can be calculated for (p = 0; p < NUM_OP_POINTS; p++) { o_operating_points[VPD_PT_SET_BIASED][p].pstate = (((revle32(o_operating_points[VPD_PT_SET_BIASED][ULTRA].frequency_mhz) - revle32(o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz)) * 1000) / revle32(i_gppb->frequency_step_khz)); FAPI_DBG("Bi: OpPoint=[%d][%d], PS=%3d, Freq=%3X (%4d), Vdd=%3X (%4d), UT Freq=%3X (%4d) Step Freq=%5d", VPD_PT_SET_BIASED, p, o_operating_points[VPD_PT_SET_BIASED][p].pstate, revle32(o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_BIASED][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_BIASED][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_BIASED][ULTRA].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_BIASED][ULTRA].frequency_mhz), revle32(i_gppb->frequency_step_khz)); } //BIASED POINTS and SYSTEM PARMS APPLIED POINTS for (p = 0; p < NUM_OP_POINTS; p++) { uint32_t l_vdd_mv = revle32(o_operating_points[VPD_PT_SET_BIASED][p].vdd_mv); uint32_t l_idd_ma = revle32(o_operating_points[VPD_PT_SET_BIASED][p].idd_100ma) * 100; uint32_t l_vcs_mv = revle32(o_operating_points[VPD_PT_SET_BIASED][p].vcs_mv); uint32_t l_ics_ma = revle32(o_operating_points[VPD_PT_SET_BIASED][p].ics_100ma) * 100; o_operating_points[VPD_PT_SET_BIASED_SYSP][p].vdd_mv = sysparm_uplift(l_vdd_mv, l_idd_ma, l_vdd_loadline_uohm, l_vdd_distloss_uohm, l_vdd_distoffset_uv); o_operating_points[VPD_PT_SET_BIASED_SYSP][p].vcs_mv = sysparm_uplift(l_vcs_mv, l_ics_ma, l_vcs_loadline_uohm, l_vcs_distloss_uohm, l_vcs_distoffset_uv); o_operating_points[VPD_PT_SET_BIASED_SYSP][p].idd_100ma = o_operating_points[VPD_PT_SET_BIASED][p].idd_100ma; o_operating_points[VPD_PT_SET_BIASED_SYSP][p].ics_100ma = o_operating_points[VPD_PT_SET_BIASED][p].ics_100ma; o_operating_points[VPD_PT_SET_BIASED_SYSP][p].frequency_mhz = o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz; o_operating_points[VPD_PT_SET_BIASED_SYSP][p].pstate = o_operating_points[VPD_PT_SET_BIASED][p].pstate; FAPI_DBG("BS: OpPoint=[%d][%d], PS=%3d, Freq=%3X (%4d), Vdd=%3X (%4d)", VPD_PT_SET_BIASED_SYSP, p, o_operating_points[VPD_PT_SET_SYSP][p].pstate, revle32(o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv)); } } // Slope of m = (y1-y0)/(x1-x0) in 4.12 Fixed-Pt format int16_t compute_slope_4_12(uint32_t y1, uint32_t y0, uint32_t x1, uint32_t x0) { return (int16_t) ( // Perform division using floats for maximum precision // Store resulting slope in 4.12 Fixed-Pt format ((float)(y1 - y0) / (float)(x1 - x0)) * (1 << VID_SLOPE_FP_SHIFT_12) ); } // Slope of m = (y1-y0)/(x1-x0) in 3.13 Fixed-Pt format int16_t compute_slope_3_13(uint32_t y1, uint32_t y0, uint32_t x1, uint32_t x0) { return (int16_t) ( // Perform division using floats for maximum precision // Store resulting slope in 3.13 Fixed-Pt format ((float)(y1 - y0) / (float)(x1 - x0)) * (1 << VID_SLOPE_FP_SHIFT) ); } // Slope of m = (y1-y0)/(x1-x0) in 4.12 Fixed-Pt format for thresholds int16_t compute_slope_thresh(int32_t y1, int32_t y0, int32_t x1, int32_t x0) { return (int16_t) ( // Perform division using double for maximum precision // Store resulting slope in 4.12 Fixed-Pt format ((double)(y1 - y0) / (double)(x1 - x0)) * (1 << THRESH_SLOPE_FP_SHIFT) ); } // // p9_pstate_compute_PsV_slopes // // Computes slope of voltage-PState curve and PState-voltage // // PState(Frequency) on y-axis, Voltage is on x-axis for VF curve // Interpolation formula: (y-y0)/(x-x0) = (y1-y0)/(x1-x0) // m = (x1-x0)/(y1-y0), then use this to calculate voltage, x = (y-y0)*m + x0 // 1/m = (y1-y0)/(x1-x0) here, then use this to calculate pstate(frequency), y = (x-x0)*m + y0 // Region 0 is b/w POWERSAVE and NOMINAL // Region 1 is b/w NOMINAL and TURBO // Region 2 is between TURBO and ULTRA_TURBO // // Inflection Point 3 is ULTRA_TURBO // Inflection Point 2 is TURBO // Inflection Point 1 is NOMINAL // Inflection Point 0 is POWERSAVE // //\todo: Remove this. RTC: 174743 void p9_pstate_compute_PsV_slopes(VpdOperatingPoint i_operating_points[][4], GlobalPstateParmBlock* o_gppb) { for(auto pt_set = 0; pt_set < VPD_NUM_SLOPES_SET; ++pt_set) { FAPI_DBG("PsVSlopes pt_set %d", pt_set); // ULTRA TURBO pstate check is not required because its pstate will be 0 if (!(i_operating_points[pt_set][POWERSAVE].pstate) || !(i_operating_points[pt_set][NOMINAL].pstate) || !(i_operating_points[pt_set][TURBO].pstate)) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero for %s (%d)", vpdSetStr[pt_set], pt_set); break; } //Calculate slopes for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { // Pstate value decreases with increasing region. Thus the values // are swapped to result in a positive difference. o_gppb->PsVSlopes[pt_set][region] = revle16( compute_slope_3_13(revle32(i_operating_points[pt_set][region + 1].vdd_mv), revle32(i_operating_points[pt_set][region].vdd_mv), i_operating_points[pt_set][region].pstate, i_operating_points[pt_set][region + 1].pstate) ); FAPI_DBG("PsVSlopes[%s][%s] 0x%04x %d", vpdSetStr[pt_set], region_names[region], revle16(o_gppb->PsVSlopes[pt_set][region]), revle16(o_gppb->PsVSlopes[pt_set][region])); } //Calculate inverted slopes for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { // Pstate value decreases with increasing region. Thus the values // are swapped to result in a positive difference. o_gppb->VPsSlopes[pt_set][region] = revle16( compute_slope_3_13(i_operating_points[pt_set][region].pstate, i_operating_points[pt_set][region + 1].pstate, revle32(i_operating_points[pt_set][region + 1].vdd_mv), revle32(i_operating_points[pt_set][region].vdd_mv)) ); FAPI_DBG("VPsSlopes[%s][%s] 0x%04x %d", vpdSetStr[pt_set], region_names[region], revle16(o_gppb->VPsSlopes[pt_set][region]), revle16(o_gppb->VPsSlopes[pt_set][region])); } } } //This fills up the PStateVSlopes and VPStatesSlopes in GlobalParmBlock //Going forward this method should be retained in favor of the p9_pstate_compute_PsVSlopes void p9_pstate_compute_PStateV_slope(VpdOperatingPoint i_operating_points[][4], GlobalPstateParmBlock* o_gppb) { for(auto pt_set = 0; pt_set < NUM_VPD_PTS_SET; ++pt_set) { // ULTRA TURBO pstate check is not required..because it's pstate will be // 0 if (!(i_operating_points[pt_set][POWERSAVE].pstate) || !(i_operating_points[pt_set][NOMINAL].pstate) || !(i_operating_points[pt_set][TURBO].pstate)) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero for %s", vpdSetStr[pt_set]); return; } //Calculate slopes for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { // Pstate value decreases with increasing region. Thus the values // are swapped to result in a positive difference. o_gppb->PStateVSlopes[pt_set][region] = revle16( compute_slope_4_12(revle32(i_operating_points[pt_set][region + 1].vdd_mv), revle32(i_operating_points[pt_set][region].vdd_mv), i_operating_points[pt_set][region].pstate, i_operating_points[pt_set][region + 1].pstate) ); FAPI_DBG("PStateVSlopes[%s][%s] 0x%04x %d", vpdSetStr[pt_set], region_names[region], revle16(o_gppb->PStateVSlopes[pt_set][region]), revle16(o_gppb->PStateVSlopes[pt_set][region])); } //Calculate inverted slopes for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { // Pstate value decreases with increasing region. Thus the values // are swapped to result in a positive difference. o_gppb->VPStateSlopes[pt_set][region] = revle16( compute_slope_4_12(i_operating_points[pt_set][region].pstate, i_operating_points[pt_set][region + 1].pstate, revle32(i_operating_points[pt_set][region + 1].vdd_mv), revle32(i_operating_points[pt_set][region].vdd_mv)) ); FAPI_DBG("VPStateSlopes[%s][%s] 0x%04x %d", vpdSetStr[pt_set], region_names[region], revle16(o_gppb->VPStateSlopes[pt_set][region]), revle16(o_gppb->VPStateSlopes[pt_set][region])); } } } #define CENTER_STR(_buffer, _variable, _width) \ { \ int _w_ = _width-strlen(_variable)/2; \ sprintf(_buffer, " %*s%*s ", _w_, _variable, _w_, ""); \ } #define HEX_DEC_STR(_buffer, _hex, _dec) \ { \ char _temp_buffer[64]; \ sprintf(_temp_buffer, " %04X (%4d) ", _dec, _hex); \ strcat(_buffer, _temp_buffer); \ } /// Print a GlobalPstateParameterBlock structure on a given stream /// /// \param gppb The Global Pstate Parameter Block print void gppb_print(GlobalPstateParmBlock* i_gppb) { static const uint32_t BUFFSIZE = 256; char l_buffer[BUFFSIZE]; char l_temp_buffer[BUFFSIZE]; char l_temp_buffer1[BUFFSIZE]; const char* pv_op_str[NUM_OP_POINTS] = PV_OP_ORDER_STR; const char* thresh_op_str[NUM_THRESHOLD_POINTS] = VPD_THRESHOLD_ORDER_STR; const char* slope_region_str[VPD_NUM_SLOPES_REGION] = VPD_OP_SLOPES_REGION_ORDER_STR; // Put out the endian-corrected scalars FAPI_INF("---------------------------------------------------------------------------------------"); FAPI_INF("Global Pstate Parameter Block @ %p", i_gppb); FAPI_INF("---------------------------------------------------------------------------------------"); FAPI_INF("%-20s : %X", "Options", revle32(i_gppb->options.options)); FAPI_INF("%-20s : %X (%d)", "Reference Frequency", revle32(i_gppb->reference_frequency_khz), revle32(i_gppb->reference_frequency_khz)); FAPI_INF("%-20s : %X (%d)", "Frequency Step Size", revle32(i_gppb->frequency_step_khz), revle32(i_gppb->frequency_step_khz)); FAPI_INF("Operating Points: Frequency VDD(mV) IDD(100mA) VCS(mV) ICS(100mA)"); for (uint32_t i = 0; i < NUM_OP_POINTS; i++) { strcpy(l_buffer,""); sprintf (l_temp_buffer, " %-18s : ",pv_op_str[i]); strcat(l_buffer, l_temp_buffer); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].frequency_mhz), revle32(i_gppb->operating_points[i].frequency_mhz)); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].vdd_mv), revle32(i_gppb->operating_points[i].vdd_mv)); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].idd_100ma), revle32(i_gppb->operating_points[i].idd_100ma)); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].vcs_mv), revle32(i_gppb->operating_points[i].vcs_mv)); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].ics_100ma), revle32(i_gppb->operating_points[i].ics_100ma)); FAPI_INF("%s", l_buffer); } FAPI_INF("System Parameters: VDD VCS VDN") strcpy(l_buffer,""); sprintf(l_temp_buffer, " %-30s :", "Load line (uOhm)"); strcat(l_buffer, l_temp_buffer); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdd_sysparm.loadline_uohm), revle32(i_gppb->vdd_sysparm.loadline_uohm)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vcs_sysparm.loadline_uohm), revle32(i_gppb->vcs_sysparm.loadline_uohm)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdn_sysparm.loadline_uohm), revle32(i_gppb->vdn_sysparm.loadline_uohm)); FAPI_INF("%s", l_buffer); strcpy(l_buffer,""); sprintf(l_temp_buffer, " %-30s :", "Distribution Loss (uOhm)"); strcat(l_buffer, l_temp_buffer); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdd_sysparm.distloss_uohm), revle32(i_gppb->vdd_sysparm.distloss_uohm)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vcs_sysparm.distloss_uohm), revle32(i_gppb->vcs_sysparm.distloss_uohm)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdn_sysparm.distloss_uohm), revle32(i_gppb->vdn_sysparm.distloss_uohm)); FAPI_INF("%s", l_buffer); strcpy(l_buffer,""); sprintf(l_temp_buffer, " %-30s :", "Offset (uV)"); strcat(l_buffer, l_temp_buffer); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdd_sysparm.distoffset_uv), revle32(i_gppb->vdd_sysparm.distoffset_uv)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vcs_sysparm.distoffset_uv), revle32(i_gppb->vcs_sysparm.distoffset_uv)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdn_sysparm.distoffset_uv), revle32(i_gppb->vdn_sysparm.distoffset_uv)); FAPI_INF("%s", l_buffer); FAPI_INF("Safe Parameters:"); FAPI_INF(" %-30s : %04X (%3d) ", "Frequency", revle32(i_gppb->safe_frequency_khz), revle32(i_gppb->safe_frequency_khz)); FAPI_INF(" %-30s : %04X (%3d) ", "Voltage", revle32(i_gppb->safe_voltage_mv), revle32(i_gppb->safe_voltage_mv)); FAPI_INF("Pstate Stepping Parameters:"); FAPI_INF(" %-30s : %04X (%3d) ", "Delay range exponent", revle32(i_gppb->vrm_stepdelay_range), revle32(i_gppb->vrm_stepdelay_range)); FAPI_INF(" %-30s : %04X (%3d) ", "Significand", revle32(i_gppb->vrm_stepdelay_value), revle32(i_gppb->vrm_stepdelay_value)); FAPI_INF("External VRM Parameters:"); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Transition Start", revle32(i_gppb->ext_vrm_transition_start_ns), revle32(i_gppb->ext_vrm_transition_start_ns)); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Transition Rate - Rising", revle32(i_gppb->ext_vrm_transition_rate_inc_uv_per_us), revle32(i_gppb->ext_vrm_transition_rate_inc_uv_per_us)); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Transition Rate - Falling", revle32(i_gppb->ext_vrm_transition_rate_dec_uv_per_us), revle32(i_gppb->ext_vrm_transition_rate_dec_uv_per_us)); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Settling Time (us)", revle32(i_gppb->ext_vrm_transition_rate_dec_uv_per_us), revle32(i_gppb->ext_vrm_transition_rate_dec_uv_per_us)); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Transition Step Size (mV)", revle32(i_gppb->ext_vrm_step_size_mv), revle32(i_gppb->ext_vrm_step_size_mv)); FAPI_INF(" %-30s : %04X (%3d) ", "Nest Frequency", revle32(i_gppb->nest_frequency_mhz), revle32(i_gppb->nest_frequency_mhz)); // 2 Slope sets sprintf(l_buffer, "PsVSlopes:"); sprintf( l_temp_buffer, "%9s", ""); strcat(l_buffer, l_temp_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, " %s ", prt_region_names[j]); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < VPD_NUM_SLOPES_SET; ++i) { sprintf(l_buffer, " %-16s : ", vpdSetStr[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, "%6s%04X%7s ", " ",revle16(i_gppb->PsVSlopes[i][j])," "); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "VPsSlopes:"); sprintf( l_temp_buffer, "%9s", ""); strcat(l_buffer, l_temp_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, " %s ", prt_region_names[j]); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < VPD_NUM_SLOPES_SET; ++i) { sprintf(l_buffer, " %-16s : ", vpdSetStr[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, "%6s%04X%7s ", " ",revle16(i_gppb->VPsSlopes[i][j])," "); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } // 4 Slope sets sprintf(l_buffer, "PstateVSlopes:"); sprintf( l_temp_buffer, "%5s", ""); strcat(l_buffer, l_temp_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, " %s ", prt_region_names[j]); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < NUM_VPD_PTS_SET; ++i) { sprintf(l_buffer, " %-16s : ", vpdSetStr[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, "%6s%04X%7s ", " ",revle16(i_gppb->PStateVSlopes[i][j])," "); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "VPstateSlopes:"); sprintf( l_temp_buffer, "%5s", ""); strcat(l_buffer, l_temp_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, " %s ", prt_region_names[j]); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < NUM_VPD_PTS_SET; ++i) { sprintf(l_buffer, " %-16s : ", vpdSetStr[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, "%6s%04X%7s ", " ",revle16(i_gppb->VPStateSlopes[i][j])," "); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } FAPI_INF ("VID Operating Points"); for (auto i = 0; i < NUM_OP_POINTS; ++i) { sprintf (l_buffer, " %-16s : %02X ",pv_op_str[i], i_gppb->vid_point_set[i]); FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "%-25s", "Thrshod Op Points: "); for (auto j = 0; j < NUM_THRESHOLD_POINTS; ++j) { CENTER_STR(l_temp_buffer, thresh_op_str[j], 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); strcpy(l_buffer,""); for (auto i = 0; i < NUM_OP_POINTS; ++i) { sprintf(l_buffer, " %-16s : ", pv_op_str[i]); for (auto j = 0; j < NUM_THRESHOLD_POINTS; ++j) { sprintf(l_temp_buffer1, "%04X", i_gppb->threshold_set[i][j]); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "VID Compare Slopes:"); int l_len = strlen(l_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer1, "%s", prt_region_names[j]); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); sprintf( l_buffer, "%*s", l_len+6," "); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer1, "%04X", revle16(i_gppb->PsVIDCompSlopes[j])); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); sprintf(l_buffer, "%-18s", "VDM Thrshld Slopes:"); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { CENTER_STR(l_temp_buffer, slope_region_str[j], 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < NUM_THRESHOLD_POINTS; ++i) { sprintf(l_buffer, " %-16s : ", thresh_op_str[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer1, " %3i ", i_gppb->PsVDMThreshSlopes[i][j]); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "%-18s", "VDM Jump Slopes: "); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { CENTER_STR(l_temp_buffer, slope_region_str[j], 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < NUM_THRESHOLD_POINTS; ++i) { sprintf(l_buffer, " %-16s : ", thresh_op_str[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer1, " %02X ", i_gppb->PsVDMJumpSlopes[i][j]); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } // // // // FAPI_INF ("VDM THRESHOLD SLOPES"); // // for (uint8_t i = 0; i < VPD_NUM_SLOPES_REGION; ++i) // { // strcpy(l_buffer,""); // sprintf (l_temp_buffer, " %s ",slope_region_str[i]); // FAPI_INF("%s", l_temp_buffer); // for (uint8_t j = 0; j < NUM_THRESHOLD_POINTS; ++j) // { // sprintf (l_temp_buffer, " %s : %02X ",thresh_op_str[j], i_gppb->PsVDMThreshSlopes[i][j]); // strcat (l_buffer, l_temp_buffer); // } // FAPI_INF("%s", l_buffer); // } // // FAPI_INF ("VDM JUMP SLOPES"); // // for (uint8_t i = 0; i < VPD_NUM_SLOPES_REGION; ++i) // { // strcpy(l_buffer,""); // sprintf (l_temp_buffer, " %s ",slope_region_str[i]); // FAPI_INF("%s", l_temp_buffer); // for (uint8_t j = 0; j < NUM_JUMP_VALUES; ++j) // { // sprintf (l_temp_buffer, " %s : %02X ",thresh_op_str[j], i_gppb->PsVDMJumpSlopes[i][j]); // strcat (l_buffer, l_temp_buffer); // } // FAPI_INF("%s", l_buffer); // } // Resonant Clocking FAPI_DBG("Resonant Clocking Setup:"); FAPI_DBG("Pstates ResClk Index"); for (auto i = 0; i < RESCLK_FREQ_REGIONS; ++i) { FAPI_DBG(" %03d %02d", i_gppb->resclk.resclk_freq[i], i_gppb->resclk.resclk_index[i]); } FAPI_INF("---------------------------------------------------------------------------------------"); } /// Print an OCCPstateParameterBlock structure on a given stream /// /// \param oppb The OCC Pstate Parameter Block print void oppb_print(OCCPstateParmBlock* i_oppb) { static const uint32_t BUFFSIZE = 256; char l_buffer[BUFFSIZE]; char l_temp_buffer[BUFFSIZE]; // Put out the endian-corrected scalars FAPI_INF("---------------------------------------------------------------------------------------"); FAPI_INF("OCC Pstate Parameter Block @ %p", i_oppb); FAPI_INF("---------------------------------------------------------------------------------------"); // fprintf(stream, "Magic: %llu\n", revle64(i_oppb->magic)); FAPI_INF("Operating Points: Frequency VDD(mV) IDD(100mA) VCS(mV) ICS(100mA)"); for (auto i = 0; i < NUM_OP_POINTS; i++) { sprintf(l_buffer, " "); sprintf(l_temp_buffer, " %04X (%4d) ", revle32(i_oppb->operating_points[i].frequency_mhz), revle32(i_oppb->operating_points[i].frequency_mhz)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%4d) ", revle32(i_oppb->operating_points[i].vdd_mv), revle32(i_oppb->operating_points[i].vdd_mv)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%4d) ", revle32(i_oppb->operating_points[i].idd_100ma), revle32(i_oppb->operating_points[i].idd_100ma)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%4d) ", revle32(i_oppb->operating_points[i].vcs_mv), revle32(i_oppb->operating_points[i].vcs_mv)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->operating_points[i].ics_100ma), revle32(i_oppb->operating_points[i].ics_100ma)); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); } FAPI_INF("System Parameters: VDD VCS VDN"); sprintf(l_buffer, " Load line (uOhm) "); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdd_sysparm.loadline_uohm), revle32(i_oppb->vdd_sysparm.loadline_uohm)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vcs_sysparm.loadline_uohm), revle32(i_oppb->vcs_sysparm.loadline_uohm)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdn_sysparm.loadline_uohm), revle32(i_oppb->vdn_sysparm.loadline_uohm)); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); sprintf(l_buffer, " Distribution Loss (uOhm) "); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdd_sysparm.distloss_uohm), revle32(i_oppb->vdd_sysparm.distloss_uohm)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vcs_sysparm.distloss_uohm), revle32(i_oppb->vcs_sysparm.distloss_uohm)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdn_sysparm.distloss_uohm), revle32(i_oppb->vdn_sysparm.distloss_uohm)); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); sprintf(l_buffer, " Offset (uV) "); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdd_sysparm.distoffset_uv), revle32(i_oppb->vdd_sysparm.distoffset_uv)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vcs_sysparm.distoffset_uv), revle32(i_oppb->vcs_sysparm.distoffset_uv)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdn_sysparm.distoffset_uv), revle32(i_oppb->vdn_sysparm.distoffset_uv)); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); FAPI_INF("Frequency Minumum (kHz): %04X (%3d)", revle32(i_oppb->frequency_min_khz), revle32(i_oppb->frequency_min_khz)); FAPI_INF("Frequency Maximum (kHz): %04X (%3d)", revle32(i_oppb->frequency_max_khz), revle32(i_oppb->frequency_max_khz)); FAPI_INF("Frequency Step (kHz): %04X (%3d)", revle32(i_oppb->frequency_step_khz), revle32(i_oppb->frequency_step_khz)); FAPI_INF("Pstate of Minimum Frequency: %02X (%3d)", i_oppb->pstate_min, i_oppb->pstate_min); FAPI_INF("Nest Frequency: %02X (%3d)", i_oppb->nest_frequency_mhz, i_oppb->nest_frequency_mhz); FAPI_INF("Nest Leakage Percent: %02X (%3d)", i_oppb->nest_leakage_percent, i_oppb->nest_leakage_percent); FAPI_INF("Ceff TDP Vdn: %02X (%3d)", i_oppb->ceff_tdp_vdn, i_oppb->ceff_tdp_vdn); FAPI_INF("Iac TDP VDD Turbo(10ma): %02X (%3d)", i_oppb->lac_tdp_vdd_turbo_10ma, i_oppb->lac_tdp_vdd_turbo_10ma); FAPI_INF("Iac TDP VDD Nominal(10ma): %02X (%3d)", i_oppb->lac_tdp_vdd_nominal_10ma, i_oppb->lac_tdp_vdd_nominal_10ma); FAPI_INF("WOF Elements"); sprintf(l_buffer, " WOF Enabled "); sprintf(l_temp_buffer, " %1d ", i_oppb->wof.wof_enabled); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); sprintf(l_buffer, " TDP RDP Factor "); sprintf(l_temp_buffer, " %04X (%3d) ", i_oppb->wof.tdp_rdp_factor, i_oppb->wof.tdp_rdp_factor); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); // Put out the structure to the trace iddq_print(&(i_oppb->iddq)); FAPI_INF("---------------------------------------------------------------------------------------"); } /// Print an iddq_print structure on a given stream /// /// \param i_iddqt pointer to Iddq structure to output void iddq_print(IddqTable* i_iddqt) { uint32_t i, j; const char* idd_meas_str[IDDQ_MEASUREMENTS] = IDDQ_ARRAY_VOLTAGES_STR; // char l_buffer_str[256]; // Temporary formatting string buffer // char l_line_str[256]; // Formatted output line string char l_buffer_str[1024]; // Temporary formatting string buffer char l_line_str[1024]; // Formatted output line string static const uint32_t IDDQ_DESC_SIZE = 56; static const uint32_t IDDQ_QUAD_SIZE = IDDQ_DESC_SIZE - strlen("Quad X:"); FAPI_INF("IDDQ"); // Put out the endian-corrected scalars // get IQ version and advance pointer 1-byte FAPI_INF(" IDDQ Version Number = %u", i_iddqt->iddq_version); FAPI_INF(" Sort Info: Good Quads = %02d Good Cores = %02d Good Caches = %02d", i_iddqt->good_quads_per_sort, i_iddqt->good_normal_cores_per_sort, i_iddqt->good_caches_per_sort); // get number of good normal cores in each quad strcpy(l_line_str, " Good normal cores:"); strcpy(l_buffer_str, ""); for (i = 0; i < MAXIMUM_QUADS; i++) { sprintf(l_buffer_str, " Quad %d = %u ", i, i_iddqt->good_normal_cores[i]); strcat(l_line_str, l_buffer_str); } FAPI_INF("%s", l_line_str); // get number of good caches in each quad strcpy(l_line_str, " Good caches: "); strcpy(l_buffer_str, ""); for (i = 0; i < MAXIMUM_QUADS; i++) { sprintf(l_buffer_str, " Quad %d = %u ", i, i_iddqt->good_caches[i]); strcat(l_line_str, l_buffer_str); } FAPI_INF("%s", l_line_str); // get RDP TO TDP scalling factor FAPI_INF(" RDP TO TDP scalling factor = %u", revle16(i_iddqt->rdp_to_tdp_scale_factor)); // get WOF IDDQ margin factor FAPI_INF(" WOF IDDQ margin factor = %u", revle16(i_iddqt->wof_iddq_margin_factor)); // get VDD Temperature scaling factor FAPI_INF(" VDD Temperature scaling factor = %u", revle16(i_iddqt->vdd_temperature_scale_factor)); // get VDN Temperature scaling factor FAPI_INF(" VDN Temperature scaling factor = %u", revle16(i_iddqt->vdn_temperature_scale_factor)); // All IQ IDDQ measurements are at 5mA resolution. The OCC wants to // consume these at 1mA values. thus, all values are multiplied by // 5 upon installation into the paramater block. static const uint32_t CONST_5MA_1MA = 5; FAPI_INF(" IDDQ data is converted 5mA units to 1mA units"); // Put out the measurement voltages to the trace. strcpy(l_line_str, " Measurement voltages:"); sprintf(l_buffer_str, "%-*s ", IDDQ_DESC_SIZE, l_line_str); strcpy(l_line_str, l_buffer_str); strcpy(l_buffer_str, ""); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { sprintf(l_buffer_str, " %*sV ", 5, idd_meas_str[i]); strcat(l_line_str, l_buffer_str); } FAPI_INF("%s", l_line_str); #define IDDQ_CURRENT_EXTRACT(_member) \ { \ uint16_t _temp = revle16(i_iddqt->_member) * CONST_5MA_1MA; \ sprintf(l_buffer_str, " %6.3f ", (double)_temp/1000); \ strcat(l_line_str, l_buffer_str); \ } // Temps are all 1B quantities. Not endianess issues. #define IDDQ_TEMP_EXTRACT(_member) \ sprintf(l_buffer_str, " %4.1f ", ((double)i_iddqt->_member)/2); \ strcat(l_line_str, l_buffer_str); #define IDDQ_TRACE(string, size) \ strcpy(l_line_str, string); \ sprintf(l_buffer_str, "%-*s", size, l_line_str);\ strcpy(l_line_str, l_buffer_str); \ strcpy(l_buffer_str, ""); // get IVDDQ measurements with all good cores ON IDDQ_TRACE (" IDDQ all good cores ON:", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_CURRENT_EXTRACT(ivdd_all_good_cores_on_caches_on[i]); } FAPI_INF("%s", l_line_str); // get IVDDQ measurements with all cores and caches OFF IDDQ_TRACE (" IVDDQ all cores and caches OFF:", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_CURRENT_EXTRACT(ivdd_all_cores_off_caches_off[i]); } FAPI_INF("%s", l_line_str);; // get IVDDQ measurements with all good cores OFF and caches ON IDDQ_TRACE (" IVDDQ all good cores OFF and caches ON:", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_CURRENT_EXTRACT(ivdd_all_good_cores_off_good_caches_on[i]); } FAPI_INF("%s", l_line_str); // get IVDDQ measurements with all good cores in each quad for (i = 0; i < MAXIMUM_QUADS; i++) { IDDQ_TRACE (" IVDDQ all good cores ON and caches ON ", IDDQ_QUAD_SIZE); sprintf(l_buffer_str, "Quad %d:", i); strcat(l_line_str, l_buffer_str); for (j = 0; j < IDDQ_MEASUREMENTS; j++) { IDDQ_CURRENT_EXTRACT(ivdd_quad_good_cores_on_good_caches_on[i][j]); } FAPI_INF("%s", l_line_str); } // get IVDN data IDDQ_TRACE (" IVDN", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_CURRENT_EXTRACT(ivdn[i]); } FAPI_INF("%s", l_line_str); // get average temperature measurements with all good cores ON IDDQ_TRACE (" Average temp all good cores ON:",IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_TEMP_EXTRACT(avgtemp_all_good_cores_on[i]); } FAPI_INF("%s", l_line_str); // get average temperature measurements with all cores and caches OFF IDDQ_TRACE (" Average temp all cores OFF, caches OFF:", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_TEMP_EXTRACT(avgtemp_all_cores_off_caches_off[i]); } FAPI_INF("%s", l_line_str); // get average temperature measurements with all good cores OFF and caches ON IDDQ_TRACE (" Average temp all good cores OFF, caches ON:",IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_TEMP_EXTRACT(avgtemp_all_good_cores_off[i]); } FAPI_INF("%s", l_line_str); // get average temperature measurements with all good cores in each quad for (i = 0; i < MAXIMUM_QUADS; i++) { IDDQ_TRACE (" Average temp all good cores ON, good caches ON ",IDDQ_QUAD_SIZE); sprintf(l_buffer_str, "Quad %d:", i); strcat(l_line_str, l_buffer_str); for (j = 0; j < IDDQ_MEASUREMENTS; j++) { IDDQ_TEMP_EXTRACT(avgtemp_quad_good_cores_on[i][j]); } FAPI_INF("%s", l_line_str); } // get average nest temperature nest IDDQ_TRACE (" Average temp Nest:",IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_TEMP_EXTRACT(avgtemp_vdn[i]); } FAPI_INF("%s", l_line_str); } // Convert frequency to Pstate number int freq2pState (const GlobalPstateParmBlock* gppb, const uint32_t freq_khz, Pstate* pstate, const FREQ2PSTATE_ROUNDING i_round) { int rc = 0; float pstate32 = 0; // ---------------------------------- // compute pstate for given frequency // ---------------------------------- pstate32 = ((float)(revle32(gppb->reference_frequency_khz) - (float)freq_khz)) / (float)revle32(gppb->frequency_step_khz); // @todo Bug fix from Characterization team to deal with VPD not being // exactly in step increments // - not yet included to separate changes // As higher Pstate numbers represent lower frequencies, the pstate must be // snapped to the nearest *higher* integer value for safety. (e.g. slower // frequencies are safer). if ((i_round == ROUND_SLOW) && (freq_khz)) { *pstate = (Pstate)internal_ceil(pstate32); FAPI_DBG("freq2pState: ROUND SLOW"); } else { *pstate = (Pstate)pstate32; FAPI_DBG("freq2pState: ROUND FAST"); } FAPI_DBG("freq2pState: freq_khz = %u (0x%X); pstate32 = %f; pstate = %u (0x%X)", freq_khz, freq_khz, pstate32, *pstate, *pstate); FAPI_DBG("freq2pState: ref_freq_khz = %u (0x%X); step_freq_khz= %u (0x%X)", revle32(gppb->reference_frequency_khz), revle32(gppb->reference_frequency_khz), revle32(gppb->frequency_step_khz), revle32(gppb->frequency_step_khz)); // ------------------------------ // perform pstate bounds checking // ------------------------------ if (pstate32 < PSTATE_MIN) { rc = -PSTATE_LT_PSTATE_MIN; *pstate = PSTATE_MIN; } if (pstate32 > PSTATE_MAX) { rc = -PSTATE_GT_PSTATE_MAX; *pstate = PSTATE_MAX; } return rc; } // Convert Pstate number to frequency int pState2freq (const GlobalPstateParmBlock* gppb, const Pstate i_pstate, uint32_t* o_freq_khz) { int rc = 0; float pstate32 = i_pstate; float l_freq_khz = 0; // ---------------------------------- // compute frequency from a pstate // ---------------------------------- l_freq_khz = ((float)(revle32(gppb->reference_frequency_khz)) - (pstate32 * (float)revle32(gppb->frequency_step_khz))); *o_freq_khz = (uint32_t)l_freq_khz; return rc; } fapi2::ReturnCode proc_get_mvpd_poundw(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t i_poundv_bucketId, LP_VDMParmBlock* o_vdmpb, PoundW_data* o_data, fapi2::voltageBucketData_t i_poundv_data, PSTATE_attribute_state* o_state) { std::vector<fapi2::Target<fapi2::TARGET_TYPE_EQ>> l_eqChiplets; fapi2::vdmData_t l_vdmBuf; uint8_t j = 0; uint8_t bucket_id = 0; uint8_t version_id = 0; const uint16_t VDM_VOLTAGE_IN_MV = 512; const uint16_t VDM_GRANULARITY = 4; const char* pv_op_str[NUM_OP_POINTS] = PV_OP_ORDER_STR; FAPI_DBG(">> proc_get_mvpd_poundw"); do { FAPI_DBG("proc_get_mvpd_poundw: VDM enable = %d, WOF enable %d", is_vdm_enabled(i_target,o_state), is_wof_enabled(i_target,o_state)); // Exit if both VDM and WOF is disabled if ((!is_vdm_enabled(i_target,o_state) && !is_wof_enabled(i_target,o_state))) { FAPI_INF(" proc_get_mvpd_poundw: BOTH VDM and WOF are disabled. Skipping remaining checks"); o_state->iv_vdm_enabled = false; o_state->iv_wof_enabled = false; break; } // Below fields for Nominal, Powersave, Turbo, Ultra Turbo // I-VDD Nominal TDP AC current 2B // I-VDD Nominal TDP DC current 2B // Overvolt Threshold 0.5 Upper nibble of byte // Small Threshold 0.5 Lower nibble of byte // Large Threshold 0.5 Upper nibble of byte // eXtreme Threshold 0.5 Lower nibble of byte // Small Frequency Drop 1B // Large Frequency Drop 1B // ----------------------------------------------------------------- l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ>(fapi2::TARGET_STATE_FUNCTIONAL); for (j = 0; j < l_eqChiplets.size(); j++) { uint8_t l_chipNum = 0xFF; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_eqChiplets[j], l_chipNum)); FAPI_INF("Chip Number => %u", l_chipNum); // clear out buffer to known value before calling fapiGetMvpdField memset(&l_vdmBuf, 0, sizeof(l_vdmBuf)); FAPI_TRY(p9_pm_get_poundw_bucket(l_eqChiplets[j], l_vdmBuf)); bucket_id = l_vdmBuf.bucketId; version_id = l_vdmBuf.version; FAPI_INF("#W chiplet = %u bucket id = %u", l_chipNum, bucket_id, version_id); //if we match with the bucket id, then we don't need to continue if (i_poundv_bucketId == bucket_id) { break; } } uint8_t l_poundw_static_data = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUND_W_STATIC_DATA_ENABLE, FAPI_SYSTEM, l_poundw_static_data), "Error from FAPI_ATTR_GET for attribute ATTR_POUND_W_STATIC_DATA_ENABLE"); if (l_poundw_static_data) { FAPI_INF("attribute ATTR_POUND_W_STATIC_DATA_ENABLE is set"); // copy the data to the pound w structure from a hardcoded table memcpy (o_data, &g_vpdData, sizeof (g_vpdData)); } else { FAPI_INF("attribute ATTR_POUND_W_STATIC_DATA_ENABLE is NOT set"); // copy the data to the pound w structure from the actual VPD image memcpy (o_data, l_vdmBuf.vdmData, sizeof (l_vdmBuf.vdmData)); } //Re-ordering to Natural order // When we read the data from VPD image the order will be N,PS,T,UT. // But we need the order PS,N,T,UT.. hence we are swapping the data // between PS and Nominal. poundw_entry_t l_tmp_data; memcpy (&l_tmp_data, &(o_data->poundw[VPD_PV_NOMINAL]), sizeof (poundw_entry_t)); memcpy (&(o_data->poundw[VPD_PV_NOMINAL]), &(o_data->poundw[VPD_PV_POWERSAVE]), sizeof(poundw_entry_t)); memcpy (&(o_data->poundw[VPD_PV_POWERSAVE]), &l_tmp_data, sizeof(poundw_entry_t)); // If the #W version is less than 3, validate Turbo VDM large threshold // not larger than -32mV. This filters out parts that have bad VPD. If // this check fails, log a recovered error, mark the VDMs disabled and // break out of the reset of the checks. uint32_t turbo_vdm_large_threshhold = (o_data->poundw[TURBO].vdm_large_extreme_thresholds >> 4) & 0x0F; FAPI_DBG("o_data->poundw[TURBO].vdm_large_thresholds 0x%X; grey code index %d; max grey code index %d", turbo_vdm_large_threshhold, g_GreyCodeIndexMapping[turbo_vdm_large_threshhold], GREYCODE_INDEX_M32MV); if (version_id < FULLY_VALID_POUNDW_VERSION && g_GreyCodeIndexMapping[turbo_vdm_large_threshhold] > GREYCODE_INDEX_M32MV) { o_state->iv_vdm_enabled = false; fapi2::ATTR_CHIP_EC_FEATURE_VDM_POUNDW_SUPPRESS_ERROR_Type l_suppress_pdw_error; FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_VDM_POUNDW_SUPPRESS_ERROR, i_target, l_suppress_pdw_error); if (l_suppress_pdw_error) { FAPI_INF("VDM #W ERROR: Turbo Large Threshold less than -32mV. Indicates bad VPD so VDMs being disabled and pressing on"); } else { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_VERY_INVALID_VDM_DATA(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_TURBO_LARGE_THRESHOLD(o_data->poundw[TURBO].vdm_large_extreme_thresholds), "VDM #W ERROR: Turbo Large Threshold less than -32mV. Indicates bad VPD so VDMs being disabled and pressing on"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } break; } // Validate the WOF content is non-zero if WOF is enabled if (is_wof_enabled(i_target,o_state)) { bool b_tdp_ac = true; bool b_tdp_dc = true; // Check that the WOF currents are non-zero for (auto p = 0; p < NUM_OP_POINTS; ++p) { FAPI_INF("%s ivdd_tdp_ac_current %5d (10mA) %6.2f (A)", pv_op_str[p], revle16(o_data->poundw[p].ivdd_tdp_ac_current_10ma), ((double)revle16(o_data->poundw[p].ivdd_tdp_ac_current_10ma)/100)); FAPI_INF("%s ivdd_tdp_dc_current %5d (10mA) %6.2f (A)", pv_op_str[p], revle16(o_data->poundw[p].ivdd_tdp_dc_current_10ma), ((double)revle16(o_data->poundw[p].ivdd_tdp_dc_current_10ma)/100)); if (!o_data->poundw[p].ivdd_tdp_ac_current_10ma) { FAPI_ERR("%s.ivdd_tdp_ac_current_10ma is zero!!!", pv_op_str[p]); b_tdp_ac = false; o_state->iv_wof_enabled = false; } if (!o_data->poundw[p].ivdd_tdp_dc_current_10ma) { FAPI_ERR("%s.ivdd_tdp_dc_current_10ma is zero!!!", pv_op_str[p]); b_tdp_dc = false; o_state->iv_wof_enabled = false; } } FAPI_ASSERT_NOEXIT(b_tdp_ac, fapi2::PSTATE_PB_POUND_W_TDP_IAC_INVALID(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_NOMINAL_TDP_IAC(o_data->poundw[NOMINAL].ivdd_tdp_dc_current_10ma) .set_POWERSAVE_TDP_IAC(o_data->poundw[POWERSAVE].ivdd_tdp_dc_current_10ma) .set_TURBO_TDP_IAC(o_data->poundw[TURBO].ivdd_tdp_dc_current_10ma) .set_ULTRA_TDP_IAC(o_data->poundw[ULTRA].ivdd_tdp_dc_current_10ma), "Pstate Parameter Block #W : one or more Idd TDP AC values are zero"); FAPI_ASSERT_NOEXIT(b_tdp_dc, fapi2::PSTATE_PB_POUND_W_TDP_IDC_INVALID(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_NOMINAL_TDP_IDC(o_data->poundw[NOMINAL].ivdd_tdp_dc_current_10ma) .set_POWERSAVE_TDP_IDC(o_data->poundw[POWERSAVE].ivdd_tdp_dc_current_10ma) .set_TURBO_TDP_IDC(o_data->poundw[TURBO].ivdd_tdp_dc_current_10ma) .set_ULTRA_TDP_IDC(o_data->poundw[ULTRA].ivdd_tdp_dc_current_10ma), "o_dataPstate Parameter Block #W : one or more Idd TDP DC values are zero"); // Set the return code to success to keep going. fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } // The rest of the processing here is all checking of the VDM content // within #W. If VDMs are not enabled (or supported), skip all of it if (!is_vdm_enabled(i_target,o_state)) { FAPI_INF(" proc_get_mvpd_poundw: VDM is disabled. Skipping remaining checks"); o_state->iv_vdm_enabled = false; break; } for (int i = 0; i < NUM_OP_POINTS; ++i) { uint32_t l_mv = 512 + (o_data->poundw[i].vdm_vid_compare_ivid << 2); FAPI_INF("%10s vdm_vid_compare_ivid %3d => %d mv", pv_op_str[i], o_data->poundw[i].vdm_vid_compare_ivid, l_mv); } //Validation of VPD Data // //If all VID compares are zero then use #V VDD voltage to populate local //data structure..So that we make progress in lab with early hardware if ( !(o_data->poundw[NOMINAL].vdm_vid_compare_ivid) && !(o_data->poundw[POWERSAVE].vdm_vid_compare_ivid) && !(o_data->poundw[TURBO].vdm_vid_compare_ivid) && !(o_data->poundw[ULTRA].vdm_vid_compare_ivid)) { //vdm_vid_compare_ivid will be in ivid units (eg HEX((Compare //Voltage (mv) - 512mV)/4mV). o_data->poundw[NOMINAL].vdm_vid_compare_ivid = (i_poundv_data.VddNomVltg - VDM_VOLTAGE_IN_MV ) / VDM_GRANULARITY; o_data->poundw[POWERSAVE].vdm_vid_compare_ivid = (i_poundv_data.VddPSVltg - VDM_VOLTAGE_IN_MV ) / VDM_GRANULARITY; o_data->poundw[TURBO].vdm_vid_compare_ivid = (i_poundv_data.VddTurboVltg - VDM_VOLTAGE_IN_MV ) / VDM_GRANULARITY; o_data->poundw[ULTRA].vdm_vid_compare_ivid = (i_poundv_data.VddUTurboVltg - VDM_VOLTAGE_IN_MV ) / VDM_GRANULARITY; }//if any one of the VID compares are zero, then need to fail because of BAD VPD image. else if ( !(o_data->poundw[NOMINAL].vdm_vid_compare_ivid) || !(o_data->poundw[POWERSAVE].vdm_vid_compare_ivid) || !(o_data->poundw[TURBO].vdm_vid_compare_ivid) || !(o_data->poundw[ULTRA].vdm_vid_compare_ivid)) { o_state->iv_vdm_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_INVALID_VID_VALUE(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_NOMINAL_VID_COMPARE_IVID_VALUE(o_data->poundw[NOMINAL].vdm_vid_compare_ivid) .set_POWERSAVE_VID_COMPARE_IVID_VALUE(o_data->poundw[POWERSAVE].vdm_vid_compare_ivid) .set_TURBO_VID_COMPARE_IVID_VALUE(o_data->poundw[TURBO].vdm_vid_compare_ivid) .set_ULTRA_VID_COMPARE_IVID_VALUE(o_data->poundw[ULTRA].vdm_vid_compare_ivid), "Pstate Parameter Block #W : one of the VID compare value is zero"); break; } // validate vid values bool l_compare_vid_value_state = 1; VALIDATE_VID_VALUES (o_data->poundw[POWERSAVE].vdm_vid_compare_ivid, o_data->poundw[NOMINAL].vdm_vid_compare_ivid, o_data->poundw[TURBO].vdm_vid_compare_ivid, o_data->poundw[ULTRA].vdm_vid_compare_ivid, l_compare_vid_value_state); if (!l_compare_vid_value_state) { o_state->iv_vdm_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_INVALID_VID_ORDER(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_NOMINAL_VID_COMPARE_IVID_VALUE(o_data->poundw[NOMINAL].vdm_vid_compare_ivid) .set_POWERSAVE_VID_COMPARE_IVID_VALUE(o_data->poundw[POWERSAVE].vdm_vid_compare_ivid) .set_TURBO_VID_COMPARE_IVID_VALUE(o_data->poundw[TURBO].vdm_vid_compare_ivid) .set_ULTRA_VID_COMPARE_IVID_VALUE(o_data->poundw[ULTRA].vdm_vid_compare_ivid), "Pstate Parameter Block #W VID compare data are not in increasing order"); break; } // validate threshold values bool l_threshold_value_state = 1; for (uint8_t p = 0; p < NUM_OP_POINTS; ++p) { FAPI_INF("o_data->poundw[%d].vdm_overvolt_thresholds 0x%X",p,(o_data->poundw[p].vdm_overvolt_small_thresholds >> 4) & 0x0F); FAPI_INF("o_data->poundw[%d].vdm_small_thresholds 0x%X",p,(o_data->poundw[p].vdm_overvolt_small_thresholds ) & 0x0F); FAPI_INF("o_data->poundw[%d].vdm_large_thresholds 0x%X",p,(o_data->poundw[p].vdm_large_extreme_thresholds >> 4) & 0x0F); FAPI_INF("o_data->poundw[%d].vdm_extreme_thresholds 0x%X",p,(o_data->poundw[p].vdm_large_extreme_thresholds) & 0x0F); VALIDATE_THRESHOLD_VALUES(((o_data->poundw[p].vdm_overvolt_small_thresholds >> 4) & 0x0F), // overvolt ((o_data->poundw[p].vdm_overvolt_small_thresholds) & 0x0F), //small ((o_data->poundw[p].vdm_large_extreme_thresholds >> 4) & 0x0F), //large ((o_data->poundw[p].vdm_large_extreme_thresholds) & 0x0F), //extreme l_threshold_value_state); if (!l_threshold_value_state) { o_state->iv_vdm_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_INVALID_THRESHOLD_VALUE(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_OP_POINT_TYPE(p) .set_VDM_OVERVOLT((o_data->poundw[p].vdm_overvolt_small_thresholds >> 4) & 0x0F) .set_VDM_SMALL(o_data->poundw[p].vdm_overvolt_small_thresholds & 0x0F) .set_VDM_EXTREME((o_data->poundw[p].vdm_large_extreme_thresholds >> 4) & 0x0F) .set_VDM_LARGE((o_data->poundw[p].vdm_large_extreme_thresholds) & 0x0F), "Pstate Parameter Block #W VDM threshold data are invalid"); break; } } bool l_frequency_value_state = 1; for (uint8_t p = 0; p < NUM_OP_POINTS; ++p) { // These fields are 4 bits wide, and stored in a uint8, hence the shifting // N_S, N_L, L_S, S_N FAPI_INF("o_data->poundw[%d] VDM_FREQ_DROP N_S = %d", p, ((o_data->poundw[p].vdm_normal_freq_drop >> 4) & 0x0F)); FAPI_INF("o_data->poundw[%d] VDM_FREQ_DROP N_L = %d", p, ((o_data->poundw[p].vdm_normal_freq_drop) & 0x0F)); FAPI_INF("o_data->poundw[%d] VDM_FREQ_RETURN L_S = %d", p, ((o_data->poundw[p].vdm_normal_freq_return >> 4) & 0x0F)); FAPI_INF("o_data->poundw[%d] VDM_FREQ_RETURN S_N = %d", p, ((o_data->poundw[p].vdm_normal_freq_return) & 0x0F)); VALIDATE_FREQUENCY_DROP_VALUES(((o_data->poundw[p].vdm_normal_freq_drop) & 0x0F), // N_L ((o_data->poundw[p].vdm_normal_freq_drop >> 4) & 0x0F), // N_S ((o_data->poundw[p].vdm_normal_freq_return >> 4) & 0x0F), // L_S ((o_data->poundw[p].vdm_normal_freq_return) & 0x0F), // S_N l_frequency_value_state); if (!l_frequency_value_state) { o_state->iv_vdm_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_INVALID_FREQ_DROP_VALUE(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_OP_POINT_TYPE(p) .set_VDM_NORMAL_SMALL((o_data->poundw[p].vdm_normal_freq_drop >> 4) & 0x0F) .set_VDM_NORMAL_LARGE(o_data->poundw[p].vdm_normal_freq_drop & 0x0F) .set_VDM_LARGE_SMALL((o_data->poundw[p].vdm_normal_freq_return >> 4) & 0x0F) .set_VDM_SMALL_NORMAL((o_data->poundw[p].vdm_normal_freq_return) & 0x0F), "Pstate Parameter Block #W VDM frequency drop data are invalid"); break; } } //Biased compare vid data fapi2::ATTR_VDM_VID_COMPARE_BIAS_0P5PCT_Type l_bias_value; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDM_VID_COMPARE_BIAS_0P5PCT, i_target, l_bias_value), "Error from FAPI_ATTR_GET for attribute ATTR_VDM_VID_COMPARE_BIAS_0P5PCT"); float l_pound_w_points[NUM_OP_POINTS]; for (uint8_t i = 0; i < NUM_OP_POINTS; i++) { l_pound_w_points[i] = calc_bias(l_bias_value[i]); o_data->poundw[i].vdm_vid_compare_ivid = (uint32_t)(o_data->poundw[i].vdm_vid_compare_ivid * l_pound_w_points[i]); FAPI_INF("vdm_vid_compare_ivid %x %x, %x", o_data->poundw[i].vdm_vid_compare_ivid, o_data->poundw[i].vdm_vid_compare_ivid, l_pound_w_points[i]); } memcpy(&(o_vdmpb->vpd_w_data), o_data, sizeof(o_vdmpb->vpd_w_data)); } while(0); fapi_try_exit: // Given #W has both VDM and WOF content, a failure needs to disable both if (fapi2::current_err != fapi2::FAPI2_RC_SUCCESS) { o_state->iv_vdm_enabled = false; o_state->iv_wof_enabled = false; } if (!(o_state->iv_vdm_enabled)) { // With VDMs disabled, we have to ensure that we have some Large // Jump values to compute the safe mode frequency and voltage as some // part sorts assume that uplift in their guardbands. As systems are // offered assuming VDM operability which elevates the floor, default // values are needed. large_jump_defaults(o_data); } FAPI_DBG("<< proc_get_mvpd_poundw"); return fapi2::current_err; } fapi2::ReturnCode proc_set_resclk_table_attrs(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PSTATE_attribute_state* o_state) { uint8_t l_resclk_freq_index[RESCLK_FREQ_REGIONS]; uint8_t l_l3_steparray[RESCLK_L3_STEPS]; uint16_t l_resclk_freq_regions[RESCLK_FREQ_REGIONS]; uint16_t l_resclk_value[RESCLK_STEPS]; uint16_t l_l3_threshold_mv; o_state->iv_resclk_enabled = true; do { // Perform some basic sanity checks on the header data structures (since // the header values are provided by another team) FAPI_ASSERT_NOEXIT((p9_resclk_defines::RESCLK_INDEX_VEC.size() == RESCLK_FREQ_REGIONS), fapi2::PSTATE_PB_RESCLK_INDEX_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_FREQ_REGIONS(RESCLK_FREQ_REGIONS) .set_INDEX_VEC_SIZE(p9_resclk_defines::RESCLK_INDEX_VEC.size()), "p9_resclk_defines.h RESCLK_INDEX_VEC.size() mismatch"); FAPI_ASSERT_NOEXIT((p9_resclk_defines::RESCLK_TABLE_VEC.size() == RESCLK_STEPS), fapi2::PSTATE_PB_RESCLK_TABLE_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_STEPS(RESCLK_STEPS) .set_TABLE_VEC_SIZE(p9_resclk_defines::RESCLK_TABLE_VEC.size()), "p9_resclk_defines.h RESCLK_TABLE_VEC.size() mismatch"); FAPI_ASSERT_NOEXIT((p9_resclk_defines::L3CLK_TABLE_VEC.size() == RESCLK_L3_STEPS), fapi2::PSTATE_PB_RESCLK_L3_TABLE_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_L3_STEPS(RESCLK_L3_STEPS) .set_L3_VEC_SIZE(p9_resclk_defines::L3CLK_TABLE_VEC.size()), "p9_resclk_defines.h L3CLK_TABLE_VEC.size() mismatch"); //FAPI_ASSERT_NOEXIT will log an error with recoverable.. but rc won't be //cleared.. So we are initializing again to continue further if (fapi2::current_err != fapi2::FAPI2_RC_SUCCESS) { o_state->iv_resclk_enabled = false; fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; break; } FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_L3_VALUE, i_target, l_l3_steparray)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGIONS, i_target, l_resclk_freq_regions)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGION_INDEX, i_target, l_resclk_freq_index)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_VALUE, i_target, l_resclk_value)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_L3_VOLTAGE_THRESHOLD_MV, i_target, l_l3_threshold_mv)); for (uint8_t i = 0; i < RESCLK_FREQ_REGIONS; ++i) { if (l_resclk_freq_regions[i] == 0) { l_resclk_freq_regions[i] = p9_resclk_defines::RESCLK_INDEX_VEC.at(i).freq; } if (l_resclk_freq_index[i] == 0) { l_resclk_freq_index[i] = p9_resclk_defines::RESCLK_INDEX_VEC.at(i).idx; } } for (uint8_t i = 0; i < RESCLK_STEPS; ++i) { if (l_resclk_value[i] == 0) { l_resclk_value[i] = p9_resclk_defines::RESCLK_TABLE_VEC.at(i); } } for (uint8_t i = 0; i < RESCLK_L3_STEPS; ++i) { if (l_l3_steparray[i] == 0) { l_l3_steparray[i] = p9_resclk_defines::L3CLK_TABLE_VEC.at(i); } } if(l_l3_threshold_mv == 0) { l_l3_threshold_mv = p9_resclk_defines::L3_VOLTAGE_THRESHOLD_MV; } FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_L3_VALUE, i_target, l_l3_steparray)); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGIONS, i_target, l_resclk_freq_regions)); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGION_INDEX, i_target, l_resclk_freq_index)); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_VALUE, i_target, l_resclk_value)); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_L3_VOLTAGE_THRESHOLD_MV, i_target, l_l3_threshold_mv)); }while(0); fapi_try_exit: return fapi2::current_err; } //@brief Initialize HOMER VFRT data fapi2::ReturnCode p9_pstate_update_vfrt(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const GlobalPstateParmBlock* i_gppb, uint8_t* i_pBuffer, HomerVFRTLayout_t* o_vfrt_data, uint32_t i_reference_freq) { uint32_t l_index_0 = 0; uint32_t l_index_1 = 0; uint8_t l_type = 0; uint32_t l_freq_khz = 0; uint32_t l_step_freq_khz; Pstate l_ps; l_step_freq_khz = revle32(i_gppb->frequency_step_khz); FAPI_DBG("l_step_freq_khz = 0x%X (%d)", l_step_freq_khz, l_step_freq_khz); //Initialize VFRT header o_vfrt_data->vfrtHeader.magic_number = revle16(UINT16_GET(i_pBuffer)); i_pBuffer += 2; o_vfrt_data->vfrtHeader.reserved = revle16(UINT16_GET(i_pBuffer)); i_pBuffer += 2; o_vfrt_data->vfrtHeader.type_version = *i_pBuffer; i_pBuffer++; o_vfrt_data->vfrtHeader.res_vdnId = *i_pBuffer; // Future: this name is not accurate but takes a header change. i_pBuffer++; o_vfrt_data->vfrtHeader.VddId_QAId = *i_pBuffer; // Future: this name is not accurate but takes a header change. i_pBuffer++; o_vfrt_data->vfrtHeader.rsvd_QAId = *i_pBuffer; i_pBuffer++; //find type l_type = (o_vfrt_data->vfrtHeader.type_version) >> 4; char l_buffer_str[256]; // Temporary formatting string buffer char l_line_str[256]; // Formatted output line string // Filtering Tracing output to only only QID of 0 bool b_output_trace = false; if (o_vfrt_data->vfrtHeader.rsvd_QAId == QID_KEY && o_vfrt_data->vfrtHeader.res_vdnId <= VDN_PERCENT_KEY) { b_output_trace = true; } FAPI_DBG("res_vdnId = %X, VDN_PERCENT_KEY = %X, .rsvd_QAId = %X, QID_KEY = %X, trace = %u", o_vfrt_data->vfrtHeader.res_vdnId, VDN_PERCENT_KEY, o_vfrt_data->vfrtHeader.rsvd_QAId, QID_KEY, b_output_trace); if (b_output_trace) { strcpy(l_line_str, "VFRT:"); sprintf(l_buffer_str, " %X Ver/Type %X VDN%% %3d VDD%% %3d QID %d", revle16(o_vfrt_data->vfrtHeader.magic_number), revle16(o_vfrt_data->vfrtHeader.type_version), o_vfrt_data->vfrtHeader.res_vdnId, /// BUG: this should be VDN!!! o_vfrt_data->vfrtHeader.VddId_QAId, /// BUG: this should be VDD!!! o_vfrt_data->vfrtHeader.rsvd_QAId); /// BUG: this should be resvQID!!! strcat(l_line_str, l_buffer_str); } const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_WOF_ENABLE_FRATIO_Type l_enable_fratio; FAPI_ATTR_GET(fapi2::ATTR_WOF_ENABLE_FRATIO, FAPI_SYSTEM, l_enable_fratio); fapi2::ATTR_WOF_ENABLE_VRATIO_Type l_enable_vratio; FAPI_ATTR_GET(fapi2::ATTR_WOF_ENABLE_VRATIO, FAPI_SYSTEM, l_enable_vratio); bool b_fratio_set = true; bool b_first_vratio_set = true; // Get the frequency biases in place and check that they all match double f_freq_bias = 0; int freq_bias_value_hp = 0; int freq_bias_value_m1_hp = 0; bool b_bias_error = false; for (auto v = 0; v < NUM_OP_POINTS; ++v) { freq_bias_value_hp = i_gppb->ext_biases[v].frequency_hp; if (v > 0) { if (freq_bias_value_hp != freq_bias_value_m1_hp) { b_bias_error = true; FAPI_DBG("FATAL Bias mismatch error: v = %d; freq_bias_value_hp = %d; freq_bias_value_m1_hp = %d", v, freq_bias_value_hp, freq_bias_value_m1_hp ); } } freq_bias_value_m1_hp = freq_bias_value_hp; if (v == ULTRA) { f_freq_bias = calc_bias(freq_bias_value_hp); } } FAPI_ASSERT(!b_bias_error, fapi2::PSTATE_PB_VFRT_BIAS_ERROR() .set_CHIP_TARGET(i_target) .set_FREQ_BIAS_HP_ULTRATURBO(i_gppb->ext_biases[ULTRA].frequency_hp) .set_FREQ_BIAS_HP_TURBO(i_gppb->ext_biases[TURBO].frequency_hp) .set_FREQ_BIAS_HP_NOMINAL(i_gppb->ext_biases[NOMINAL].frequency_hp) .set_FREQ_BIAS_HP_POWERSAVE(i_gppb->ext_biases[POWERSAVE].frequency_hp) .set_UT_FREQ(i_reference_freq), "Frequency Biases do not match so VFRT biasing cannot occur"); if (f_freq_bias != 1) FAPI_INF("A frequency bias multiplier of %f being applied to all VFRT entries", f_freq_bias); //Initialize VFRT data part for (l_index_0 = 0; l_index_0 < VFRT_FRATIO_SIZE; ++l_index_0) { strcpy(l_buffer_str, ""); for (l_index_1 = 0; l_index_1 < VFRT_VRATIO_SIZE; ++l_index_1) { // Offset MHz*1000 (khz) + step (khz) * sysvalue float l_freq_raw_khz; float l_freq_biased_khz; l_freq_raw_khz = (float)(1000 * 1000 + (l_step_freq_khz * (*i_pBuffer))); l_freq_biased_khz = l_freq_raw_khz * f_freq_bias; // Round to nearest MHz as that is how the system tables are generated float l_freq_raw_up_mhz = (l_freq_biased_khz + 500)/1000; float l_freq_raw_dn_mhz = (l_freq_biased_khz)/1000; float l_freq_rounded_khz; if (l_freq_raw_up_mhz >= l_freq_raw_dn_mhz) l_freq_rounded_khz = (uint32_t)(l_freq_raw_up_mhz * 1000); else l_freq_rounded_khz = (uint32_t)(l_freq_raw_dn_mhz * 1000); l_freq_khz = (uint32_t)(l_freq_rounded_khz); FAPI_DBG("freq_raw_khz = %f; freq_biased_khz = %f; freq_rounded = 0x%X (%d); sysvalue = 0x%X (%d)", l_freq_raw_khz, l_freq_biased_khz, l_freq_khz, l_freq_khz, *i_pBuffer, *i_pBuffer); // Translate to Pstate. The called function will clip to the // legal range. The rc is only interesting if we care that // the pstate was clipped; in this case, we don't. freq2pState(i_gppb, l_freq_khz, &l_ps); o_vfrt_data->vfrt_data[l_index_0][l_index_1] = l_ps; if (b_first_vratio_set && l_index_1 >= 20 && b_output_trace) { sprintf(l_buffer_str, "[%2d][%2d] 0x%2X %4d; ", l_index_0, l_index_1, l_ps, l_freq_khz / 1000); strcat(l_line_str, l_buffer_str); } // Trace the last 8 values of the 24 for debug. As this is // in a loop that is processing over 1000 tables, the last // 8 gives a view that can correlate that the input data read // is correct without overfilling the HB trace buffer. if (l_index_1+1 == VFRT_VRATIO_SIZE && b_first_vratio_set && b_fratio_set && b_output_trace) { FAPI_INF("%s ", l_line_str); strcpy(l_buffer_str, ""); strcpy(l_line_str, " "); b_first_vratio_set = false; } i_pBuffer++; } // If fratio is not enabled, don't trace the remaining, duplicate entries. if (!l_enable_fratio) { b_fratio_set = false; b_first_vratio_set = false; } else { b_fratio_set = true; b_first_vratio_set = true; } } // Flip the type from System (0) to HOMER (1) l_type = 1; o_vfrt_data->vfrtHeader.type_version |= l_type << 4; fapi_try_exit: return fapi2::current_err; } /// Get IAC VDN vlue uint16_t get_iac_vdn_value (uint16_t i_vpd_vdn_mv, IddqTable i_iddq, uint8_t nest_leakage_percent, uint16_t i_vpd_idn_100ma) { uint16_t l_ac_vdn_value = 0; uint8_t l_iddq_index = 0; const uint8_t MIN_IDDQ_VALUE = 6; //considering 0.6 as 6 here for easy math const uint16_t IDDQ_MIN_VOLT_LEVEL = 600; uint8_t l_measured_temp_C[2] = {0}; uint16_t l_Ivdnq_5ma[2] = {0}; float l_scaled_leakage_ma[2] = {0}; uint16_t l_Ivdnq_vpd_ma = 0; uint8_t i = 0; uint8_t j = 0; //check bonunding is required or not uint16_t l_bounding_value = i_vpd_vdn_mv % 100; //Index to read from IDDQ table //Assumption here i_vpd_vdn_mv value will be greater than 600 and lesser //than 1100 mv l_iddq_index = (i_vpd_vdn_mv / 100) - MIN_IDDQ_VALUE; i = l_iddq_index; j = l_iddq_index + 1; uint16_t l_iq_mv[2] = {0}; l_iq_mv[0] = IDDQ_MIN_VOLT_LEVEL + (100 * i); l_iq_mv[1] = IDDQ_MIN_VOLT_LEVEL + (100 * (i + 1)); uint8_t l_diff_value = 0; do { if (!l_bounding_value) { //Read measured temp l_measured_temp_C[0] = i_iddq.avgtemp_vdn[i]; if ((l_measured_temp_C[0] == 0)) { FAPI_INF("Non Bounded measured temp value is 0"); break; } else if (l_measured_temp_C[0] < nest_leakage_percent) { l_diff_value = nest_leakage_percent - l_measured_temp_C[0]; } else { l_diff_value = l_measured_temp_C[0] - nest_leakage_percent; } //Read ivdnq_5ma l_Ivdnq_5ma[0] = i_iddq.ivdn[i]; //Scale each bounding Ivdnq_5ma value to 75C in mA l_scaled_leakage_ma[0] = l_Ivdnq_5ma[0] * 5 * pow (1.3, (l_diff_value / 10)); l_Ivdnq_vpd_ma = l_scaled_leakage_ma[0]; l_ac_vdn_value = (i_vpd_idn_100ma * 10) - (l_Ivdnq_vpd_ma * 10); } else { //Read measured temp l_measured_temp_C[0] = i_iddq.avgtemp_vdn[i]; l_measured_temp_C[1] = i_iddq.avgtemp_vdn[i + 1]; //Read ivdnq_5ma l_Ivdnq_5ma[0] = i_iddq.ivdn[i]; l_Ivdnq_5ma[1] = i_iddq.ivdn[i + 1]; //Scale each bounding Ivdnq_5ma value to 75C in mA for (j = 0; j < 2; j++) { if ((l_measured_temp_C[j] == 0)) { FAPI_INF("Bounded measured temp value is 0"); break; } else if (l_measured_temp_C[j] < nest_leakage_percent) { l_diff_value = nest_leakage_percent - l_measured_temp_C[j]; } else { l_diff_value = l_measured_temp_C[j] - nest_leakage_percent; } l_scaled_leakage_ma[j] = l_Ivdnq_5ma[j] * 5 * pow (1.3, (l_diff_value / 10)); } //Interpolate between scaled_leakage_ma[i] and scaled_leakage_ma[i+1] //using the same ratio as the VPD voltage is to the bounding volages) to //arrive at Ivdnq_vpd_ma l_Ivdnq_vpd_ma = l_scaled_leakage_ma[i] + roundUp((i_vpd_vdn_mv - 600 + (100 * i)) / ((l_iq_mv[1] - l_iq_mv[0]) * (l_scaled_leakage_ma[1] - l_scaled_leakage_ma[0]))); l_ac_vdn_value = (i_vpd_idn_100ma * 10) - (l_Ivdnq_vpd_ma * 10); } }while(0); return l_ac_vdn_value; } /** * calculate_effective_capacitance * * Description: Generic function to perform the effective capacitance * calculations. * C_eff = I / (V^1.3 * F) * * I is the AC component of Idd in 0.01 Amps (or10 mA) * V is the silicon voltage in 100 uV * F is the frequency in MHz * * Note: Caller must ensure they check for a 0 return value * and disable wof if that is the case * * Param[in]: i_iAC - the AC component * Param[in]: i_voltage - the voltage component in 100uV * Param[in]: i_frequency - the frequency component * * Return: The calculated effective capacitance */ uint16_t pstate_calculate_effective_capacitance( uint16_t i_iAC, uint16_t i_voltage, uint16_t i_frequency ) { // Compute V^1.3 using a best-fit equation // (V^1.3) = (21374 * (voltage in 100uV) - 50615296)>>10 uint32_t v_exp_1_dot_3 = (21374 * i_voltage - 50615296) >> 10; // Compute I / (V^1.3) uint32_t I = i_iAC << 14; // * 16384 // Prevent divide by zero if( v_exp_1_dot_3 == 0 ) { // Return 0 causing caller to disable wof. return 0; } uint32_t c_eff = (I / v_exp_1_dot_3); c_eff = c_eff << 14; // * 16384 // Divide by frequency and return the final value. // (I / (V^1.3 * F)) == I / V^1.3 /F return c_eff / i_frequency; } uint16_t roundUp(float i_value) { return ((uint16_t)(i_value == (uint16_t)i_value ? i_value : i_value + 1)); } // // p9_pstate_compute_vdm_threshold_pts // void p9_pstate_compute_vdm_threshold_pts(PoundW_data i_data, LocalPstateParmBlock* io_lppb) { int p = 0; //VID POINTS for (p = 0; p < NUM_OP_POINTS; p++) { io_lppb->vid_point_set[p] = i_data.poundw[p].vdm_vid_compare_ivid; FAPI_INF("Bi:VID=%x", io_lppb->vid_point_set[p]); } // Threshold points for (p = 0; p < NUM_OP_POINTS; p++) { // overvolt threshold io_lppb->threshold_set[p][VDM_OVERVOLT_INDEX] = g_GreyCodeIndexMapping[(i_data.poundw[p].vdm_overvolt_small_thresholds >> 4) & 0x0F]; FAPI_INF("Bi: OV TSHLD =%d", io_lppb->threshold_set[p][0]); // small threshold io_lppb->threshold_set[p][VDM_SMALL_INDEX] = (g_GreyCodeIndexMapping[i_data.poundw[p].vdm_overvolt_small_thresholds & 0x0F]); FAPI_INF("Bi: SM TSHLD =%d", io_lppb->threshold_set[p][1]); // large threshold io_lppb->threshold_set[p][VDM_LARGE_INDEX] = (g_GreyCodeIndexMapping[(i_data.poundw[p].vdm_large_extreme_thresholds >> 4) & 0x0F]); FAPI_INF("Bi: LG TSHLD =%d", io_lppb->threshold_set[p][2]); // extreme threshold io_lppb->threshold_set[p][VDM_XTREME_INDEX] = (g_GreyCodeIndexMapping[i_data.poundw[p].vdm_large_extreme_thresholds & 0x0F]); FAPI_INF("Bi: EX TSHLD =%d", io_lppb->threshold_set[p][3]); } // Jump value points for (p = 0; p < NUM_OP_POINTS; p++) { // N_L value io_lppb->jump_value_set[p][VDM_N_S_INDEX] = (i_data.poundw[p].vdm_normal_freq_drop >> 4) & 0x0F; FAPI_INF("Bi: N_S =%d", io_lppb->jump_value_set[p][0]); // N_S value io_lppb->jump_value_set[p][VDM_N_L_INDEX] = i_data.poundw[p].vdm_normal_freq_drop & 0x0F; FAPI_INF("Bi: N_L =%d", io_lppb->jump_value_set[p][1]); // L_S value io_lppb->jump_value_set[p][VDM_L_S_INDEX] = (i_data.poundw[p].vdm_normal_freq_return >> 4) & 0x0F; FAPI_INF("Bi: L_S =%d", io_lppb->jump_value_set[p][2]); // S_L value io_lppb->jump_value_set[p][VDM_S_N_INDEX] = i_data.poundw[p].vdm_normal_freq_return & 0x0F; FAPI_INF("Bi: S_L =%d", io_lppb->jump_value_set[p][3]); } } // // // p9_pstate_compute_PsVIDCompSlopes_slopes // void p9_pstate_compute_PsVIDCompSlopes_slopes(PoundW_data i_data, LocalPstateParmBlock* io_lppb, uint8_t* i_pstate) { do { char const* region_names[] = { "REGION_POWERSAVE_NOMINAL", "REGION_NOMINAL_TURBO", "REGION_TURBO_ULTRA" }; // ULTRA TURBO pstate check is not required..because its pstate will be // 0 if (!(i_pstate[POWERSAVE]) || !(i_pstate[NOMINAL]) || !(i_pstate[TURBO])) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero"); break; } for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { io_lppb->PsVIDCompSlopes[region] = revle16( compute_slope_4_12( io_lppb->vid_point_set[region + 1], io_lppb->vid_point_set[region], i_pstate[region], i_pstate[region + 1]) ); FAPI_DBG("PsVIDCompSlopes[%s] 0x%04x %d", region_names[region], revle16(io_lppb->PsVIDCompSlopes[region]), revle16(io_lppb->PsVIDCompSlopes[region])); } } while(0); } // // // p9_pstate_compute_PsVDMThreshSlopes // void p9_pstate_compute_PsVDMThreshSlopes( LocalPstateParmBlock* io_lppb, uint8_t* i_pstate) { do { // ULTRA TURBO pstate check is not required..because its pstate will be // 0 if (!(i_pstate[POWERSAVE]) || !(i_pstate[NOMINAL]) || !(i_pstate[TURBO])) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero"); break; } for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { for (uint8_t i = 0; i < NUM_THRESHOLD_POINTS; ++i) { io_lppb->PsVDMThreshSlopes[region][i] = revle16( compute_slope_thresh(io_lppb->threshold_set[region+1][i], io_lppb->threshold_set[region][i], i_pstate[region], i_pstate[region+1]) ); FAPI_INF("PsVDMThreshSlopes %s %x TH_N %d TH_P %d PS_P %d PS_N %d", prt_region_names[region], revle16(io_lppb->PsVDMThreshSlopes[region][i]), io_lppb->threshold_set[region+1][i], io_lppb->threshold_set[region][i], i_pstate[region], i_pstate[region+1]); } } } while(0); } // // p9_pstate_compute_PsVDMJumpSlopes // void p9_pstate_compute_PsVDMJumpSlopes( LocalPstateParmBlock* io_lppb, uint8_t* i_pstate) { do { // ULTRA TURBO pstate check is not required..because its pstate will be // 0 if (!(i_pstate[POWERSAVE]) || !(i_pstate[NOMINAL]) || !(i_pstate[TURBO])) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero"); break; } //Calculate slopes // for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { for (uint8_t i = 0; i < NUM_JUMP_VALUES; ++i) { io_lppb->PsVDMJumpSlopes[region][i] = revle16( compute_slope_thresh(io_lppb->jump_value_set[region+1][i], io_lppb->jump_value_set[region][i], i_pstate[region], i_pstate[region+1]) ); FAPI_INF("PsVDMJumpSlopes %s %x N_S %d N_L %d L_S %d S_N %d", prt_region_names[region], revle16(io_lppb->PsVDMJumpSlopes[region][i]), io_lppb->jump_value_set[region+1][i], io_lppb->jump_value_set[region][i], i_pstate[region], i_pstate[region+1]); } } } while(0); } // p9_pstate_set_global_feature_attributes fapi2::ReturnCode p9_pstate_set_global_feature_attributes(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PSTATE_attribute_state i_state, QuadManagerFlags* o_qm_flags) { // Quad Manager Flags fapi2::buffer<uint16_t> l_data16; fapi2::ATTR_PSTATES_ENABLED_Type l_ps_enabled = (fapi2::ATTR_PSTATES_ENABLED_Type)fapi2::ENUM_ATTR_PSTATES_ENABLED_FALSE; fapi2::ATTR_RESCLK_ENABLED_Type l_resclk_enabled = (fapi2::ATTR_RESCLK_ENABLED_Type)fapi2::ENUM_ATTR_RESCLK_ENABLED_FALSE; fapi2::ATTR_VDM_ENABLED_Type l_vdm_enabled = (fapi2::ATTR_VDM_ENABLED_Type)fapi2::ENUM_ATTR_VDM_ENABLED_FALSE; fapi2::ATTR_IVRM_ENABLED_Type l_ivrm_enabled = (fapi2::ATTR_IVRM_ENABLED_Type)fapi2::ENUM_ATTR_IVRM_ENABLED_FALSE; fapi2::ATTR_WOF_ENABLED_Type l_wof_enabled = (fapi2::ATTR_WOF_ENABLED_Type)fapi2::ENUM_ATTR_WOF_ENABLED_FALSE; if (i_state.iv_pstates_enabled) { l_ps_enabled = (fapi2::ATTR_PSTATES_ENABLED_Type)fapi2::ENUM_ATTR_PSTATES_ENABLED_TRUE; } if (i_state.iv_resclk_enabled) { l_resclk_enabled = (fapi2::ATTR_RESCLK_ENABLED_Type)fapi2::ENUM_ATTR_RESCLK_ENABLED_TRUE; } if (i_state.iv_vdm_enabled) { l_vdm_enabled = (fapi2::ATTR_VDM_ENABLED_Type)fapi2::ENUM_ATTR_VDM_ENABLED_TRUE; } if (i_state.iv_ivrm_enabled) { l_ivrm_enabled = (fapi2::ATTR_IVRM_ENABLED_Type)fapi2::ENUM_ATTR_IVRM_ENABLED_TRUE; } if (i_state.iv_wof_enabled) { l_wof_enabled = (fapi2::ATTR_WOF_ENABLED_Type)fapi2::ENUM_ATTR_WOF_ENABLED_TRUE; } #define SET_ATTR(attr_name, target, attr_assign) \ FAPI_TRY(FAPI_ATTR_SET(attr_name, target, attr_assign),"Attribute set failed"); \ FAPI_INF("%-60s = 0x%08x %d", #attr_name, attr_assign, attr_assign); SET_ATTR(fapi2::ATTR_PSTATES_ENABLED, i_target, l_ps_enabled); SET_ATTR(fapi2::ATTR_RESCLK_ENABLED, i_target, l_resclk_enabled); SET_ATTR(fapi2::ATTR_VDM_ENABLED, i_target, l_vdm_enabled); SET_ATTR(fapi2::ATTR_IVRM_ENABLED, i_target, l_ivrm_enabled); SET_ATTR(fapi2::ATTR_WOF_ENABLED, i_target, l_wof_enabled); // ---------------- // set CME QM flags // ---------------- l_data16.flush<0>(); l_data16.insertFromRight<0, 1>(l_resclk_enabled); l_data16.insertFromRight<1, 1>(l_ivrm_enabled); l_data16.insertFromRight<2, 1>(l_vdm_enabled); l_data16.insertFromRight<3, 1>(l_wof_enabled); // DROOP_PROTECT -> DPLL Mode 3 // DROOP_PROTECT_OVERVOLT -> DPLL Mode 3.5 // DYNAMIC -> DPLL Mode 4 // DYNAMIC_PROTECT -> DPLL Mode 5 // enable_fmin enable_fmax enable_jump // DPLL Mode 2 0 0 0 // DPLL Mode 3 0 0 1 // DPLL Mode 4 X 1 0 // DPLL Mode 4 1 X 0 // DPLL Mode 3.5 0 1 1 // DPLL Mode 5 1 X 1 switch (attr.attr_dpll_vdm_response) { case fapi2::ENUM_ATTR_DPLL_VDM_RESPONSE_DROOP_PROTECT: l_data16 |= CME_QM_FLAG_SYS_JUMP_PROTECT; FAPI_INF("%-60s", "DPLL Response"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_JUMP_PROTECT"); break; case fapi2::ENUM_ATTR_DPLL_VDM_RESPONSE_DROOP_PROTECT_OVERVOLT: l_data16 |= CME_QM_FLAG_SYS_DYN_FMAX_ENABLE; l_data16 |= CME_QM_FLAG_SYS_JUMP_PROTECT; FAPI_INF("%-60s", "DPLL Response"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_DYN_FMAX_ENABLE"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_JUMP_PROTECT"); break; case fapi2::ENUM_ATTR_DPLL_VDM_RESPONSE_DYNAMIC: l_data16 |= CME_QM_FLAG_SYS_DYN_FMIN_ENABLE; l_data16 |= CME_QM_FLAG_SYS_DYN_FMAX_ENABLE; FAPI_INF("%-60s", "DPLL Response"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_DYN_FMIN_ENABLEE"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_DYN_FMAX_ENABLE"); break; case fapi2::ENUM_ATTR_DPLL_VDM_RESPONSE_DYNAMIC_PROTECT: l_data16 |= CME_QM_FLAG_SYS_DYN_FMIN_ENABLE; l_data16 |= CME_QM_FLAG_SYS_JUMP_PROTECT; FAPI_INF("%-60s", "DPLL Response"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_DYN_FMIN_ENABLE"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_JUMP_PROTECT"); break; } o_qm_flags->value = revle16(l_data16); FAPI_INF("%-60s = 0x%04x %d", "QM Flags", revle16(o_qm_flags->value)); fapi_try_exit: return fapi2::current_err; } //large_jump_interpolate uint32_t large_jump_interpolate(const Pstate i_pstate, const VpdOperatingPoint i_operating_points[NUM_OP_POINTS], const uint32_t i_step_frequency, const Pstate i_ps_pstate, const PoundW_data i_data) { uint8_t l_jump_value_set_ps = i_data.poundw[POWERSAVE].vdm_normal_freq_drop & 0x0F; uint8_t l_jump_value_set_nom = i_data.poundw[NOMINAL].vdm_normal_freq_drop & 0x0F; uint32_t l_slope_value = compute_slope_thresh(l_jump_value_set_nom, l_jump_value_set_ps, i_operating_points[POWERSAVE].pstate, i_operating_points[NOMINAL].pstate); uint32_t l_vdm_jump_value = (uint32_t)((int32_t)l_jump_value_set_ps + (((int32_t)l_slope_value * (i_ps_pstate - i_pstate)) >> THRESH_SLOPE_FP_SHIFT)); return l_vdm_jump_value; } //large_jump_defaults void large_jump_defaults(PoundW_data* io_data) { const float DEFAULT_VDM_DROP_PERCENT = 12.5; const float DEFAULT_VDM_DROP_DIVISOR = 32; float poundw_freq_drop_float = (DEFAULT_VDM_DROP_PERCENT/100)*DEFAULT_VDM_DROP_DIVISOR; uint8_t poundw_freq_drop_value = (uint8_t)poundw_freq_drop_float; FAPI_DBG ("DEFAULT_VDM_DROP_PERCENT = %6.3f%%; DEFAULT_VDM_DROP_DIVISOR = %6.3f; poundw_freq_drop_value = %f %X", DEFAULT_VDM_DROP_PERCENT, DEFAULT_VDM_DROP_DIVISOR, poundw_freq_drop_float, poundw_freq_drop_value); // N_S/N_L - each a nibble in a byte io_data->poundw[POWERSAVE].vdm_normal_freq_drop = poundw_freq_drop_value; io_data->poundw[NOMINAL].vdm_normal_freq_drop = poundw_freq_drop_value; FAPI_INF ("Using default Large Jump percentage (%6.3f%%) for N_L (%X) for both POWERSAVE and NOMINAL due to #W access failure ", DEFAULT_VDM_DROP_PERCENT, io_data->poundw[POWERSAVE].vdm_normal_freq_drop); return; } //ps2v_mv - Pstate to External Voltage in mV uint32_t ps2v_mv(const Pstate i_pstate, const VpdOperatingPoint i_operating_points[NUM_OP_POINTS], const uint32_t i_step_frequency) { uint32_t region_start, region_end; const char* pv_op_str[NUM_OP_POINTS] = PV_OP_ORDER_STR; FAPI_DBG("i_pstate = 0x%x, (%d)", i_pstate, i_pstate); // Determine the VPD region if(i_pstate > i_operating_points[NOMINAL].pstate) { region_start = POWERSAVE; region_end = NOMINAL; FAPI_DBG("Region POWERSAVE_NOMINAL detected"); } else if(i_pstate > i_operating_points[TURBO].pstate) { region_start = NOMINAL; region_end = TURBO; FAPI_DBG("Region NOMINAL_TURBO detected"); } else { region_start = TURBO; region_end = ULTRA; FAPI_DBG("Region TURBO_ULTRA detected"); } uint32_t l_SlopeValue = compute_slope_4_12(revle32(i_operating_points[region_end].vdd_mv), revle32(i_operating_points[region_start].vdd_mv), i_operating_points[region_start].pstate, i_operating_points[region_end].pstate); FAPI_INF("l_globalppb.i_operating_points[%s].vdd_mv 0x%-3x (%d)", pv_op_str[region_end], revle32(i_operating_points[region_end].vdd_mv), revle32(i_operating_points[region_end].vdd_mv)); FAPI_INF("l_globalppb.i_operating_points[%s].vdd_mv 0x%-3x (%d)", pv_op_str[region_start], revle32(i_operating_points[region_start].vdd_mv), revle32(i_operating_points[region_start].vdd_mv)); FAPI_INF("l_globalppb.i_operating_points[%s].pstate 0x%-3x (%d)", pv_op_str[region_end], i_operating_points[region_end].pstate, i_operating_points[region_end].pstate); FAPI_INF("l_globalppb.i_operating_points[%s].pstate 0x%-3x (%d)", pv_op_str[region_start], i_operating_points[region_start].pstate, i_operating_points[region_start].pstate); FAPI_INF ("l_SlopeValue %x",l_SlopeValue); uint32_t x = (l_SlopeValue * (-i_pstate + i_operating_points[region_start].pstate)); uint32_t y = x >> VID_SLOPE_FP_SHIFT_12; uint32_t l_vdd = (((l_SlopeValue * (-i_pstate + i_operating_points[region_start].pstate)) >> VID_SLOPE_FP_SHIFT_12) + revle32(i_operating_points[region_start].vdd_mv)); // Round up l_vdd = (l_vdd << 1) + 1; l_vdd = l_vdd >> 1; FAPI_DBG("i_pstate = %d " "i_operating_points[%s].pstate) = %d " "i_operating_points[%s].vdd_mv = %d " "VID_SLOPE_FP_SHIFT_12 = %X " "x = %x (%d) y = %x (%d)", i_pstate, pv_op_str[region_start], i_operating_points[region_start].pstate, pv_op_str[region_start], revle32(i_operating_points[region_start].vdd_mv), VID_SLOPE_FP_SHIFT_12, x, x, y, y); FAPI_INF ("l_vdd 0x%x (%d)", l_vdd, l_vdd); return l_vdd; } //p9_pstate_safe_mode_computation fapi2::ReturnCode p9_pstate_safe_mode_computation(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const VpdOperatingPoint i_operating_points[NUM_VPD_PTS_SET][NUM_OP_POINTS], const uint32_t i_reference_freq, const uint32_t i_step_frequency, const Pstate i_ps_pstate, Safe_mode_parameters *o_safe_mode_values, const PoundW_data i_poundw_data) { Safe_mode_parameters l_safe_mode_values; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_SAFE_MODE_FREQUENCY_MHZ_Type l_safe_mode_freq_mhz; fapi2::ATTR_SAFE_MODE_VOLTAGE_MV_Type l_safe_mode_mv; fapi2::ATTR_VDD_BOOT_VOLTAGE_Type l_boot_mv; uint32_t l_safe_mode_op_ps2freq_mhz; VpdOperatingPoint l_operating_point[NUM_OP_POINTS]; get_operating_point(i_operating_points, VPD_PT_SET_BIASED_SYSP, l_operating_point); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_CORE_FLOOR_MHZ, FAPI_SYSTEM, l_safe_mode_values.safe_op_freq_mhz)); // Core floor frequency should be less than ultra turbo freq.. // if not log an error if ((l_safe_mode_values.safe_op_freq_mhz*1000) > i_reference_freq) { FAPI_ERR("Core floor frequency %08x is greater than UltraTurbo frequency %08x", (l_safe_mode_values.safe_op_freq_mhz*1000), i_reference_freq); FAPI_ASSERT(false, fapi2::PSTATE_PB_CORE_FLOOR_FREQ_GT_UT_FREQ() .set_CHIP_TARGET(i_target) .set_CORE_FLOOR_FREQ(l_safe_mode_values.safe_op_freq_mhz*1000) .set_UT_FREQ(i_reference_freq), "Core floor freqency is greater than UltraTurbo frequency"); } FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SAFE_MODE_FREQUENCY_MHZ, i_target, l_safe_mode_freq_mhz)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SAFE_MODE_VOLTAGE_MV, i_target, l_safe_mode_mv)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDD_BOOT_VOLTAGE, i_target, l_boot_mv)); FAPI_DBG ("l_safe_mode_freq_mhz 0%08x (%d)", l_safe_mode_freq_mhz, l_safe_mode_freq_mhz); FAPI_DBG ("l_safe_mode_mv 0%08x (%d)", l_safe_mode_mv, l_safe_mode_mv); FAPI_DBG ("l_boot_mv 0%08x (%d)", l_boot_mv, l_boot_mv); FAPI_INF ("l_safe_mode_values.safe_op_freq_mhz 0%08x (%d)", l_safe_mode_values.safe_op_freq_mhz, l_safe_mode_values.safe_op_freq_mhz); FAPI_INF ("i_reference_freq 0%08x (%d)", i_reference_freq, i_reference_freq); FAPI_INF ("i_step_frequency 0%08x (%d)", i_step_frequency, i_step_frequency); // Calculate safe operational pstate. This must be rounded down to create // a faster Pstate than the floor l_safe_mode_values.safe_op_ps = ((float)(i_reference_freq) - (float)(l_safe_mode_values.safe_op_freq_mhz * 1000)) / (float)i_step_frequency; l_safe_mode_op_ps2freq_mhz = (i_reference_freq - (l_safe_mode_values.safe_op_ps * i_step_frequency)) / 1000; while (l_safe_mode_op_ps2freq_mhz < l_safe_mode_values.safe_op_freq_mhz) { l_safe_mode_values.safe_op_ps--; l_safe_mode_op_ps2freq_mhz = (i_reference_freq - (l_safe_mode_values.safe_op_ps * i_step_frequency)) / 1000; } // Calculate safe jump value for large frequency l_safe_mode_values.safe_vdm_jump_value = large_jump_interpolate(l_safe_mode_values.safe_op_ps, l_operating_point, i_step_frequency, i_ps_pstate, i_poundw_data); FAPI_INF ("l_safe_mode_values.safe_vdm_jump_value %x -> %5.2f %%", l_safe_mode_values.safe_vdm_jump_value, ((float)l_safe_mode_values.safe_vdm_jump_value/32)*100); // Calculate safe mode frequency - Round up to nearest MHz // The uplifted frequency is based on the fact that the DPLL percentage is a // "down" value. Hence: // X (uplifted safe) = Y (safe operating) / (1 - droop percentage) l_safe_mode_values.safe_mode_freq_mhz = (uint32_t) (((float)l_safe_mode_op_ps2freq_mhz * 1000 / (1 - (float)l_safe_mode_values.safe_vdm_jump_value/32) + 500) / 1000); if (l_safe_mode_freq_mhz) { l_safe_mode_values.safe_mode_freq_mhz = l_safe_mode_freq_mhz; FAPI_INF("Applying override safe mode freq value of %d MHz", l_safe_mode_freq_mhz); } else { FAPI_INF("Setting safe mode frequency to %d MHz (0x%x)", l_safe_mode_values.safe_mode_freq_mhz, l_safe_mode_values.safe_mode_freq_mhz); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SAFE_MODE_FREQUENCY_MHZ, i_target, l_safe_mode_values.safe_mode_freq_mhz)); } FAPI_INF ("l_safe_mode_values.safe_mode_freq_mhz 0x%0x (%d)", l_safe_mode_values.safe_mode_freq_mhz, l_safe_mode_values.safe_mode_freq_mhz); // Safe frequency must be less than ultra turbo freq. // if not log an error if ((l_safe_mode_values.safe_mode_freq_mhz*1000) > i_reference_freq) { FAPI_ERR("Safe mode frequency %08x is greater than UltraTurbo frequency %08x", (l_safe_mode_values.safe_op_freq_mhz*1000), i_reference_freq); FAPI_ASSERT(false, fapi2::PSTATE_PB_SAFE_FREQ_GT_UT_FREQ() .set_CHIP_TARGET(i_target) .set_SAFE_FREQ(l_safe_mode_values.safe_mode_freq_mhz*1000) .set_UT_FREQ(i_reference_freq), "Safe mode freqency is greater than UltraTurbo frequency"); } l_safe_mode_values.safe_mode_ps = ((float)(i_reference_freq) - (float)(l_safe_mode_values.safe_mode_freq_mhz * 1000)) / (float)i_step_frequency; FAPI_INF ("l_safe_mode_values.safe_mode_ps %x (%d)", l_safe_mode_values.safe_mode_ps, l_safe_mode_values.safe_mode_ps); // Calculate safe mode voltage // Use the biased with system parms operating points l_safe_mode_values.safe_mode_mv = ps2v_mv(l_safe_mode_values.safe_mode_ps, l_operating_point, i_step_frequency); if (l_safe_mode_mv) { l_safe_mode_values.safe_mode_mv = l_safe_mode_mv; FAPI_INF("Applying override safe mode voltage value of %d mV", l_safe_mode_mv); } else { FAPI_INF("Setting safe mode voltage to %d mv (0x%x)", l_safe_mode_values.safe_mode_mv, l_safe_mode_values.safe_mode_mv); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SAFE_MODE_VOLTAGE_MV, i_target, l_safe_mode_values.safe_mode_mv)); } FAPI_INF ("l_safe_mode_values.safe_mode_mv 0x%x (%d)", l_safe_mode_values.safe_mode_mv, l_safe_mode_values.safe_mode_mv); fapi2::ATTR_SAFE_MODE_NOVDM_UPLIFT_MV_Type l_uplift_mv; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SAFE_MODE_NOVDM_UPLIFT_MV, i_target, l_uplift_mv)); // Calculate boot mode voltage l_safe_mode_values.boot_mode_mv = l_safe_mode_values.safe_mode_mv + l_uplift_mv; FAPI_INF("l_safe_mode_values.boot_mode_mv 0x%x (%d)", l_safe_mode_values.boot_mode_mv, l_safe_mode_values.boot_mode_mv); memcpy (o_safe_mode_values,&l_safe_mode_values, sizeof(Safe_mode_parameters)); fapi_try_exit: return fapi2::current_err; } // *INDENT-ON* PM: fix Core floor being below PowerSave for boot/safe voltage Key_Cronus_Test=PM_REGRESS Change-Id: Id7651266a11af04c5d05ec4080f7901b7a64a742 CQ: SW424899 Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/57355 Tested-by: FSP CI Jenkins <aa9e4d9ac7cd25905e9c0dd36d4150516e73dd86@us.ibm.com> Tested-by: Jenkins Server <8e3f934e4c44875bc48d33da3ea13d93ba9a233f@us.ibm.com> Tested-by: Hostboot CI <52521565bd8ea18a2b112942dce4f4220a97c2c8@us.ibm.com> Tested-by: Cronus HW CI <a731a82009671cd8b97b45874b464801949fbbb7@us.ibm.com> Reviewed-by: AMIT J. TENDOLKAR <dbb26baba4b5f8b9f96883027867d8ea93350b6c@in.ibm.com> Reviewed-by: RANGANATHPRASAD G. BRAHMASAMUDRA <95a9682e5bdc1ccf6e82d516bbb3db21526dc713@in.ibm.com> Reviewed-by: Jennifer A. Stofer <ab93eca12e43608f33daa16a67357cd7b7e867ab@us.ibm.com> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pstate_parameter_block.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pstate_parameter_block.C /// @brief Setup Pstate super structure for PGPE/CME HCode /// /// *HWP HW Owner : Greg Still <stillgs@us.ibm.com> /// *HWP FW Owner : Prasad Bg Ranganath <prasadbgr@in.ibm.com> /// *HWP Team : PM /// *HWP Level : 3 /// *HWP Consumed by : PGPE,CME /// /// @verbatim /// Procedure Summary: /// - Read VPD and attributes to create the Pstate Parameter Block(s) (one each for PGPE,OCC and CMEs). /// @endverbatim // *INDENT-OFF* // // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <fapi2.H> #include <p9_pstate_parameter_block.H> #include <p9_hcd_memmap_base.H> #include "p9_pm_get_poundw_bucket.H" #include "p9_resclk_defines.H" #include <attribute_ids.H> #include <math.h> //the value in this table are in Index format uint8_t g_GreyCodeIndexMapping [] = { /* 0mV 0x00*/ 0, /* - 8mV 0x01*/ 1, /* -24mV 0x02*/ 3, /* -16mV 0x03*/ 2, /* -56mV 0x04*/ 7, /* -48mV 0x05*/ 6, /* -32mV 0x06*/ 4, /* -40mV 0x07*/ 5, /* -96mV 0x08*/ 12, /* -96mV 0x09*/ 12, /* -96mV 0x0a*/ 12, /* -96mV 0x0b*/ 12, /* -64mV 0x0c*/ 8, /* -72mV 0x0d*/ 9, /* -88mV 0x0e*/ 11, /* -80mV 0x0f*/ 10 }; // from above mapping const uint8_t GREYCODE_INDEX_M32MV = 4; // #W version number where no special checks are needed. const uint32_t FULLY_VALID_POUNDW_VERSION = 3; fapi2::vdmData_t g_vpdData = {1, 2, { 0x29, 0x0C, 0x05, 0xC3, 0x61, 0x36, 0x1, 0x3, 0x0, 0x0, //Nominal 0x28, 0xa8, 0x05, 0x5f, 0x21, 0x36, 0x1, 0x3, 0x0, 0x0, //PowerSave 0x29, 0x70, 0x06, 0x27, 0x71, 0x36, 0x1, 0x3, 0x0, 0x0, //Turbo 0x29, 0xD4, 0x06, 0x8b, 0x51, 0x36, 0x1, 0x3, 0x0, 0x0, //UltraTurbo 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0, 0x0, 0x0, 0x0, //Resistance 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0, 0x0, 0x0, 0x0 //Spare } }; uint8_t g_wofData[] = { 0x57, 0x46, 0x54, 0x48 /*MAGIC CODE WFTH*/, 0x00, 0x00, 0x00, 0x01 /*version*/, 0x00, 0x80 /*VFRT block size*/, 0x00, 0x08 /*VFRT header size*/, 0x00, 0x01 /*VFRT data size*/, 0x6 /*Quad value*/, 0x18 /*core count*/, 0x00, 0xFA /*Vdn start*/, 0x00, 0x64 /*Vdn step*/, 0x00, 0x08 /*Vdn size*/, 0x00, 0x00 /*Vdd start*/, 0x00, 0x32 /*Vdd step*/, 0x00, 0x15 /*Vdd size*/, 0x03, 0xE8 /*Vratio start*/, 0x00, 0x53 /*Vratio step*/, 0x00, 0x18 /*Vratio size*/, 0x03, 0xE8 /*Fratio start*/, 0x00, 0x64 /*Fratio step*/, 0x00, 0x5 /*Fratio size*/, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*Vdn percent*/, 0x00, 0x64 /*Socket power Watts*/, 0x07, 0x4a /*nest freq*/, 0x09, 0x60 /*nominl freq*/, 0x00, 0x00 /*RDP capacity*/, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* WOF table source tag*/, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*package name*/, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*Pad to 128B*/ }; // uint8_t g_sysvfrtData[] = {0x56, 0x54, 0x00, 0x00, 0x02, 0x01, 0x01, 0x06, /// VFRT header values // // Magic_codea(2B) // // reserved(2B) // // type(4b),version(4b) // // vdn(1B),vdd(1B) // // quad id(1B) // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D, // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D, // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D, // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D, // 0xB1, 0xB1, 0xB0, 0xAF, 0xA9, 0xA1, 0x97, 0x8E, 0x86, 0x7F, 0x78, 0x73, 0x6D, 0x68, 0x63, 0x5F, 0x5B, 0x57, 0x53, 0x4E, 0x4D, 0x4D, 0x4D, 0x4D // }; const uint8_t VDN_PERCENT_KEY = 35; const uint8_t QID_KEY = 6; uint8_t g_sysvfrtData[] = {0x56, 0x54, // Magic_code 2B) 0x00, 0x00, // reserved (2B) 0x02, // type(4b),version(4b) VDN_PERCENT_KEY, // vdn percentage(1B), 0x05, // vdd percentage(1B) QID_KEY, // quad id(1B) 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA8, 0xA5, 0xA5, 0xA1, 0x9D, 0x9A }; #define VALIDATE_VID_VALUES(w,x,y,z,state) \ if (!((w <= x) && (x <= y) && (y <= z))) \ {state = 0;} #define VALIDATE_THRESHOLD_VALUES(w,x,y,z,state) \ if ((w > 0x7 && w != 0xC) || /* overvolt */ \ (x == 8) || (x == 9) || (x > 0xF) || \ (y == 8) || (y == 9) || (y > 0xF) || \ (z == 8) || (z == 9) || (z > 0xF) ) \ {state = 0;} //w => N_L (w > 7 is invalid) //x => N_S (x > N_L is invalid) //y => L_S (y > (N_L - S_N) is invalid) //z => S_N (z > N_S is invalid #define VALIDATE_FREQUENCY_DROP_VALUES(w,x,y,z,state) \ if ((w > 7) || \ (x > w) || \ (y > (w - z)) || \ (z > x) || \ ((w | x | y | z) == 0)) \ {state = 0; } #define VALIDATE_WOF_HEADER_DATA(a,b,c,d,e,f,g,state) \ if ( ((!a) || (!b) || (!c) || (!d) || (!e) || (!f) || (!g))) \ {state = 0; } double internal_ceil(double x) { if ((x-(int)(x))>0) return (int)x+1; return ((int)x); } double internal_floor(double x) { if(x>=0)return (int)x; return (int)(x-0.9999999999999999); } // Struct Variable for all attributes AttributeList attr; // Strings used in traces char const* vpdSetStr[NUM_VPD_PTS_SET] = VPD_PT_SET_ORDER_STR; char const* region_names[] = { "REGION_POWERSAVE_NOMINAL", "REGION_NOMINAL_TURBO", "REGION_TURBO_ULTRA" }; char const* prt_region_names[] = VPD_OP_SLOPES_REGION_ORDER_STR; ///-------------------------------------- /// @brief Check wof is enabled or not /// @param[in] pstate attribute state /// @return true or false ///-------------------------------------- bool is_wof_enabled(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PSTATE_attribute_state* i_state) { uint8_t attr_dd_wof_not_supported; uint8_t attr_system_wof_disable; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_WOF_DISABLE, FAPI_SYSTEM, attr_system_wof_disable); FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_WOF_NOT_SUPPORTED, i_target, attr_dd_wof_not_supported); return (!(attr_system_wof_disable) && !(attr_dd_wof_not_supported) && i_state->iv_wof_enabled) ? true : false; } ///-------------------------------------- /// @brief Check vdm is enabled or not /// @param[in] pstate attribute state /// @return true or false ///-------------------------------------- bool is_vdm_enabled(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PSTATE_attribute_state* i_state) { const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; uint8_t attr_dd_vdm_not_supported; uint8_t attr_system_vdm_disable; FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_VDM_DISABLE, FAPI_SYSTEM, attr_system_vdm_disable); FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_VDM_NOT_SUPPORTED, i_target, attr_dd_vdm_not_supported); return (!(attr_system_vdm_disable) && !(attr_dd_vdm_not_supported) && i_state->iv_vdm_enabled) ? true : false; } void load_gppb_attrs(const AttributeList* i_attr, GlobalPstateParmBlock* o_globalppb) { //Variables for Loadline, Distribution loss and offset SysPowerDistParms l_vdd_sysparm; memset(&l_vdd_sysparm,0x00,sizeof(SysPowerDistParms)); SysPowerDistParms l_vcs_sysparm; memset(&l_vcs_sysparm,0x00,sizeof(SysPowerDistParms)); SysPowerDistParms l_vdn_sysparm; memset(&l_vdn_sysparm,0x00,sizeof(SysPowerDistParms)); // Frequency step variable double l_frequency_step_khz; // ----------------------------------------------- // System power distribution parameters // ----------------------------------------------- // VDD rail l_vdd_sysparm.loadline_uohm = revle32(i_attr->attr_proc_r_loadline_vdd_uohm); l_vdd_sysparm.distloss_uohm = revle32(i_attr->attr_proc_r_distloss_vdd_uohm); l_vdd_sysparm.distoffset_uv = revle32(i_attr->attr_proc_vrm_voffset_vdd_uv); // VCS rail l_vcs_sysparm.loadline_uohm = revle32(i_attr->attr_proc_r_loadline_vcs_uohm); l_vcs_sysparm.distloss_uohm = revle32(i_attr->attr_proc_r_distloss_vcs_uohm); l_vcs_sysparm.distoffset_uv = revle32(i_attr->attr_proc_vrm_voffset_vcs_uv); // VDN rail l_vdn_sysparm.loadline_uohm = revle32(i_attr->attr_proc_r_loadline_vdn_uohm); l_vdn_sysparm.distloss_uohm = revle32(i_attr->attr_proc_r_distloss_vdn_uohm); l_vdn_sysparm.distoffset_uv = revle32(i_attr->attr_proc_vrm_voffset_vdn_uv); o_globalppb->vdd_sysparm = l_vdd_sysparm; o_globalppb->vcs_sysparm = l_vcs_sysparm; o_globalppb->vdn_sysparm = l_vdn_sysparm; // frequency_step_khz l_frequency_step_khz = (i_attr->attr_freq_proc_refclock_khz / i_attr->attr_proc_dpll_divider); o_globalppb->frequency_step_khz = revle32((uint32_t)l_frequency_step_khz); o_globalppb->nest_frequency_mhz = revle32(i_attr->attr_nest_frequency_mhz); // External VRM parameters o_globalppb->ext_vrm_transition_start_ns = revle32(i_attr->attr_ext_vrm_transition_start_ns); o_globalppb->ext_vrm_transition_rate_inc_uv_per_us = revle32(i_attr->attr_ext_vrm_transition_rate_inc_uv_per_us); o_globalppb->ext_vrm_transition_rate_dec_uv_per_us = revle32(i_attr->attr_ext_vrm_transition_rate_dec_uv_per_us); o_globalppb->ext_vrm_stabilization_time_us = revle32(i_attr->attr_ext_vrm_stabilization_time_us); o_globalppb->ext_vrm_step_size_mv = revle32(i_attr->attr_ext_vrm_step_size_mv); // load the biases // Note: all are uint8_t so no endianess correction is necessary for (auto p = 0; p < NUM_OP_POINTS; p++) { switch (p) { case POWERSAVE: o_globalppb->ext_biases[p].frequency_hp = i_attr->attr_freq_bias_powersave; o_globalppb->ext_biases[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_powersave; o_globalppb->int_biases[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_powersave; break; case NOMINAL: o_globalppb->ext_biases[p].frequency_hp = i_attr->attr_freq_bias_nominal; o_globalppb->ext_biases[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_nominal; o_globalppb->int_biases[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_nominal; break; case TURBO: o_globalppb->ext_biases[p].frequency_hp = i_attr->attr_freq_bias_turbo; o_globalppb->ext_biases[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_turbo; o_globalppb->int_biases[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_turbo; break; case ULTRA: o_globalppb->ext_biases[p].frequency_hp = i_attr->attr_freq_bias_ultraturbo; o_globalppb->ext_biases[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_ultraturbo; o_globalppb->int_biases[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_ultraturbo; } o_globalppb->ext_biases[p].vdn_ext_hp = i_attr->attr_voltage_ext_vdn_bias; o_globalppb->ext_biases[p].vcs_ext_hp = i_attr->attr_voltage_ext_vcs_bias; } } // START OF PSTATE PARAMETER BLOCK function fapi2::ReturnCode p9_pstate_parameter_block( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PstateSuperStructure* io_pss, uint8_t* o_buf, uint32_t& io_size) { FAPI_DBG("> p9_pstate_parameter_block"); const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ReturnCode l_rc = 0; io_size = 0; const uint8_t pv_op_order[NUM_OP_POINTS] = VPD_PV_ORDER; const char* pv_op_str[NUM_OP_POINTS] = VPD_PV_ORDER_STR; do { // ----------------------------------------------------------- // Clear the PstateSuperStructure and install the magic number //---------------------------------------------------------- memset(io_pss, 0, sizeof(PstateSuperStructure)); FAPI_INF("Populating magic number in Pstate Parameter block structure"); (*io_pss).magic = revle64(PSTATE_PARMSBLOCK_MAGIC); //Local variables for Global,local and OCC parameter blocks // PGPE content GlobalPstateParmBlock l_globalppb; memset (&l_globalppb, 0, sizeof(GlobalPstateParmBlock)); // CME content LocalPstateParmBlock l_localppb; memset (&l_localppb, 0, sizeof(LocalPstateParmBlock)); // OCC content OCCPstateParmBlock l_occppb; memset (&l_occppb , 0, sizeof (OCCPstateParmBlock)); PSTATE_attribute_state l_state; l_state.iv_pstates_enabled = true; l_state.iv_resclk_enabled = true; l_state.iv_vdm_enabled = true; l_state.iv_ivrm_enabled = true; l_state.iv_wof_enabled = true; // Enablement state PoundW_data l_poundw_data; memset (&l_poundw_data,0,sizeof(l_poundw_data)); // MVPD #V variables uint32_t attr_mvpd_poundv[PV_D][PV_W]; uint32_t attr_mvpd_poundv_biased[PV_D][PV_W]; uint8_t present_chiplets = 0; uint32_t valid_pdv_points = 0; // Local IDDQ table variable IddqTable l_iddqt; memset( & l_iddqt, 0x00, sizeof(IddqTable)); //VDM Parm block GP_VDMParmBlock l_gp_vdmpb; memset (&l_gp_vdmpb,0x00,sizeof(GP_VDMParmBlock)); LP_VDMParmBlock l_lp_vdmpb; memset (&l_lp_vdmpb, 0x00, sizeof(LP_VDMParmBlock)); //Resonant Clocking setup ResonantClockingSetup l_resclk_setup; memset (&l_resclk_setup,0x00, sizeof(ResonantClockingSetup)); //IVRM Parm block IvrmParmBlock l_ivrmpb; memset (&l_ivrmpb, 0x00,sizeof(IvrmParmBlock)); // VPD voltage and frequency biases VpdBias l_vpdbias[NUM_OP_POINTS]; memset (l_vpdbias,0,sizeof(VpdBias)); // ------------------------- // Get all attributes needed // ------------------------- FAPI_INF("Getting Attributes to build Pstate Superstructure"); FAPI_TRY(proc_get_attributes(i_target, &attr), "Get attributes function failed"); // Put attr driven content into GPPB load_gppb_attrs(&attr, &l_globalppb); //if PSTATES_MODE is off then we dont need to execute further to collect //the data. if (attr.attr_pstate_mode == fapi2::ENUM_ATTR_SYSTEM_PSTATES_MODE_OFF) { FAPI_INF("Pstate mode is to not boot the PGPE. Thus, none of the parameter blocks will be constructed"); // Set the io_size to 0 so that memory allocation issues won't be // detected by the caller. io_size = 0; break; } // ---------------- // get #V data // ---------------- FAPI_IMP("Getting #V Data"); uint8_t l_poundv_bucketId = 0; // clear MVPD arrays memset(attr_mvpd_poundv, 0, sizeof(attr_mvpd_poundv)); memset(attr_mvpd_poundv_biased, 0, sizeof(attr_mvpd_poundv_biased)); fapi2::voltageBucketData_t l_poundv_data; FAPI_TRY(proc_get_mvpd_data(i_target, attr_mvpd_poundv, &valid_pdv_points, &present_chiplets, l_poundv_bucketId, &l_poundv_data, &l_state), "proc_get_mvpd_data function failed to retrieve pound V data"); for (int i = 0; i <= NUM_OP_POINTS - 1; i++) { FAPI_DBG("Raw #V operating point (%s) f=%u v=%u i=%u v=%u i=%u", pv_op_str[pv_op_order[i]], attr_mvpd_poundv[pv_op_order[i]][0], attr_mvpd_poundv[pv_op_order[i]][1], attr_mvpd_poundv[pv_op_order[i]][2], attr_mvpd_poundv[pv_op_order[i]][3], attr_mvpd_poundv[pv_op_order[i]][4]); } if (!present_chiplets) { FAPI_IMP("**** WARNING : There are no EQ chiplets present which means there is no valid #V VPD"); FAPI_IMP("**** WARNING : Pstates and all related functions will NOT be enabled."); l_state.iv_pstates_enabled = false; l_state.iv_resclk_enabled = false; l_state.iv_resclk_enabled = false; l_state.iv_wof_enabled = false; // Set the io_size to 0 so that memory allocation issues won't be // detected by the caller. io_size = 0; break; } FAPI_DBG("Pstate Base Frequency - Raw %X (%d)", attr_mvpd_poundv[ULTRA][0] * 1000, attr_mvpd_poundv[ULTRA][0] * 1000); VpdOperatingPoint l_raw_operating_points[NUM_OP_POINTS]; FAPI_INF("Load RAW VPD"); FAPI_TRY(load_mvpd_operating_point(attr_mvpd_poundv, l_raw_operating_points, revle32(l_globalppb.frequency_step_khz)), "Loading MVPD operating point failed"); // --------------------------------------------- // process external and internal bias attributes // --------------------------------------------- FAPI_IMP("Apply Biasing to #V"); // Copy to Bias array for (int i = 0; i <= NUM_OP_POINTS - 1; i++) { for (int d = 0; d < PV_D; ++d) { for (int w = 0; w < PV_W; ++w) { attr_mvpd_poundv_biased[d][w] = attr_mvpd_poundv[d][w]; } } FAPI_DBG("Biased #V operating point (%s) f=%u v=%u i=%u v=%u i=%u", pv_op_str[pv_op_order[i]], attr_mvpd_poundv_biased[pv_op_order[i]][0], attr_mvpd_poundv_biased[pv_op_order[i]][1], attr_mvpd_poundv_biased[pv_op_order[i]][2], attr_mvpd_poundv_biased[pv_op_order[i]][3], attr_mvpd_poundv_biased[pv_op_order[i]][4]); } FAPI_TRY(proc_get_extint_bias(attr_mvpd_poundv_biased, &attr, l_vpdbias), "Bias application function failed"); //Validating Bias values FAPI_INF("Validate Biasd Voltage and Frequency values"); FAPI_TRY(proc_chk_valid_poundv( i_target, attr_mvpd_poundv_biased, &valid_pdv_points, i_target.getChipletNumber(), l_poundv_bucketId, &l_state,true)); FAPI_DBG("Pstate Base Frequency - after bias %X (%d)", attr_mvpd_poundv_biased[ULTRA][0] * 1000, attr_mvpd_poundv_biased[ULTRA][0] * 1000); //if wof is disabled.. don't call IQ function if (is_wof_enabled(i_target,&l_state)) { // ---------------- // get IQ (IDDQ) data // ---------------- FAPI_INF("Getting IQ (IDDQ) Data"); l_rc = proc_get_mvpd_iddq(i_target, &l_iddqt, &l_state); if (l_rc) { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_IQ_ACCESS_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_FAPI_RC(l_rc), "Pstate Parameter Block proc_get_mvpd_iddq function failed"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } } else { FAPI_INF("Skipping IQ (IDDQ) Data as WOF is disabled"); l_state.iv_wof_enabled = false; } // ---------------- // get VDM Parameters data // ---------------- FAPI_INF("Getting VDM Parameters Data"); FAPI_TRY(proc_get_vdm_parms(i_target, &attr, &l_gp_vdmpb)); // Note: the proc_get_mvpd_poundw has the conditional checking for VDM // and WOF enablement as #W has both VDM and WOF content l_rc = proc_get_mvpd_poundw(i_target, l_poundv_bucketId, &l_lp_vdmpb, &l_poundw_data, l_poundv_data, &l_state); if (l_rc) { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_ACCESS_FAIL(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_FAPI_RC(l_rc), "Pstate Parameter Block proc_get_mvpd_poundw function failed"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } // ---------------- // get IVRM Parameters data // ---------------- FAPI_INF("Getting IVRM Parameters Data"); FAPI_TRY(proc_get_ivrm_parms(i_target, &attr, &l_ivrmpb, &l_state)); // ----------------------------------------------- // Global parameter block // ----------------------------------------------- // Needs to be Endianness corrected going into the block l_globalppb.magic = revle64(PSTATE_PARMSBLOCK_MAGIC); l_globalppb.options.options = 0; // until options get defined. // ----------------------------------------------- // populate VpdOperatingPoint with biased MVPD attributes // ----------------------------------------------- FAPI_INF("Load VPD"); // VPD operating point FAPI_TRY(load_mvpd_operating_point(attr_mvpd_poundv, l_globalppb.operating_points, revle32(l_globalppb.frequency_step_khz)), "Loading MVPD operating point failed"); VpdOperatingPoint l_operating_points[NUM_VPD_PTS_SET][NUM_OP_POINTS]; // Compute VPD pointsp9_pstate_compute_PStateV_slope p9_pstate_compute_vpd_pts(l_operating_points, &l_globalppb, l_raw_operating_points); memcpy(l_globalppb.operating_points_set, l_operating_points, sizeof(l_operating_points)); FAPI_INF("Pstate Base Frequency %X (%d)", revle32(l_globalppb.reference_frequency_khz), revle32(l_globalppb.reference_frequency_khz)); // VpdBias External and Internal Biases for Global and Local parameter // block for (uint8_t i = 0; i < NUM_OP_POINTS; i++) { l_globalppb.ext_biases[i] = l_vpdbias[i]; l_globalppb.int_biases[i] = l_vpdbias[i]; l_localppb.ext_biases[i] = l_vpdbias[i]; l_localppb.int_biases[i] = l_vpdbias[i]; } // VpdBias External and Internal Biases for Global and Local parameter // block for (uint8_t i = 0; i < NUM_OP_POINTS; i++) { l_globalppb.ext_biases[i] = l_vpdbias[i]; l_globalppb.int_biases[i] = l_vpdbias[i]; l_localppb.ext_biases[i] = l_vpdbias[i]; l_localppb.int_biases[i] = l_vpdbias[i]; } // safe_voltage_mv l_globalppb.safe_voltage_mv = revle32(attr.attr_pm_safe_voltage_mv); // safe_frequency_khz l_globalppb.safe_frequency_khz = revle32(attr.attr_pm_safe_frequency_mhz * 1000); FAPI_INF("Safe Mode Frequency %d (0x%X) kHz; Voltage %d (0x%X) mV", revle32(l_globalppb.safe_frequency_khz), revle32(l_globalppb.safe_frequency_khz), revle32(l_globalppb.safe_voltage_mv), revle32(l_globalppb.safe_voltage_mv)); // ---------------- // get Resonant clocking attributes // ---------------- { if (attr.attr_resclk_disable == fapi2::ENUM_ATTR_SYSTEM_RESCLK_DISABLE_OFF) { FAPI_TRY(proc_set_resclk_table_attrs(i_target, &l_state), "proc_set_resclk_table_attrs failed"); if (l_state.iv_resclk_enabled) { FAPI_TRY(proc_res_clock_setup(i_target, &l_resclk_setup, &l_globalppb)); l_localppb.resclk = l_resclk_setup; l_globalppb.resclk = l_resclk_setup; } FAPI_INF("Resonant Clocks are enabled"); } else { l_state.iv_resclk_enabled = false; FAPI_INF("Resonant Clocks are disabled. Skipping setup."); } } // VDMParmBlock vdm l_globalppb.vdm = l_gp_vdmpb; // IvrmParmBlock l_globalppb.ivrm = l_ivrmpb; // Calculate pre-calculated slopes p9_pstate_compute_PsV_slopes(l_operating_points, &l_globalppb); //Remote this RTC: 174743 p9_pstate_compute_PStateV_slope(l_operating_points, &l_globalppb); l_globalppb.dpll_pstate0_value = revle32(revle32(l_globalppb.reference_frequency_khz) / revle32(l_globalppb.frequency_step_khz)); FAPI_INF("l_globalppb.dpll_pstate0_value %X (%d)", revle32(l_globalppb.dpll_pstate0_value), revle32(l_globalppb.dpll_pstate0_value)); // ----------------------------------------------- // Local parameter block // ----------------------------------------------- l_localppb.magic = revle64(LOCAL_PARMSBLOCK_MAGIC); // VPD operating point FAPI_TRY(load_mvpd_operating_point(attr_mvpd_poundv_biased, l_localppb.operating_points, revle32(l_globalppb.frequency_step_khz)), "Loading MVPD operating point failed"); l_localppb.vdd_sysparm = l_globalppb.vdd_sysparm; // IvrmParmBlock l_localppb.ivrm = l_ivrmpb; // VDMParmBlock l_localppb.vdm = l_lp_vdmpb; l_localppb.dpll_pstate0_value = revle32(revle32(l_globalppb.reference_frequency_khz) / revle32(l_globalppb.frequency_step_khz)); FAPI_INF("l_localppb.dpll_pstate0_value %X (%d)", revle32(l_localppb.dpll_pstate0_value), revle32(l_localppb.dpll_pstate0_value)); uint8_t l_biased_pstate[NUM_OP_POINTS]; for (uint8_t i = 0; i < NUM_OP_POINTS; ++i) { l_biased_pstate[i] = l_operating_points[VPD_PT_SET_BIASED][i].pstate; FAPI_INF ("l_biased_pstate %d ", l_biased_pstate[i]); } if (attr.attr_system_vdm_disable == fapi2::ENUM_ATTR_SYSTEM_VDM_DISABLE_OFF) { p9_pstate_compute_vdm_threshold_pts(l_poundw_data, &l_localppb); // VID slope calculation p9_pstate_compute_PsVIDCompSlopes_slopes(l_poundw_data, &l_localppb, l_biased_pstate); // VDM threshold slope calculation p9_pstate_compute_PsVDMThreshSlopes(&l_localppb, l_biased_pstate); // VDM Jump slope calculation p9_pstate_compute_PsVDMJumpSlopes (&l_localppb, l_biased_pstate); //Initializing threshold and jump values for GPPB memcpy ( l_globalppb.vid_point_set, l_localppb.vid_point_set, sizeof(l_localppb.vid_point_set)); memcpy ( l_globalppb.threshold_set, l_localppb.threshold_set, sizeof(l_localppb.threshold_set)); memcpy ( l_globalppb.jump_value_set, l_localppb.jump_value_set, sizeof(l_localppb.jump_value_set)); memcpy ( l_globalppb.PsVIDCompSlopes, l_localppb.PsVIDCompSlopes, sizeof(l_localppb.PsVIDCompSlopes)); memcpy ( l_globalppb.PsVDMThreshSlopes, l_localppb.PsVDMThreshSlopes, sizeof(l_localppb.PsVDMThreshSlopes)); memcpy ( l_globalppb.PsVDMJumpSlopes, l_localppb.PsVDMJumpSlopes, sizeof(l_localppb.PsVDMJumpSlopes)); } // ----------------------------------------------- // OCC parameter block // ----------------------------------------------- l_occppb.magic = revle64(OCC_PARMSBLOCK_MAGIC); // VPD operating point FAPI_TRY(load_mvpd_operating_point(attr_mvpd_poundv_biased, l_occppb.operating_points, l_globalppb.frequency_step_khz), "Loading MVPD operating point failed"); l_occppb.vdd_sysparm = l_globalppb.vdd_sysparm; l_occppb.vcs_sysparm = l_globalppb.vcs_sysparm; l_occppb.vdn_sysparm = l_globalppb.vdn_sysparm; // frequency_min_khz - Value from Power safe operating point after biases Pstate l_ps; //Translate safe mode frequency to pstate freq2pState(&l_globalppb, revle32(attr.attr_pm_safe_frequency_mhz * 1000), &l_ps, ROUND_FAST); //Compute real frequency l_occppb.frequency_min_khz = l_globalppb.reference_frequency_khz - (l_ps * l_globalppb.frequency_step_khz); // frequency_max_khz - Value from Ultra Turbo operating point after biases l_occppb.frequency_max_khz = l_globalppb.reference_frequency_khz; // frequency_step_khz l_occppb.frequency_step_khz = l_globalppb.frequency_step_khz; //Power bus nest freq uint16_t l_pbus_nest_freq = revle16(l_poundv_data.pbFreq); FAPI_INF("l_pbus_nest_freq 0x%x", (l_pbus_nest_freq)); // I- VDN PB current uint16_t l_vpd_idn_100ma = revle16(l_poundv_data.IdnPbCurr); FAPI_INF("l_vpd_idn_100ma 0x%x", (l_vpd_idn_100ma)); if (is_wof_enabled(i_target,&l_state)) { // Iddq Table l_occppb.iddq = l_iddqt; l_occppb.wof.tdp_rdp_factor = revle32(attr.attr_tdp_rdp_current_factor); FAPI_INF("l_occppb.wof.tdp_rdp_factor 0x%x", revle32(l_occppb.wof.tdp_rdp_factor)); // nest leakage percent l_occppb.nest_leakage_percent = attr.attr_nest_leakage_percent; FAPI_INF("l_occppb.nest_leakage_percent 0x%x", l_occppb.nest_leakage_percent); l_occppb.lac_tdp_vdd_turbo_10ma = revle16(l_poundw_data.poundw[TURBO].ivdd_tdp_ac_current_10ma); l_occppb.lac_tdp_vdd_nominal_10ma = revle16(l_poundw_data.poundw[NOMINAL].ivdd_tdp_ac_current_10ma); FAPI_INF("l_occppb.lac_tdp_vdd_turbo_10ma 0x%x", l_occppb.lac_tdp_vdd_turbo_10ma); FAPI_INF("l_occppb.lac_tdp_vdd_nominal_10ma 0x%x",l_occppb.lac_tdp_vdd_nominal_10ma); //Power bus vdn voltage uint16_t l_vpd_vdn_mv = revle16(l_poundv_data.VdnPbVltg); FAPI_INF("l_vpd_vdn_mv 0x%x (%d)", l_vpd_vdn_mv, l_vpd_vdn_mv); uint8_t l_nest_leakage_for_occ = 75; uint16_t l_iac_tdp_vdn = get_iac_vdn_value ( l_vpd_vdn_mv, l_iddqt, l_nest_leakage_for_occ, l_vpd_idn_100ma); if (!l_iac_tdp_vdn) { l_state.iv_wof_enabled = false; } else { l_occppb.ceff_tdp_vdn = revle16( pstate_calculate_effective_capacitance(l_iac_tdp_vdn, l_vpd_vdn_mv * 1000, l_pbus_nest_freq) ); } FAPI_INF("l_iac_tdp_vdn 0x%x", l_iac_tdp_vdn); FAPI_INF("l_occppb.ceff_tdp_vdn 0x%x", revle16(l_occppb.ceff_tdp_vdn)); // Put the good_normal_cores value into the GPPB for PGPE // This is done as a union overlay so that the inter-platform headers // are not touched. GPPBOptionsPadUse pad; pad.fields.good_cores_in_sort = l_iddqt.good_normal_cores_per_sort; l_globalppb.options.pad = pad.value; // Note: the following is presently accurate as the first 3 bytes // are reserved. FAPI_INF("good normal cores per sort %d 0x%X", revle32(l_globalppb.options.pad), revle32(l_globalppb.options.pad)); } else { l_state.iv_wof_enabled = false; } //Update nest frequency in OPPB l_occppb.nest_frequency_mhz = l_globalppb.nest_frequency_mhz; // The minimum Pstate must be rounded FAST so that core floor // constraints are not violated. Pstate pstate_min; int rc = freq2pState(&l_globalppb, revle32(l_occppb.frequency_min_khz), &pstate_min, ROUND_FAST); switch (rc) { case -PSTATE_LT_PSTATE_MIN: FAPI_INF("OCC Minimum Frequency was clipped to Pstate 0"); break; case -PSTATE_GT_PSTATE_MAX: FAPI_INF("OCC Minimum Frequency %d KHz is outside the range that can be represented" " by a Pstate with a base frequency of %d KHz and step size %d KHz", revle32(l_occppb.frequency_min_khz), revle32(l_globalppb.reference_frequency_khz), revle32(l_globalppb.frequency_step_khz)); FAPI_INF("Pstate is set to %X (%d)", pstate_min); break; } l_occppb.pstate_min = pstate_min; FAPI_INF("l_occppb.pstate_min 0x%x (%u)", pstate_min, pstate_min); //Check WOF is enabled or not io_size = 0; if (is_wof_enabled(i_target,&l_state)) { FAPI_TRY(p9_pstate_wof_initialization( i_target, &l_globalppb, o_buf, io_size, &l_state, attr_mvpd_poundv_biased[VPD_PV_ULTRA][0]), "WOF initialization failure"); } else { FAPI_INF("WOF is not enabled"); l_state.iv_wof_enabled = false; } l_occppb.wof.wof_enabled = l_state.iv_wof_enabled; // QuadManagerFlags QuadManagerFlags l_qm_flags; FAPI_TRY(p9_pstate_set_global_feature_attributes(i_target, l_state, &l_qm_flags)); l_localppb.qmflags = l_qm_flags; // Put out the Parmater Blocks to the trace gppb_print(&(l_globalppb)); oppb_print(&(l_occppb)); // Populate Global,local and OCC parameter blocks into Pstate super structure (*io_pss).globalppb = l_globalppb; (*io_pss).localppb = l_localppb; (*io_pss).occppb = l_occppb; } while(0); fapi_try_exit: FAPI_DBG("< p9_pstate_parameter_block"); return fapi2::current_err; } // END OF PSTATE PARAMETER BLOCK function fapi2::ReturnCode p9_pstate_wof_initialization (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const GlobalPstateParmBlock* i_gppb, uint8_t* o_buf, uint32_t& io_size, PSTATE_attribute_state* o_state, const uint32_t i_base_state_frequency) { FAPI_DBG(">> WOF initialization"); fapi2::ReturnCode l_rc = 0; uint16_t l_vdd_size = 0; uint16_t l_vdn_size = 0; //this structure has VFRT header + data HomerVFRTLayout_t l_vfrt; memset (&l_vfrt, 0, sizeof(l_vfrt)); // Use new to avoid over-running the stack fapi2::ATTR_WOF_TABLE_DATA_Type* l_wof_table_data = (fapi2::ATTR_WOF_TABLE_DATA_Type*)new fapi2::ATTR_WOF_TABLE_DATA_Type; FAPI_DBG("l_wof_table_data addr = %p size = %d", l_wof_table_data, sizeof(fapi2::ATTR_WOF_TABLE_DATA_Type)); do { // If this attribute is set, fill in l_wof_table_data with the VFRT data // from the internal, static table. const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_SYS_VFRT_STATIC_DATA_ENABLE_Type l_sys_vfrt_static_data = 0; FAPI_ATTR_GET(fapi2::ATTR_SYS_VFRT_STATIC_DATA_ENABLE, FAPI_SYSTEM, l_sys_vfrt_static_data); if (l_sys_vfrt_static_data) { FAPI_DBG("ATTR_SYS_VFRT_STATIC_DATA_ENABLE is SET"); // Copy WOF header data memcpy (l_wof_table_data, g_wofData, sizeof(g_wofData)); uint32_t l_index = sizeof(g_wofData); WofTablesHeader_t* p_wfth; p_wfth = reinterpret_cast<WofTablesHeader_t*>(l_wof_table_data); FAPI_INF("WFTH: %X", revle32(p_wfth->magic_number)); l_vdn_size = revle16(p_wfth->vdn_size); l_vdd_size = revle16(p_wfth->vdd_size); if (l_sys_vfrt_static_data == fapi2::ENUM_ATTR_SYS_VFRT_STATIC_DATA_ENABLE_VDN_STEP_OFF) { l_vdn_size = 1; } FAPI_INF("STATIC WOF: l_vdn_size %04x, l_vdd_size %04x",l_vdn_size,l_vdd_size); memcpy(&l_vfrt, &g_sysvfrtData, sizeof (g_sysvfrtData)); for (uint32_t vdn = 0; vdn < l_vdn_size; ++vdn) { // This creates a VDN percentage value can that can test the trace // filtering. l_vfrt.vfrtHeader.res_vdnId = (vdn+1)*VDN_PERCENT_KEY; for (uint32_t vdd = 0; vdd < l_vdd_size; ++vdd) { for (uint32_t qid = 0; qid < ACTIVE_QUADS; ++qid) { l_vfrt.vfrtHeader.VddId_QAId = vdd << 4 | qid; FAPI_DBG(" l_vfrt.vfrtHeader res_vdnId = %1X VddId_QAId = 0x%2X", l_vfrt.vfrtHeader.res_vdnId, l_vfrt.vfrtHeader.VddId_QAId); memcpy((*l_wof_table_data) + l_index, &l_vfrt, sizeof (l_vfrt)); l_index += sizeof (g_sysvfrtData); } } } io_size = l_index; FAPI_DBG(" io_size = %d", io_size); } else { FAPI_DBG("ATTR_SYS_VFRT_STATIC_DATA_ENABLE is not SET"); // Read System VFRT data l_rc = FAPI_ATTR_GET(fapi2::ATTR_WOF_TABLE_DATA, FAPI_SYSTEM, (*l_wof_table_data)); if (l_rc) { FAPI_INF("Pstate Parameter Block ATTR_WOF_TABLE_DATA attribute failed. Disabling WOF"); o_state->iv_wof_enabled = false; // Write the returned error content to the error log fapi2::logError(l_rc,fapi2::FAPI2_ERRL_SEV_UNRECOVERABLE); break; } } // Copy WOF header data memcpy (o_buf, (*l_wof_table_data), sizeof(WofTablesHeader_t)); uint32_t l_wof_table_index = sizeof(WofTablesHeader_t); uint32_t l_index = sizeof(WofTablesHeader_t); //Validate WOF header part WofTablesHeader_t* p_wfth; p_wfth = reinterpret_cast<WofTablesHeader_t*>(o_buf); FAPI_INF("WFTH: %X", revle32(p_wfth->magic_number)); bool l_wof_header_data_state = 1; VALIDATE_WOF_HEADER_DATA(p_wfth->magic_number, p_wfth->reserved_version, p_wfth->vfrt_block_size, p_wfth->vfrt_block_header_size, p_wfth->vfrt_data_size, p_wfth->quads_active_size, p_wfth->core_count, l_wof_header_data_state); if (!l_wof_header_data_state) { o_state->iv_wof_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_WOF_HEADER_DATA_INVALID(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(FAPI_SYSTEM) .set_MAGIC_NUMBER(p_wfth->magic_number) .set_VERSION(p_wfth->reserved_version) .set_VFRT_BLOCK_SIZE(p_wfth->vfrt_block_size) .set_VFRT_HEADER_SIZE(p_wfth->vfrt_block_header_size) .set_VFRT_DATA_SIZE(p_wfth->vfrt_data_size) .set_QUADS_ACTIVE_SIZE(p_wfth->quads_active_size) .set_CORE_COUNT(p_wfth->core_count), "Pstate Parameter Block WOF Header validation failed"); break; } l_vdn_size = revle16(p_wfth->vdn_size) ? revle16(p_wfth->vdn_size) : 1; l_vdd_size = revle16(p_wfth->vdd_size) ? revle16(p_wfth->vdd_size) : 1; FAPI_INF("WOF: l_vdn_size %04x, l_vdd_size %04x",l_vdn_size,l_vdd_size); // Convert system vfrt to homer vfrt for (auto vfrt_index = 0; vfrt_index < (l_vdn_size * l_vdd_size * ACTIVE_QUADS); ++vfrt_index) { l_rc = p9_pstate_update_vfrt (i_target, i_gppb, ((*l_wof_table_data) + l_wof_table_index), &l_vfrt, i_base_state_frequency); if (l_rc) { o_state->iv_wof_enabled = false; FAPI_TRY(l_rc); // Exit the function as a fail } // Check for "VT" at the start of the magic number if (revle16(l_vfrt.vfrtHeader.magic_number) != 0x5654) { o_state->iv_wof_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_VFRT_HEADER_DATA_INVALID(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(FAPI_SYSTEM) .set_MAGIC_NUMBER(l_vfrt.vfrtHeader.magic_number) .set_VFRT_INDEX(vfrt_index), "Pstate Parameter Block: Invalid VFRT Magic word"); break; } l_wof_table_index += 128; //System vFRT size is 128B..hence need to jump after each VFRT entry memcpy(o_buf + l_index, &l_vfrt, sizeof (l_vfrt)); l_index += sizeof (l_vfrt); } io_size = l_index; } while(0); // This is for the case that the magic number didn't match and we don't // want to fail; rather, we just disable WOF. fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: delete l_wof_table_data; FAPI_DBG("<< WOF initialization"); return fapi2::current_err; } // START OF GET ATTRIBUTES fapi2::ReturnCode proc_get_attributes ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, AttributeList* io_attr) { const uint32_t EXT_VRM_TRANSITION_START_NS = 8000; const uint32_t EXT_VRM_TRANSITION_RATE_INC_UV_PER_US = 10000; const uint32_t EXT_VRM_TRANSITION_RATE_DEC_UV_PER_US = 10000; const uint32_t EXT_VRM_STABILIZATION_TIME_NS = 5; const uint32_t EXT_VRM_STEPSIZE_MV = 50; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; // -------------------------- // attributes not yet defined // -------------------------- io_attr->attr_dpll_bias = 0; io_attr->attr_undervolting = 0; // --------------------------------------------------------------- // set ATTR_PROC_DPLL_DIVIDER // --------------------------------------------------------------- FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_DPLL_DIVIDER, i_target, io_attr->attr_proc_dpll_divider), "fapiGetAttribute of ATTR_PROC_DPLL_DIVIDER failed"); FAPI_DBG("ATTR_PROC_DPLL_DIVIDER - get to %x", io_attr->attr_proc_dpll_divider); // If value is 0, set a default if (!io_attr->attr_proc_dpll_divider) { FAPI_DBG("ATTR_PROC_DPLL_DIVIDER - setting default to %x", io_attr->attr_proc_dpll_divider); io_attr->attr_proc_dpll_divider = 8; FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_DPLL_DIVIDER, i_target, io_attr->attr_proc_dpll_divider), "fapiSetAttribute of ATTR_PROC_DPLL_DIVIDER failed"); } FAPI_INF("ATTR_PROC_DPLL_DIVIDER - %x", io_attr->attr_proc_dpll_divider); // ---------------------------- // attributes currently defined // ---------------------------- #define DATABLOCK_GET_ATTR(attr_name, target, attr_assign) \ FAPI_TRY(FAPI_ATTR_GET(fapi2::attr_name, target, io_attr->attr_assign),"Attribute read failed"); \ FAPI_INF("%-60s = 0x%08x %d", #attr_name, io_attr->attr_assign, io_attr->attr_assign); // Frequency Bias attributes DATABLOCK_GET_ATTR(ATTR_FREQ_BIAS_ULTRATURBO, i_target, attr_freq_bias_ultraturbo); DATABLOCK_GET_ATTR(ATTR_FREQ_BIAS_TURBO, i_target, attr_freq_bias_turbo); DATABLOCK_GET_ATTR(ATTR_FREQ_BIAS_NOMINAL, i_target, attr_freq_bias_nominal); DATABLOCK_GET_ATTR(ATTR_FREQ_BIAS_POWERSAVE, i_target, attr_freq_bias_powersave); // Voltage Bias attributes DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDD_BIAS_ULTRATURBO, i_target, attr_voltage_ext_vdd_bias_ultraturbo); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDD_BIAS_TURBO, i_target, attr_voltage_ext_vdd_bias_turbo); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDD_BIAS_NOMINAL, i_target, attr_voltage_ext_vdd_bias_nominal); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDD_BIAS_POWERSAVE, i_target, attr_voltage_ext_vdd_bias_powersave); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VCS_BIAS, i_target, attr_voltage_ext_vcs_bias); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_EXT_VDN_BIAS, i_target, attr_voltage_ext_vdn_bias); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_INT_VDD_BIAS_ULTRATURBO, i_target, attr_voltage_int_vdd_bias_ultraturbo); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_INT_VDD_BIAS_TURBO, i_target, attr_voltage_int_vdd_bias_turbo); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_INT_VDD_BIAS_NOMINAL, i_target, attr_voltage_int_vdd_bias_nominal); DATABLOCK_GET_ATTR(ATTR_VOLTAGE_INT_VDD_BIAS_POWERSAVE, i_target, attr_voltage_int_vdd_bias_powersave); // Frequency attributes DATABLOCK_GET_ATTR(ATTR_FREQ_PROC_REFCLOCK_KHZ, FAPI_SYSTEM, attr_freq_proc_refclock_khz); DATABLOCK_GET_ATTR(ATTR_FREQ_PB_MHZ, FAPI_SYSTEM, attr_nest_frequency_mhz); DATABLOCK_GET_ATTR(ATTR_FREQ_CORE_CEILING_MHZ, FAPI_SYSTEM, attr_freq_core_ceiling_mhz); DATABLOCK_GET_ATTR(ATTR_SAFE_MODE_FREQUENCY_MHZ, i_target, attr_pm_safe_frequency_mhz); DATABLOCK_GET_ATTR(ATTR_SAFE_MODE_VOLTAGE_MV, i_target, attr_pm_safe_voltage_mv); DATABLOCK_GET_ATTR(ATTR_FREQ_CORE_FLOOR_MHZ, FAPI_SYSTEM, attr_freq_core_floor_mhz); // Loadline, Distribution loss and Distribution offset attributes DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VDD_UOHM, i_target, attr_proc_r_loadline_vdd_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VDD_UOHM, i_target, attr_proc_r_distloss_vdd_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VDD_UV, i_target, attr_proc_vrm_voffset_vdd_uv); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VDN_UOHM, i_target, attr_proc_r_loadline_vdn_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VDN_UOHM, i_target, attr_proc_r_distloss_vdn_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VDN_UV, i_target, attr_proc_vrm_voffset_vdn_uv); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VCS_UOHM, i_target, attr_proc_r_loadline_vcs_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VCS_UOHM, i_target, attr_proc_r_distloss_vcs_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VCS_UV, i_target, attr_proc_vrm_voffset_vcs_uv); // Read IVRM,WOF and DPLL attributes DATABLOCK_GET_ATTR(ATTR_SYSTEM_IVRM_DISABLE, FAPI_SYSTEM, attr_system_ivrm_disable); DATABLOCK_GET_ATTR(ATTR_SYSTEM_WOF_DISABLE, FAPI_SYSTEM, attr_system_wof_disable); DATABLOCK_GET_ATTR(ATTR_SYSTEM_VDM_DISABLE, FAPI_SYSTEM, attr_system_vdm_disable); DATABLOCK_GET_ATTR(ATTR_DPLL_VDM_RESPONSE, FAPI_SYSTEM, attr_dpll_vdm_response); DATABLOCK_GET_ATTR(ATTR_SYSTEM_RESCLK_DISABLE, FAPI_SYSTEM, attr_resclk_disable); DATABLOCK_GET_ATTR(ATTR_CHIP_EC_FEATURE_WOF_NOT_SUPPORTED, i_target, attr_dd_wof_not_supported); DATABLOCK_GET_ATTR(ATTR_CHIP_EC_FEATURE_VDM_NOT_SUPPORTED, i_target, attr_dd_vdm_not_supported); DATABLOCK_GET_ATTR(ATTR_SYSTEM_PSTATES_MODE, FAPI_SYSTEM, attr_pstate_mode); DATABLOCK_GET_ATTR(ATTR_TDP_RDP_CURRENT_FACTOR, i_target, attr_tdp_rdp_current_factor); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_TRANSITION_START_NS, FAPI_SYSTEM, attr_ext_vrm_transition_start_ns); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_TRANSITION_RATE_INC_UV_PER_US, FAPI_SYSTEM, attr_ext_vrm_transition_rate_inc_uv_per_us); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_TRANSITION_RATE_DEC_UV_PER_US, FAPI_SYSTEM, attr_ext_vrm_transition_rate_dec_uv_per_us); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_TRANSITION_STABILIZATION_TIME_NS, FAPI_SYSTEM, attr_ext_vrm_stabilization_time_us); DATABLOCK_GET_ATTR(ATTR_EXTERNAL_VRM_STEPSIZE, FAPI_SYSTEM, attr_ext_vrm_step_size_mv); DATABLOCK_GET_ATTR(ATTR_NEST_LEAKAGE_PERCENT, FAPI_SYSTEM, attr_nest_leakage_percent); // AVSBus ... needed by p9_setup_evid DATABLOCK_GET_ATTR(ATTR_VDD_AVSBUS_BUSNUM, i_target,vdd_bus_num); DATABLOCK_GET_ATTR(ATTR_VDD_AVSBUS_RAIL, i_target,vdd_rail_select); DATABLOCK_GET_ATTR(ATTR_VDN_AVSBUS_BUSNUM, i_target,vdn_bus_num); DATABLOCK_GET_ATTR(ATTR_VDN_AVSBUS_RAIL, i_target,vdn_rail_select); DATABLOCK_GET_ATTR(ATTR_VCS_AVSBUS_BUSNUM, i_target,vcs_bus_num); DATABLOCK_GET_ATTR(ATTR_VCS_AVSBUS_RAIL, i_target,vcs_rail_select); DATABLOCK_GET_ATTR(ATTR_VCS_BOOT_VOLTAGE, i_target,vcs_voltage_mv); DATABLOCK_GET_ATTR(ATTR_VDD_BOOT_VOLTAGE, i_target,vdd_voltage_mv); DATABLOCK_GET_ATTR(ATTR_VDN_BOOT_VOLTAGE, i_target,vdn_voltage_mv); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VDD_UOHM, i_target,r_loadline_vdd_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VDD_UOHM, i_target,r_distloss_vdd_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VDD_UV, i_target,vrm_voffset_vdd_uv ); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VDN_UOHM, i_target,r_loadline_vdn_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VDN_UOHM, i_target,r_distloss_vdn_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VDN_UV, i_target,vrm_voffset_vdn_uv ); DATABLOCK_GET_ATTR(ATTR_PROC_R_LOADLINE_VCS_UOHM, i_target,r_loadline_vcs_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_R_DISTLOSS_VCS_UOHM, i_target,r_distloss_vcs_uohm); DATABLOCK_GET_ATTR(ATTR_PROC_VRM_VOFFSET_VCS_UV, i_target,vrm_voffset_vcs_uv); DATABLOCK_GET_ATTR(ATTR_FREQ_PROC_REFCLOCK_KHZ, FAPI_SYSTEM, freq_proc_refclock_khz); DATABLOCK_GET_ATTR(ATTR_PROC_DPLL_DIVIDER, i_target, proc_dpll_divider); // AVSBus ... needed by p9_setup_evid // Deal with defaults if attributes are not set #define SET_DEFAULT(_attr_name, _attr_default) \ if (!(io_attr->_attr_name)) \ { \ io_attr->_attr_name = _attr_default; \ FAPI_INF("Setting %-44s = 0x%08x %d (internal default)", \ #_attr_name, io_attr->_attr_name, io_attr->_attr_name); \ } SET_DEFAULT(attr_freq_proc_refclock_khz, 133333); SET_DEFAULT(freq_proc_refclock_khz, 133333); // Future: collapse this out SET_DEFAULT(attr_ext_vrm_transition_start_ns, EXT_VRM_TRANSITION_START_NS) SET_DEFAULT(attr_ext_vrm_transition_rate_inc_uv_per_us, EXT_VRM_TRANSITION_RATE_INC_UV_PER_US) SET_DEFAULT(attr_ext_vrm_transition_rate_dec_uv_per_us, EXT_VRM_TRANSITION_RATE_DEC_UV_PER_US) SET_DEFAULT(attr_ext_vrm_stabilization_time_us, EXT_VRM_STABILIZATION_TIME_NS) SET_DEFAULT(attr_ext_vrm_step_size_mv, EXT_VRM_STEPSIZE_MV) // Deal with crital attributes that are not set and that any defaults chosen // could well be very wrong FAPI_ASSERT(io_attr->attr_nest_frequency_mhz, fapi2::PSTATE_PB_NEST_FREQ_EQ_ZERO() .set_CHIP_TARGET(i_target), "ATTR_FREQ_PB_MHZ has a zero value"); fapi_try_exit: return fapi2::current_err; } /// END OF GET ATTRIBUTES function /// START OF MVPD DATA FUNCTION fapi2::ReturnCode proc_get_mvpd_data(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint32_t o_attr_mvpd_data[PV_D][PV_W], uint32_t* o_valid_pdv_points, uint8_t* o_present_chiplets, uint8_t& o_bucketId, fapi2::voltageBucketData_t* o_poundv_data, PSTATE_attribute_state* o_state) { std::vector<fapi2::Target<fapi2::TARGET_TYPE_EQ>> l_eqChiplets; fapi2::voltageBucketData_t l_poundv_data; fapi2::Target<fapi2::TARGET_TYPE_EQ> l_firstEqChiplet; uint8_t* l_buffer = reinterpret_cast<uint8_t*>(malloc(sizeof(l_poundv_data)) ); uint8_t* l_buffer_inc; uint32_t chiplet_mvpd_data[PV_D][PV_W]; uint8_t j = 0; uint8_t i = 0; uint8_t ii = 0; uint8_t first_chplt = 1; uint8_t bucket_id = 0; do { // initialize FAPI_TRY(proc_get_attributes(i_target, &attr), "proc_get_mvpd_data: Get attributes function failed"); *o_present_chiplets = 0; // ----------------------------------------------------------------- // get list of quad chiplets and loop over each and get #V data from each // ----------------------------------------------------------------- // check that frequency is the same per chiplet // for voltage, get the max for use for the chip l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ>(fapi2::TARGET_STATE_FUNCTIONAL); *o_present_chiplets = l_eqChiplets.size(); FAPI_INF("Number of EQ chiplets present => %u", *o_present_chiplets); for (j = 0; j < l_eqChiplets.size(); j++) { uint8_t l_chipNum = 0xFF; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_eqChiplets[j], l_chipNum)); FAPI_INF("Chip Number => %u", l_chipNum); // clear out buffer to known value before calling fapiGetMvpdField memset(l_buffer, 0, sizeof(o_poundv_data)); FAPI_TRY(p9_pm_get_poundv_bucket(l_eqChiplets[j], l_poundv_data)); memcpy(l_buffer, &l_poundv_data, sizeof(l_poundv_data)); memcpy(o_poundv_data, &l_poundv_data, sizeof(l_poundv_data)); // clear array memset(chiplet_mvpd_data, 0, sizeof(chiplet_mvpd_data)); // fill chiplet_mvpd_data 2d array with data iN buffer (skip first byte - bucket id) #define UINT16_GET(__uint8_ptr) ((uint16_t)( ( (*((const uint8_t *)(__uint8_ptr)) << 8) | *((const uint8_t *)(__uint8_ptr) + 1) ) )) l_buffer_inc = l_buffer; bucket_id = *l_buffer_inc; l_buffer_inc++; FAPI_INF("#V chiplet = %u bucket id = %u", l_chipNum, bucket_id); for (i = 0; i <= 4; i++) { for (ii = 0; ii <= 4; ii++) { chiplet_mvpd_data[i][ii] = (uint32_t) UINT16_GET(l_buffer_inc); FAPI_INF("#V data = 0x%04X %-6d", chiplet_mvpd_data[i][ii], chiplet_mvpd_data[i][ii]); // increment to next MVPD value in buffer l_buffer_inc += 2; } } FAPI_TRY(proc_chk_valid_poundv( i_target, chiplet_mvpd_data, o_valid_pdv_points, l_chipNum, bucket_id, o_state)); // on first chiplet put each bucket's data into attr_mvpd_voltage_control if (first_chplt) { l_firstEqChiplet = l_eqChiplets[j]; o_bucketId = bucket_id; for (i = 0; i <= 4; i++) { for (ii = 0; ii <= 4; ii++) { o_attr_mvpd_data[i][ii] = chiplet_mvpd_data[i][ii]; } } first_chplt = 0; } else { // on subsequent chiplets, check that frequencies are same for each operating point for each chiplet if ( (o_attr_mvpd_data[0][0] != chiplet_mvpd_data[0][0]) || (o_attr_mvpd_data[1][0] != chiplet_mvpd_data[1][0]) || (o_attr_mvpd_data[2][0] != chiplet_mvpd_data[2][0]) || (o_attr_mvpd_data[3][0] != chiplet_mvpd_data[3][0]) || (o_attr_mvpd_data[4][0] != chiplet_mvpd_data[4][0]) ) { o_state->iv_pstates_enabled = false; // Error out has Pstate and all dependent functions are suspious. FAPI_ASSERT(false, fapi2::PSTATE_MVPD_CHIPLET_VOLTAGE_NOT_EQUAL() .set_CHIP_TARGET(i_target) .set_CURRENT_EQ_CHIPLET_TARGET(l_eqChiplets[j]) .set_FIRST_EQ_CHIPLET_TARGET(l_firstEqChiplet) .set_BUCKET(bucket_id), "frequencies are not the same for each operating point for each chiplet"); } } // check each bucket for max voltage and if max, put bucket's data into attr_mvpd_voltage_control for (i = 0; i <= 4; i++) { if (o_attr_mvpd_data[i][1] < chiplet_mvpd_data[i][1]) { o_attr_mvpd_data[i][0] = chiplet_mvpd_data[i][0]; o_attr_mvpd_data[i][1] = chiplet_mvpd_data[i][1]; o_attr_mvpd_data[i][2] = chiplet_mvpd_data[i][2]; o_attr_mvpd_data[i][3] = chiplet_mvpd_data[i][3]; o_attr_mvpd_data[i][4] = chiplet_mvpd_data[i][4]; o_bucketId = bucket_id; } } } // end for loop } while(0); fapi_try_exit: if (fapi2::current_err != fapi2::FAPI2_RC_SUCCESS) { o_state->iv_pstates_enabled = false; } free (l_buffer); return fapi2::current_err; } // end proc_get_mvpd_data /// END OF MVPD DATA FUNCTION /// START OF IDDQ READ FUNCTION fapi2::ReturnCode proc_get_mvpd_iddq( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, IddqTable* io_iddqt, PSTATE_attribute_state* o_state) { uint8_t* l_buffer_iq_c = reinterpret_cast<uint8_t*>(malloc(IQ_BUFFER_ALLOC)); uint32_t l_record = 0; uint32_t l_bufferSize_iq = IQ_BUFFER_ALLOC; // -------------------------------------------- // Process IQ Keyword (IDDQ) Data // -------------------------------------------- // clear out buffer to known value before calling fapiGetMvpdField memset(l_buffer_iq_c, 0, IQ_BUFFER_ALLOC); // set l_record to appropriate cprx record l_record = (uint32_t)fapi2::MVPD_RECORD_CRP0; l_bufferSize_iq = IQ_BUFFER_ALLOC; //First read is to get size of vpd record, note the o_buffer is NULL FAPI_TRY( getMvpdField((fapi2::MvpdRecord)l_record, fapi2::MVPD_KEYWORD_IQ, i_target, NULL, l_bufferSize_iq) ); //Allocate memory for vpd data l_buffer_iq_c = reinterpret_cast<uint8_t*>(malloc(l_bufferSize_iq)); // Get Chip IQ MVPD data from the CRPx records FAPI_TRY(getMvpdField((fapi2::MvpdRecord)l_record, fapi2::MVPD_KEYWORD_IQ, i_target, l_buffer_iq_c, l_bufferSize_iq)); //copy VPD data to IQ structure table memcpy(io_iddqt, l_buffer_iq_c, l_bufferSize_iq); //Verify Payload header data. if ( !(io_iddqt->iddq_version) || !(io_iddqt->good_quads_per_sort) || !(io_iddqt->good_normal_cores_per_sort) || !(io_iddqt->good_caches_per_sort)) { o_state->iv_wof_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_IQ_VPD_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_VERSION(io_iddqt->iddq_version) .set_GOOD_QUADS_PER_SORT(io_iddqt->good_quads_per_sort) .set_GOOD_NORMAL_CORES_PER_SORT(io_iddqt->good_normal_cores_per_sort) .set_GOOD_CACHES_PER_SORT(io_iddqt->good_caches_per_sort), "Pstate Parameter Block IQ Payload data error being logged"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } //Verify ivdd_all_cores_off_caches_off has MSB bit is set //if yes then initialized to 0 for (int i = 0; i < IDDQ_MEASUREMENTS; ++i) { if ( io_iddqt->ivdd_all_cores_off_caches_off[i] & 0x8000) { io_iddqt->ivdd_all_cores_off_caches_off[i] = 0; } } // Put out the structure to the trace iddq_print(io_iddqt); fapi_try_exit: // Free up memory buffer free(l_buffer_iq_c); if (fapi2::current_err != fapi2::FAPI2_RC_SUCCESS) { o_state->iv_wof_enabled = false; } return fapi2::current_err; } // proc_get_mvdp_iddq /// END OF IDDQ READ FUNCTION /// START OF BIAS APPLICATION FUNCTION // Bias multiplier helper function // NOTE: BIAS_PCT_UNIT is a multipler on the percentage that the value represents double calc_bias(const int8_t i_value) { double temp = 1.0 + ((BIAS_PCT_UNIT/100) * (double)i_value); FAPI_DBG(" calc_bias: input bias (in 1/2 percent) = %d; percent = %4.1f%% biased multiplier = %6.3f", i_value, (i_value*BIAS_PCT_UNIT), temp); return temp; } fapi2::ReturnCode proc_get_extint_bias( uint32_t io_attr_mvpd_data[PV_D][PV_W], const AttributeList* i_attr, VpdBias o_vpdbias[NUM_OP_POINTS] ) { double freq_bias[NUM_OP_POINTS]; double voltage_ext_vdd_bias[NUM_OP_POINTS]; double voltage_ext_vcs_bias; double voltage_ext_vdn_bias; // Calculate the frequency multiplers and load the biases into the exported // structure for (auto p = 0; p < NUM_OP_POINTS; p++) { switch (p) { case POWERSAVE: o_vpdbias[p].frequency_hp = i_attr->attr_freq_bias_powersave; o_vpdbias[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_powersave; o_vpdbias[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_powersave; break; case NOMINAL: o_vpdbias[p].frequency_hp = i_attr->attr_freq_bias_nominal; o_vpdbias[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_nominal; o_vpdbias[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_nominal; break; case TURBO: o_vpdbias[p].frequency_hp = i_attr->attr_freq_bias_turbo; o_vpdbias[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_turbo; o_vpdbias[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_turbo; break; case ULTRA: o_vpdbias[p].frequency_hp = i_attr->attr_freq_bias_ultraturbo; o_vpdbias[p].vdd_ext_hp = i_attr->attr_voltage_ext_vdd_bias_ultraturbo; o_vpdbias[p].vdd_int_hp = i_attr->attr_voltage_int_vdd_bias_ultraturbo; } o_vpdbias[p].vdn_ext_hp = i_attr->attr_voltage_ext_vdn_bias; o_vpdbias[p].vcs_ext_hp = i_attr->attr_voltage_ext_vcs_bias; freq_bias[p] = calc_bias(o_vpdbias[p].frequency_hp); voltage_ext_vdd_bias[p] = calc_bias(o_vpdbias[p].vdd_ext_hp); FAPI_DBG(" Biases[%d](bias): Freq=%f (%f%%); VDD=%f (%f%%)", p, freq_bias[p], o_vpdbias[p].frequency_hp/2, voltage_ext_vdd_bias[p], o_vpdbias[p].vdd_ext_hp/2); } // VCS bias applied to all operating points voltage_ext_vcs_bias = calc_bias(i_attr->attr_voltage_ext_vcs_bias); // VDN bias applied to all operating points voltage_ext_vdn_bias = calc_bias(i_attr->attr_voltage_ext_vdn_bias); // Change the VPD frequency, VDD and VCS values with the bias multiplers for (auto p = 0; p < NUM_OP_POINTS; p++) { FAPI_DBG(" Orig values[%d](bias): Freq=%d (%f); VDD=%d (%f), VCS=%d (%f)", p, io_attr_mvpd_data[p][VPD_PV_CORE_FREQ_MHZ], freq_bias[p], io_attr_mvpd_data[p][VPD_PV_VDD_MV], voltage_ext_vdd_bias[p], io_attr_mvpd_data[p][VPD_PV_VCS_MV], voltage_ext_vcs_bias); double freq_mhz = (( (double)io_attr_mvpd_data[p][VPD_PV_CORE_FREQ_MHZ]) * freq_bias[p]); double vdd_mv = (( (double)io_attr_mvpd_data[p][VPD_PV_VDD_MV]) * voltage_ext_vdd_bias[p]); double vcs_mv = (( (double)io_attr_mvpd_data[p][VPD_PV_VCS_MV]) * voltage_ext_vcs_bias); io_attr_mvpd_data[p][VPD_PV_CORE_FREQ_MHZ] = (uint32_t)internal_floor(freq_mhz); io_attr_mvpd_data[p][VPD_PV_VDD_MV] = (uint32_t)internal_ceil(vdd_mv); io_attr_mvpd_data[p][VPD_PV_VCS_MV] = (uint32_t)(vcs_mv); FAPI_DBG(" Biased values[%d]: Freq=%f %d; VDD=%f %d, VCS=%f %d ", p, freq_mhz, io_attr_mvpd_data[p][VPD_PV_CORE_FREQ_MHZ], vdd_mv, io_attr_mvpd_data[p][VPD_PV_VDD_MV], vcs_mv, io_attr_mvpd_data[p][VPD_PV_VCS_MV]); } // Power bus operating point double vdn_mv = (( (double)io_attr_mvpd_data[VPD_PV_POWERBUS][VPD_PV_VDN_MV]) * voltage_ext_vdn_bias); io_attr_mvpd_data[VPD_PV_POWERBUS][VPD_PV_VDN_MV] = (uint32_t)internal_ceil(vdn_mv); return fapi2::FAPI2_RC_SUCCESS; } // end proc_get_extint_bias /// END OF BIAS APPLICATION FUNCTION fapi2::ReturnCode proc_chk_valid_poundv(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint32_t i_chiplet_mvpd_data[PV_D][PV_W], uint32_t* o_valid_pdv_points, const uint8_t i_chiplet_num, const uint8_t i_bucket_id, PSTATE_attribute_state* o_state, const bool i_biased_state) { const uint8_t pv_op_order[NUM_OP_POINTS] = VPD_PV_ORDER; const char* pv_op_str[NUM_OP_POINTS] = VPD_PV_ORDER_STR; uint8_t i = 0; bool suspend_ut_check = false; FAPI_DBG(">> proc_chk_valid_poundv for %s values", (i_biased_state) ? "biased" : "non-biased" ); const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_SYSTEM_POUNDV_VALIDITY_HALT_DISABLE_Type attr_poundv_validity_halt_disable; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_POUNDV_VALIDITY_HALT_DISABLE, FAPI_SYSTEM, attr_poundv_validity_halt_disable)); fapi2::ATTR_CHIP_EC_FEATURE_POUNDV_VALIDATE_DISABLE_Type attr_poundv_validate_ec_disable; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_POUNDV_VALIDATE_DISABLE, i_target, attr_poundv_validate_ec_disable)); if (attr_poundv_validate_ec_disable) { o_state->iv_pstates_enabled = false; FAPI_INF("**** WARNING : #V zero value checking is not being performed on this chip EC level"); FAPI_INF("**** WARNING : Pstates are not enabled"); } else { // check for non-zero freq, voltage, or current in valid operating points for (i = 0; i <= NUM_OP_POINTS - 1; i++) { FAPI_INF("Checking for Zero valued %s data in each #V operating point (%s) f=%u v=%u i=%u v=%u i=%u", (i_biased_state) ? "biased" : "non-biased", pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][0], i_chiplet_mvpd_data[pv_op_order[i]][1], i_chiplet_mvpd_data[pv_op_order[i]][2], i_chiplet_mvpd_data[pv_op_order[i]][3], i_chiplet_mvpd_data[pv_op_order[i]][4]); if (is_wof_enabled(i_target,o_state) && (strcmp(pv_op_str[pv_op_order[i]], "UltraTurbo") == 0)) { if (i_chiplet_mvpd_data[pv_op_order[i]][0] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][1] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][2] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][3] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][4] == 0 ) { FAPI_INF("**** WARNING: WOF is enabled but zero valued data found in #V (chiplet = %u bucket id = %u op point = %s)", i_chiplet_num, i_bucket_id, pv_op_str[pv_op_order[i]]); FAPI_INF("**** WARNING: Disabling WOF and continuing"); suspend_ut_check = true; // Set ATTR_WOF_ENABLED so the caller can set header flags o_state->iv_wof_enabled = false; // Take out an informational error log and then keep going. if (i_biased_state) { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_BIASED_POUNDV_WOF_UT_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block WOF Biased #V UT error being logged"); } else { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUNDV_WOF_UT_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block WOF #V UT error being logged"); } fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } } else if ((!is_wof_enabled(i_target,o_state)) && (strcmp(pv_op_str[pv_op_order[i]], "UltraTurbo") == 0)) { FAPI_INF("**** NOTE: WOF is disabled so the UltraTurbo VPD is not being checked"); suspend_ut_check = true; } else { if (i_chiplet_mvpd_data[pv_op_order[i]][0] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][1] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][2] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][3] == 0 || i_chiplet_mvpd_data[pv_op_order[i]][4] == 0 ) { o_state->iv_pstates_enabled = false; if (attr_poundv_validity_halt_disable) { FAPI_IMP("**** WARNING : halt on #V validity checking has been disabled and errors were found"); FAPI_IMP("**** WARNING : Zero valued data found in #V (chiplet = %u bucket id = %u op point = %s)", i_chiplet_num, i_bucket_id, pv_op_str[pv_op_order[i]]); FAPI_IMP("**** WARNING : Pstates are not enabled but continuing on."); // Log errors based on biased inputs or not if (i_biased_state) { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_BIASED_POUNDV_ZERO_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block Biased #V Zero contents error being logged"); } else { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUNDV_ZERO_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block #V Zero contents error being logged"); } fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } else { FAPI_ERR("**** ERROR : Zero valued data found in #V (chiplet = %u bucket id = %u op point = %s)", i_chiplet_num, i_bucket_id, pv_op_str[pv_op_order[i]]); // Error out has Pstate and all dependent functions are suspious. if (i_biased_state) { FAPI_ASSERT(false, fapi2::PSTATE_PB_BIASED_POUNDV_ZERO_ERROR() .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block Biased #V Zero contents error being logged"); } else { FAPI_ASSERT(false, fapi2::PSTATE_PB_POUNDV_ZERO_ERROR() .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block #V Zero contents error being logged"); } } // Halt disable } // #V point zero check } // WOF and UT conditions } // Operating poing loop } // validate #V EC // Adjust the valid operating point based on UltraTurbo presence // and WOF enablement *o_valid_pdv_points = NUM_OP_POINTS; if (suspend_ut_check) { (*o_valid_pdv_points)--; } FAPI_DBG("o_valid_pdv_points = %d", *o_valid_pdv_points); #define POUNDV_SLOPE_CHECK(x,y) x > y ? " is GREATER (ERROR!) than " : " is less than " if (attr_poundv_validate_ec_disable) { o_state->iv_pstates_enabled = false; FAPI_INF("**** WARNING : #V relationship checking is not being performed on this chip EC level"); FAPI_INF("**** WARNING : Pstates are not enabled"); } else { // check valid operating points' values have this relationship (power save <= nominal <= turbo <= ultraturbo) for (i = 1; i <= (*o_valid_pdv_points) - 1; i++) { FAPI_INF("Checking for relationship between #V operating point (%s <= %s)", pv_op_str[pv_op_order[i - 1]], pv_op_str[pv_op_order[i]]); // Only skip checkinug for WOF not enabled and UltraTurbo. if ( is_wof_enabled(i_target,o_state) || (!( !is_wof_enabled(i_target,o_state) && (strcmp(pv_op_str[pv_op_order[i]], "UltraTurbo") == 0))) ) { if (i_chiplet_mvpd_data[pv_op_order[i - 1]][0] > i_chiplet_mvpd_data[pv_op_order[i]][0] || i_chiplet_mvpd_data[pv_op_order[i - 1]][1] > i_chiplet_mvpd_data[pv_op_order[i]][1] || i_chiplet_mvpd_data[pv_op_order[i - 1]][2] > i_chiplet_mvpd_data[pv_op_order[i]][2] || i_chiplet_mvpd_data[pv_op_order[i - 1]][3] > i_chiplet_mvpd_data[pv_op_order[i]][3] || i_chiplet_mvpd_data[pv_op_order[i - 1]][4] > i_chiplet_mvpd_data[pv_op_order[i]][4] ) { o_state->iv_pstates_enabled = false; if (attr_poundv_validity_halt_disable) { FAPI_IMP("**** WARNING : halt on #V validity checking has been disabled and relationship errors were found"); FAPI_IMP("**** WARNING : Relationship error between #V operating point (%s > %s)(power save <= nominal <= turbo <= ultraturbo) (chiplet = %u bucket id = %u op point = %u)", pv_op_str[pv_op_order[i - 1]], pv_op_str[pv_op_order[i]], i_chiplet_num, i_bucket_id, pv_op_order[i]); FAPI_IMP("**** WARNING : Pstates are not enabled but continuing on."); } else { FAPI_ERR("**** ERROR : Relation../../xml/attribute_info/pm_plat_attributes.xmlship error between #V operating point (%s > %s)(power save <= nominal <= turbo <= ultraturbo) (chiplet = %u bucket id = %u op point = %u)", pv_op_str[pv_op_order[i - 1]], pv_op_str[pv_op_order[i]], i_chiplet_num, i_bucket_id, pv_op_order[i]); } FAPI_INF("%s Frequency value %u is %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][0], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][0], i_chiplet_mvpd_data[pv_op_order[i]][0]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][0]); FAPI_INF("%s VDD voltage value %u is %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][1], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][1], i_chiplet_mvpd_data[pv_op_order[i]][1]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][1]); FAPI_INF("%s VDD current value %u is %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][2], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][2], i_chiplet_mvpd_data[pv_op_order[i]][2]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][2]); FAPI_INF("%s VCS voltage value %u is %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][3], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][3], i_chiplet_mvpd_data[pv_op_order[i]][3]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][3]); FAPI_INF("%s VCS current value %u i../../xml/attribute_info/pm_plat_attributes.xmls %s %s Frequency value %u", pv_op_str[pv_op_order[i - 1]], i_chiplet_mvpd_data[pv_op_order[i - 1]][4], POUNDV_SLOPE_CHECK(i_chiplet_mvpd_data[pv_op_order[i - 1]][4], i_chiplet_mvpd_data[pv_op_order[i]][4]), pv_op_str[pv_op_order[i]], i_chiplet_mvpd_data[pv_op_order[i]][4]); if (i_biased_state) { if (attr_poundv_validity_halt_disable) { // Log the error only. FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_BIASED_POUNDV_SLOPE_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][0]) .set_VDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][1]) .set_IDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][2]) .set_VCS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][3]) .set_ICS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][4]) .set_FREQUENCY_B(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD_B(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD_B(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS_B(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS_B(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block Biased #V disorder contents error being logged"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } else { // Error out has Pstate and all dependent functions are suspious. FAPI_ASSERT(false, fapi2::PSTATE_PB_BIASED_POUNDV_SLOPE_ERROR() .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][0]) .set_VDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][1]) .set_IDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][2]) .set_VCS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][3]) .set_ICS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][4]) .set_FREQUENCY_B(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD_B(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD_B(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS_B(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS_B(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block Biased #V disorder contents error being logged"); } } else { if (attr_poundv_validity_halt_disable) { // Log the error only. FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUNDV_SLOPE_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][0]) .set_VDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][1]) .set_IDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][2]) .set_VCS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][3]) .set_ICS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][4]) .set_FREQUENCY_B(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD_B(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD_B(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS_B(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS_B(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block #V disorder contents error being logged"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } else { // Error out has Pstate and all dependent functions are suspious. FAPI_ASSERT(false, fapi2::PSTATE_PB_POUNDV_SLOPE_ERROR() .set_CHIP_TARGET(i_target) .set_CHIPLET_NUMBER(i_chiplet_num) .set_BUCKET(i_bucket_id) .set_POINT(i) .set_FREQUENCY_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][0]) .set_VDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][1]) .set_IDD_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][2]) .set_VCS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][3]) .set_ICS_A(i_chiplet_mvpd_data[pv_op_order[i - 1]][4]) .set_FREQUENCY_B(i_chiplet_mvpd_data[pv_op_order[i]][0]) .set_VDD_B(i_chiplet_mvpd_data[pv_op_order[i]][1]) .set_IDD_B(i_chiplet_mvpd_data[pv_op_order[i]][2]) .set_VCS_B(i_chiplet_mvpd_data[pv_op_order[i]][3]) .set_ICS_B(i_chiplet_mvpd_data[pv_op_order[i]][4]), "Pstate Parameter Block #V disorder contents error being logged"); } } } // validity failed } // Skip UT check } // point loop } // validity disabled fapi_try_exit: FAPI_DBG("<< proc_chk_valid_poundv"); return fapi2::current_err; } /// ------------------------------------------------------------ /// \brief Copy VPD operating point into destination in assending order /// \param[in] &src[NUM_OP_POINTS] => reference to source VPD structure (array) /// \param[out] *dest[NUM_OP_POINTS] => pointer to destination VpdOperatingPoint structure // \param[in] i_frequency_step_khz => Base frequency value for pstate calculation /// ------------------------------------------------------------ /// \note: this routine reads the keyword information in "VPD order" (eg Nominal, /// PowerSave, Turbo, UltraTurbo) into the data structures in "Natural Order" /// (eg (eg PowerSave, Nominal, Turbo, UltraTurbo) /// fapi2::ReturnCode load_mvpd_operating_point ( const uint32_t i_src[PV_D][PV_W], VpdOperatingPoint* o_dest, uint32_t i_frequency_step_khz) { FAPI_DBG(">> load_mvpd_operating_point"); const uint8_t pv_op_order[NUM_OP_POINTS] = VPD_PV_ORDER; for (uint32_t i = 0; i < NUM_OP_POINTS; i++) { o_dest[i].frequency_mhz = revle32(i_src[pv_op_order[i]][0]); o_dest[i].vdd_mv = revle32(i_src[pv_op_order[i]][1]); o_dest[i].idd_100ma = revle32(i_src[pv_op_order[i]][2]); o_dest[i].vcs_mv = revle32(i_src[pv_op_order[i]][3]); o_dest[i].ics_100ma = revle32(i_src[pv_op_order[i]][4]); o_dest[i].pstate = (i_src[ULTRA][0] - i_src[pv_op_order[i]][0]) * 1000 / i_frequency_step_khz; } FAPI_DBG("<< load_mvpd_operating_point"); return fapi2::FAPI2_RC_SUCCESS; } // end load_mvpd_operating_point /// ------------------------------------------------------------ /// @brief Copy out of operating point set into a destination operating point /// @param[in] &i_op_pt_set => reference to array of VpdOperatingPoint sets /// @param[out] *dest[NUM_OP_POINTS] => pointer to destination VpdOperatingPoint structure /// @param[in] i_frequency_step_khz => Base frequency value for pstate calculation /// ------------------------------------------------------------ fapi2::ReturnCode get_operating_point ( const VpdOperatingPoint i_op_pt_set[NUM_VPD_PTS_SET][NUM_OP_POINTS], uint32_t i_set, VpdOperatingPoint* o_op_pt) { FAPI_DBG(">> get_operating_point"); for (uint32_t i = 0; i < NUM_OP_POINTS; i++) { o_op_pt[i].frequency_mhz = i_op_pt_set[i_set][i].frequency_mhz; o_op_pt[i].vdd_mv = i_op_pt_set[i_set][i].vdd_mv; o_op_pt[i].idd_100ma = i_op_pt_set[i_set][i].idd_100ma; o_op_pt[i].vcs_mv = i_op_pt_set[i_set][i].vcs_mv; o_op_pt[i].ics_100ma = i_op_pt_set[i_set][i].ics_100ma; o_op_pt[i].pstate = i_op_pt_set[i_set][i].pstate; } FAPI_DBG("<< get_operating_point"); return fapi2::FAPI2_RC_SUCCESS; } // end load_mvpd_operating_point fapi2::ReturnCode proc_get_vdm_parms (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const AttributeList* i_attr, GP_VDMParmBlock* o_vdmpb) { FAPI_DBG(">> proc_get_vdm_parms"); if (i_attr->attr_system_vdm_disable == fapi2::ENUM_ATTR_SYSTEM_VDM_DISABLE_OFF) { const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_DROOP_SMALL_OVERRIDE, FAPI_SYSTEM, o_vdmpb->droop_small_override)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_DROOP_LARGE_OVERRIDE, FAPI_SYSTEM, o_vdmpb->droop_large_override)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_DROOP_EXTREME_OVERRIDE, FAPI_SYSTEM, o_vdmpb->droop_extreme_override)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_OVERVOLT_OVERRIDE, FAPI_SYSTEM, o_vdmpb->overvolt_override)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_FMIN_OVERRIDE_KHZ, FAPI_SYSTEM, o_vdmpb->fmin_override_khz)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_FMAX_OVERRIDE_KHZ, FAPI_SYSTEM, o_vdmpb->fmax_override_khz)); FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_VDM_VID_COMPARE_OVERRIDE_MV, FAPI_SYSTEM, o_vdmpb->vid_compare_override_mv)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DPLL_VDM_RESPONSE, FAPI_SYSTEM, o_vdmpb->vdm_response)); } else { FAPI_DBG(" VDM is disabled. Skipping VDM attribute accesses"); } fapi_try_exit: FAPI_DBG("<< proc_get_vdm_parms"); return fapi2::current_err; } fapi2::ReturnCode proc_res_clock_setup ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, ResonantClockingSetup* o_resclk_setup, const GlobalPstateParmBlock* i_gppb) { FAPI_DBG(">> proc_res_clock_setup"); uint8_t l_resclk_freq_index[RESCLK_FREQ_REGIONS]; uint16_t l_step_delay_ns; uint16_t l_l3_threshold_mv; uint16_t l_steparray[RESCLK_STEPS]; uint16_t l_resclk_freq_regions[RESCLK_FREQ_REGIONS]; uint32_t l_ultra_turbo_freq_khz = revle32(i_gppb->reference_frequency_khz); const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_SYSTEM_RESCLK_STEP_DELAY, FAPI_SYSTEM, l_step_delay_ns)); o_resclk_setup->step_delay_ns = revle16(l_step_delay_ns); // Resonant Clocking Frequency and Index arrays FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGIONS, i_target, l_resclk_freq_regions)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGION_INDEX, i_target, l_resclk_freq_index)); // Convert frequencies to pstates for (uint8_t i = 0; i < RESCLK_FREQ_REGIONS; ++i) { Pstate pstate; // Frequencies are given in MHz, convert to KHz uint32_t freq_khz = static_cast<uint32_t>(l_resclk_freq_regions[i]) * 1000; uint8_t idx = l_resclk_freq_index[i]; // Frequencies need to be capped at Ultra-Turbo, frequencies less-than // the Minimum can be ignored (because this table is walked from // end-begin, and the frequencies are stored in ascending order, // the "walk" will never pass the minimum frequency). if (freq_khz > l_ultra_turbo_freq_khz) { freq_khz = l_ultra_turbo_freq_khz; // Need to walk the table backwards to find the index for this frequency for (uint8_t j = i; j >= 0; --j) { if (freq_khz >= (l_resclk_freq_regions[j] * 1000)) { idx = l_resclk_freq_index[j]; break; } } } int rc = freq2pState(i_gppb, freq_khz, &pstate); switch (rc) { case -PSTATE_LT_PSTATE_MIN: FAPI_INF("Resonant clock frequency %d KHz was clipped to Pstate 0", freq_khz); break; case -PSTATE_GT_PSTATE_MAX: FAPI_INF("Resonant clock Frequency %d KHz is outside the range that can be represented" " by a Pstate with a base frequency of %d KHz and step size %d KHz", freq_khz, l_ultra_turbo_freq_khz, revle32(i_gppb->frequency_step_khz)); FAPI_INF("Pstate is set to %X (%d)", pstate); break; } o_resclk_setup->resclk_freq[i] = pstate; o_resclk_setup->resclk_index[i] = idx; FAPI_DBG("Resclk: freq = %d kHz; pstate = %d; idx = %d", freq_khz, pstate, idx); } FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_L3_VALUE, i_target, o_resclk_setup->l3_steparray)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_L3_VOLTAGE_THRESHOLD_MV, i_target, l_l3_threshold_mv)); o_resclk_setup->l3_threshold_mv = revle16(l_l3_threshold_mv); // Resonant Clocking Step array FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_VALUE, i_target, l_steparray)); for (uint8_t i = 0; i < RESCLK_STEPS; i++) { o_resclk_setup->steparray[i].value = revle16(l_steparray[i]); } fapi_try_exit: FAPI_DBG("<< proc_res_clock_setup"); return fapi2::current_err; } fapi2::ReturnCode proc_get_ivrm_parms ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const AttributeList* i_attr, IvrmParmBlock* o_ivrmpb, PSTATE_attribute_state* o_state) { FAPI_DBG(">> proc_get_ivrm_parms"); if (i_attr->attr_system_ivrm_disable == fapi2::ENUM_ATTR_SYSTEM_IVRM_DISABLE_OFF) { const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF(">> proc_get_ivrm_parms"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_STRENGTH_LOOKUP, FAPI_SYSTEM, o_ivrmpb->strength_lookup)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_VIN_MULTIPLIER, FAPI_SYSTEM, o_ivrmpb->vin_multiplier)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_VIN_MAX_MV, FAPI_SYSTEM, o_ivrmpb->vin_max_mv)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_STEP_DELAY_NS, FAPI_SYSTEM, o_ivrmpb->step_delay_ns)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_STABILIZATION_DELAY_NS, FAPI_SYSTEM, o_ivrmpb->stablization_delay_ns)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IVRM_DEADZONE_MV, FAPI_SYSTEM, o_ivrmpb->deadzone_mv)); // This is presently hardcoded to FALSE until validation code is in // place to ensure turning IVRM on is a good thing. This attribute write is // needed to allocate the HWP attribute in Cronus. // Indicate that IVRM is good to be enabled (or not) FAPI_INF(" NOTE: This level of code is forcing the iVRM to OFF"); { fapi2::ATTR_IVRM_ENABLED_Type l_ivrm_enabled = (fapi2::ATTR_IVRM_ENABLED_Type)fapi2::ENUM_ATTR_IVRM_ENABLED_FALSE; FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_IVRM_ENABLED, i_target, l_ivrm_enabled)); } } else { FAPI_DBG(" IVRM is disabled. Skipping IVRM attribute accesses"); o_state->iv_ivrm_enabled = false; } fapi_try_exit: FAPI_DBG("<< proc_get_ivrm_parms"); return fapi2::current_err; } // Apply system parameters to a VPD value uint32_t sysparm_uplift(const uint32_t i_vpd_mv, const uint32_t i_vpd_ma, const uint32_t i_loadline_uohm, const uint32_t i_distloss_uohm, const uint32_t i_distoffset_uohm) { double l_mv = ((double)i_vpd_mv + // mV ( // mA*uOhm/1000 -> uV ((double)(i_vpd_ma * (i_loadline_uohm + i_distloss_uohm)) / 1000 + // uv (double)i_distoffset_uohm) ) / 1000); // uV -> mV uint32_t l_result = (uint32_t)l_mv; FAPI_DBG(" system_uplift_mv: i_vpd_mv=%d; i_vpd_ma=%d; i_loadline_uohm=%d " "i_distloss_uohm = %d i_distoffset_uohm = %d l_mv = %5.3f l_result = %d" , i_vpd_mv, i_vpd_ma, i_loadline_uohm, i_distloss_uohm, i_distoffset_uohm, l_mv, l_result); return revle32(l_result); } // Bias Adjust a voltage data value using a 1/2 percent bias amount. Value // is always taken to the higher integer value. uint32_t bias_adjust_mv(const uint32_t i_value, const int32_t i_bias_0p5pct) { double l_mult = calc_bias(i_bias_0p5pct); double l_biased_value = (double)i_value * l_mult; double l_ceiling = internal_ceil(l_biased_value); uint32_t l_result = (uint32_t)l_ceiling; FAPI_DBG(" bias_adjust_mv: i_value=%d; mult=%5.3f; biased value=%3.0f ceiling = %3.0f result = %d", i_value, l_mult, l_biased_value, l_ceiling, l_result); return revle32(l_result); } // Bias Adjust a frequency data value using a 1/2 percent bias amount. Value // is always taken to the lower integer value. uint32_t bias_adjust_mhz(const uint32_t i_value, const int32_t i_bias_0p5pct) { double l_mult = calc_bias(i_bias_0p5pct); double l_biased_value = (double)i_value * l_mult; FAPI_DBG(" bias_adjust_mhz: i_value=%d; mult=%5.3f; biased value=%3.0f", i_value, l_mult, l_biased_value); return revle32((uint32_t)internal_floor(l_biased_value)); } // // p9_pstate_compute_vpd_pts // void p9_pstate_compute_vpd_pts(VpdOperatingPoint (*o_operating_points)[NUM_OP_POINTS], GlobalPstateParmBlock* i_gppb, VpdOperatingPoint* i_raw_vpd_pts) { int p = 0; uint32_t l_vdd_loadline_uohm = revle32(i_gppb->vdd_sysparm.loadline_uohm); uint32_t l_vdd_distloss_uohm = revle32(i_gppb->vdd_sysparm.distloss_uohm); uint32_t l_vdd_distoffset_uv = revle32(i_gppb->vdd_sysparm.distoffset_uv); uint32_t l_vcs_loadline_uohm = revle32(i_gppb->vcs_sysparm.loadline_uohm); uint32_t l_vcs_distloss_uohm = revle32(i_gppb->vcs_sysparm.distloss_uohm); uint32_t l_vcs_distoffset_uv = revle32(i_gppb->vcs_sysparm.distoffset_uv); //RAW POINTS. We just copy them as is for (p = 0; p < NUM_OP_POINTS; p++) { o_operating_points[VPD_PT_SET_RAW][p].vdd_mv = i_raw_vpd_pts[p].vdd_mv; o_operating_points[VPD_PT_SET_RAW][p].vcs_mv = i_raw_vpd_pts[p].vcs_mv; o_operating_points[VPD_PT_SET_RAW][p].idd_100ma = i_raw_vpd_pts[p].idd_100ma; o_operating_points[VPD_PT_SET_RAW][p].ics_100ma = i_raw_vpd_pts[p].ics_100ma; o_operating_points[VPD_PT_SET_RAW][p].frequency_mhz = i_raw_vpd_pts[p].frequency_mhz; o_operating_points[VPD_PT_SET_RAW][p].pstate = i_raw_vpd_pts[p].pstate; FAPI_DBG("GP: OpPoint=[%d][%d], PS=%3d, Freq=%3X (%4d), Vdd=%3X (%4d)", VPD_PT_SET_RAW, p, o_operating_points[VPD_PT_SET_RAW][p].pstate, revle32(o_operating_points[VPD_PT_SET_RAW][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_RAW][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_RAW][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_RAW][p].vdd_mv)); } //SYSTEM PARAMS APPLIED POINTS for (p = 0; p < NUM_OP_POINTS; p++) { uint32_t l_vdd_mv = revle32(i_gppb->operating_points[p].vdd_mv); uint32_t l_idd_ma = revle32(i_gppb->operating_points[p].idd_100ma * 100); uint32_t l_vcs_mv = revle32(i_gppb->operating_points[p].vcs_mv); uint32_t l_ics_ma = revle32(i_gppb->operating_points[p].ics_100ma * 100); o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv = sysparm_uplift(l_vdd_mv, l_idd_ma, l_vdd_loadline_uohm, l_vdd_distloss_uohm, l_vdd_distoffset_uv); o_operating_points[VPD_PT_SET_SYSP][p].vcs_mv = sysparm_uplift(l_vcs_mv, l_ics_ma, l_vcs_loadline_uohm, l_vcs_distloss_uohm, l_vcs_distoffset_uv); o_operating_points[VPD_PT_SET_SYSP][p].idd_100ma = i_gppb->operating_points[p].idd_100ma; o_operating_points[VPD_PT_SET_SYSP][p].ics_100ma = i_gppb->operating_points[p].ics_100ma; o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz = i_gppb->operating_points[p].frequency_mhz; o_operating_points[VPD_PT_SET_SYSP][p].pstate = i_gppb->operating_points[p].pstate; FAPI_DBG("SP: OpPoint=[%d][%d], PS=%3d, Freq=%3X (%4d), Vdd=%3X (%4d)", VPD_PT_SET_RAW, p, o_operating_points[VPD_PT_SET_SYSP][p].pstate, revle32(o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv)); } //BIASED POINTS for (p = 0; p < NUM_OP_POINTS; p++) { uint32_t l_frequency_mhz = revle32(i_gppb->operating_points[p].frequency_mhz); uint32_t l_vdd_mv = revle32(i_gppb->operating_points[p].vdd_mv); uint32_t l_vcs_mv = revle32(i_gppb->operating_points[p].vcs_mv); o_operating_points[VPD_PT_SET_BIASED][p].vdd_mv = bias_adjust_mv(l_vdd_mv, i_gppb->ext_biases[p].vdd_ext_hp); o_operating_points[VPD_PT_SET_BIASED][p].vcs_mv = bias_adjust_mv(l_vcs_mv, i_gppb->ext_biases[p].vcs_ext_hp); o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz = bias_adjust_mhz(l_frequency_mhz, i_gppb->ext_biases[p].frequency_hp); o_operating_points[VPD_PT_SET_BIASED][p].idd_100ma = i_gppb->operating_points[p].idd_100ma; o_operating_points[VPD_PT_SET_BIASED][p].ics_100ma = i_gppb->operating_points[p].ics_100ma; } // As this is memory to memory, Endianess correction is not necessary. uint32_t l_ref_freq_khz = revle32(o_operating_points[VPD_PT_SET_BIASED][ULTRA].frequency_mhz) * 1000; i_gppb->reference_frequency_khz = revle32(l_ref_freq_khz); FAPI_DBG("Reference into GPPB: LE local Freq=%X (%d); Freq=%X (%d)", l_ref_freq_khz, l_ref_freq_khz, revle32(i_gppb->reference_frequency_khz), revle32(i_gppb->reference_frequency_khz)); // Now that the ULTRA frequency is known, Pstates can be calculated for (p = 0; p < NUM_OP_POINTS; p++) { o_operating_points[VPD_PT_SET_BIASED][p].pstate = (((revle32(o_operating_points[VPD_PT_SET_BIASED][ULTRA].frequency_mhz) - revle32(o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz)) * 1000) / revle32(i_gppb->frequency_step_khz)); FAPI_DBG("Bi: OpPoint=[%d][%d], PS=%3d, Freq=%3X (%4d), Vdd=%3X (%4d), UT Freq=%3X (%4d) Step Freq=%5d", VPD_PT_SET_BIASED, p, o_operating_points[VPD_PT_SET_BIASED][p].pstate, revle32(o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_BIASED][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_BIASED][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_BIASED][ULTRA].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_BIASED][ULTRA].frequency_mhz), revle32(i_gppb->frequency_step_khz)); } //BIASED POINTS and SYSTEM PARMS APPLIED POINTS for (p = 0; p < NUM_OP_POINTS; p++) { uint32_t l_vdd_mv = revle32(o_operating_points[VPD_PT_SET_BIASED][p].vdd_mv); uint32_t l_idd_ma = revle32(o_operating_points[VPD_PT_SET_BIASED][p].idd_100ma) * 100; uint32_t l_vcs_mv = revle32(o_operating_points[VPD_PT_SET_BIASED][p].vcs_mv); uint32_t l_ics_ma = revle32(o_operating_points[VPD_PT_SET_BIASED][p].ics_100ma) * 100; o_operating_points[VPD_PT_SET_BIASED_SYSP][p].vdd_mv = sysparm_uplift(l_vdd_mv, l_idd_ma, l_vdd_loadline_uohm, l_vdd_distloss_uohm, l_vdd_distoffset_uv); o_operating_points[VPD_PT_SET_BIASED_SYSP][p].vcs_mv = sysparm_uplift(l_vcs_mv, l_ics_ma, l_vcs_loadline_uohm, l_vcs_distloss_uohm, l_vcs_distoffset_uv); o_operating_points[VPD_PT_SET_BIASED_SYSP][p].idd_100ma = o_operating_points[VPD_PT_SET_BIASED][p].idd_100ma; o_operating_points[VPD_PT_SET_BIASED_SYSP][p].ics_100ma = o_operating_points[VPD_PT_SET_BIASED][p].ics_100ma; o_operating_points[VPD_PT_SET_BIASED_SYSP][p].frequency_mhz = o_operating_points[VPD_PT_SET_BIASED][p].frequency_mhz; o_operating_points[VPD_PT_SET_BIASED_SYSP][p].pstate = o_operating_points[VPD_PT_SET_BIASED][p].pstate; FAPI_DBG("BS: OpPoint=[%d][%d], PS=%3d, Freq=%3X (%4d), Vdd=%3X (%4d)", VPD_PT_SET_BIASED_SYSP, p, o_operating_points[VPD_PT_SET_SYSP][p].pstate, revle32(o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_SYSP][p].frequency_mhz), revle32(o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv), revle32(o_operating_points[VPD_PT_SET_SYSP][p].vdd_mv)); } } // Slope of m = (y1-y0)/(x1-x0) in 4.12 Fixed-Pt format int16_t compute_slope_4_12(uint32_t y1, uint32_t y0, uint32_t x1, uint32_t x0) { return (int16_t) ( // Perform division using floats for maximum precision // Store resulting slope in 4.12 Fixed-Pt format ((float)(y1 - y0) / (float)(x1 - x0)) * (1 << VID_SLOPE_FP_SHIFT_12) ); } // Slope of m = (y1-y0)/(x1-x0) in 3.13 Fixed-Pt format int16_t compute_slope_3_13(uint32_t y1, uint32_t y0, uint32_t x1, uint32_t x0) { return (int16_t) ( // Perform division using floats for maximum precision // Store resulting slope in 3.13 Fixed-Pt format ((float)(y1 - y0) / (float)(x1 - x0)) * (1 << VID_SLOPE_FP_SHIFT) ); } // Slope of m = (y1-y0)/(x1-x0) in 4.12 Fixed-Pt format for thresholds int16_t compute_slope_thresh(int32_t y1, int32_t y0, int32_t x1, int32_t x0) { return (int16_t) ( // Perform division using double for maximum precision // Store resulting slope in 4.12 Fixed-Pt format ((double)(y1 - y0) / (double)(x1 - x0)) * (1 << THRESH_SLOPE_FP_SHIFT) ); } // // p9_pstate_compute_PsV_slopes // // Computes slope of voltage-PState curve and PState-voltage // // PState(Frequency) on y-axis, Voltage is on x-axis for VF curve // Interpolation formula: (y-y0)/(x-x0) = (y1-y0)/(x1-x0) // m = (x1-x0)/(y1-y0), then use this to calculate voltage, x = (y-y0)*m + x0 // 1/m = (y1-y0)/(x1-x0) here, then use this to calculate pstate(frequency), y = (x-x0)*m + y0 // Region 0 is b/w POWERSAVE and NOMINAL // Region 1 is b/w NOMINAL and TURBO // Region 2 is between TURBO and ULTRA_TURBO // // Inflection Point 3 is ULTRA_TURBO // Inflection Point 2 is TURBO // Inflection Point 1 is NOMINAL // Inflection Point 0 is POWERSAVE // //\todo: Remove this. RTC: 174743 void p9_pstate_compute_PsV_slopes(VpdOperatingPoint i_operating_points[][4], GlobalPstateParmBlock* o_gppb) { for(auto pt_set = 0; pt_set < VPD_NUM_SLOPES_SET; ++pt_set) { FAPI_DBG("PsVSlopes pt_set %d", pt_set); // ULTRA TURBO pstate check is not required because its pstate will be 0 if (!(i_operating_points[pt_set][POWERSAVE].pstate) || !(i_operating_points[pt_set][NOMINAL].pstate) || !(i_operating_points[pt_set][TURBO].pstate)) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero for %s (%d)", vpdSetStr[pt_set], pt_set); break; } //Calculate slopes for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { // Pstate value decreases with increasing region. Thus the values // are swapped to result in a positive difference. o_gppb->PsVSlopes[pt_set][region] = revle16( compute_slope_3_13(revle32(i_operating_points[pt_set][region + 1].vdd_mv), revle32(i_operating_points[pt_set][region].vdd_mv), i_operating_points[pt_set][region].pstate, i_operating_points[pt_set][region + 1].pstate) ); FAPI_DBG("PsVSlopes[%s][%s] 0x%04x %d", vpdSetStr[pt_set], region_names[region], revle16(o_gppb->PsVSlopes[pt_set][region]), revle16(o_gppb->PsVSlopes[pt_set][region])); } //Calculate inverted slopes for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { // Pstate value decreases with increasing region. Thus the values // are swapped to result in a positive difference. o_gppb->VPsSlopes[pt_set][region] = revle16( compute_slope_3_13(i_operating_points[pt_set][region].pstate, i_operating_points[pt_set][region + 1].pstate, revle32(i_operating_points[pt_set][region + 1].vdd_mv), revle32(i_operating_points[pt_set][region].vdd_mv)) ); FAPI_DBG("VPsSlopes[%s][%s] 0x%04x %d", vpdSetStr[pt_set], region_names[region], revle16(o_gppb->VPsSlopes[pt_set][region]), revle16(o_gppb->VPsSlopes[pt_set][region])); } } } //This fills up the PStateVSlopes and VPStatesSlopes in GlobalParmBlock //Going forward this method should be retained in favor of the p9_pstate_compute_PsVSlopes void p9_pstate_compute_PStateV_slope(VpdOperatingPoint i_operating_points[][4], GlobalPstateParmBlock* o_gppb) { for(auto pt_set = 0; pt_set < NUM_VPD_PTS_SET; ++pt_set) { // ULTRA TURBO pstate check is not required..because it's pstate will be // 0 if (!(i_operating_points[pt_set][POWERSAVE].pstate) || !(i_operating_points[pt_set][NOMINAL].pstate) || !(i_operating_points[pt_set][TURBO].pstate)) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero for %s", vpdSetStr[pt_set]); return; } //Calculate slopes for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { // Pstate value decreases with increasing region. Thus the values // are swapped to result in a positive difference. o_gppb->PStateVSlopes[pt_set][region] = revle16( compute_slope_4_12(revle32(i_operating_points[pt_set][region + 1].vdd_mv), revle32(i_operating_points[pt_set][region].vdd_mv), i_operating_points[pt_set][region].pstate, i_operating_points[pt_set][region + 1].pstate) ); FAPI_DBG("PStateVSlopes[%s][%s] 0x%04x %d", vpdSetStr[pt_set], region_names[region], revle16(o_gppb->PStateVSlopes[pt_set][region]), revle16(o_gppb->PStateVSlopes[pt_set][region])); } //Calculate inverted slopes for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { // Pstate value decreases with increasing region. Thus the values // are swapped to result in a positive difference. o_gppb->VPStateSlopes[pt_set][region] = revle16( compute_slope_4_12(i_operating_points[pt_set][region].pstate, i_operating_points[pt_set][region + 1].pstate, revle32(i_operating_points[pt_set][region + 1].vdd_mv), revle32(i_operating_points[pt_set][region].vdd_mv)) ); FAPI_DBG("VPStateSlopes[%s][%s] 0x%04x %d", vpdSetStr[pt_set], region_names[region], revle16(o_gppb->VPStateSlopes[pt_set][region]), revle16(o_gppb->VPStateSlopes[pt_set][region])); } } } #define CENTER_STR(_buffer, _variable, _width) \ { \ int _w_ = _width-strlen(_variable)/2; \ sprintf(_buffer, " %*s%*s ", _w_, _variable, _w_, ""); \ } #define HEX_DEC_STR(_buffer, _hex, _dec) \ { \ char _temp_buffer[64]; \ sprintf(_temp_buffer, " %04X (%4d) ", _dec, _hex); \ strcat(_buffer, _temp_buffer); \ } /// Print a GlobalPstateParameterBlock structure on a given stream /// /// \param gppb The Global Pstate Parameter Block print void gppb_print(GlobalPstateParmBlock* i_gppb) { static const uint32_t BUFFSIZE = 256; char l_buffer[BUFFSIZE]; char l_temp_buffer[BUFFSIZE]; char l_temp_buffer1[BUFFSIZE]; const char* pv_op_str[NUM_OP_POINTS] = PV_OP_ORDER_STR; const char* thresh_op_str[NUM_THRESHOLD_POINTS] = VPD_THRESHOLD_ORDER_STR; const char* slope_region_str[VPD_NUM_SLOPES_REGION] = VPD_OP_SLOPES_REGION_ORDER_STR; // Put out the endian-corrected scalars FAPI_INF("---------------------------------------------------------------------------------------"); FAPI_INF("Global Pstate Parameter Block @ %p", i_gppb); FAPI_INF("---------------------------------------------------------------------------------------"); FAPI_INF("%-20s : %X", "Options", revle32(i_gppb->options.options)); FAPI_INF("%-20s : %X (%d)", "Reference Frequency", revle32(i_gppb->reference_frequency_khz), revle32(i_gppb->reference_frequency_khz)); FAPI_INF("%-20s : %X (%d)", "Frequency Step Size", revle32(i_gppb->frequency_step_khz), revle32(i_gppb->frequency_step_khz)); FAPI_INF("Operating Points: Frequency VDD(mV) IDD(100mA) VCS(mV) ICS(100mA)"); for (uint32_t i = 0; i < NUM_OP_POINTS; i++) { strcpy(l_buffer,""); sprintf (l_temp_buffer, " %-18s : ",pv_op_str[i]); strcat(l_buffer, l_temp_buffer); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].frequency_mhz), revle32(i_gppb->operating_points[i].frequency_mhz)); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].vdd_mv), revle32(i_gppb->operating_points[i].vdd_mv)); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].idd_100ma), revle32(i_gppb->operating_points[i].idd_100ma)); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].vcs_mv), revle32(i_gppb->operating_points[i].vcs_mv)); HEX_DEC_STR(l_buffer, revle32(i_gppb->operating_points[i].ics_100ma), revle32(i_gppb->operating_points[i].ics_100ma)); FAPI_INF("%s", l_buffer); } FAPI_INF("System Parameters: VDD VCS VDN") strcpy(l_buffer,""); sprintf(l_temp_buffer, " %-30s :", "Load line (uOhm)"); strcat(l_buffer, l_temp_buffer); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdd_sysparm.loadline_uohm), revle32(i_gppb->vdd_sysparm.loadline_uohm)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vcs_sysparm.loadline_uohm), revle32(i_gppb->vcs_sysparm.loadline_uohm)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdn_sysparm.loadline_uohm), revle32(i_gppb->vdn_sysparm.loadline_uohm)); FAPI_INF("%s", l_buffer); strcpy(l_buffer,""); sprintf(l_temp_buffer, " %-30s :", "Distribution Loss (uOhm)"); strcat(l_buffer, l_temp_buffer); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdd_sysparm.distloss_uohm), revle32(i_gppb->vdd_sysparm.distloss_uohm)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vcs_sysparm.distloss_uohm), revle32(i_gppb->vcs_sysparm.distloss_uohm)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdn_sysparm.distloss_uohm), revle32(i_gppb->vdn_sysparm.distloss_uohm)); FAPI_INF("%s", l_buffer); strcpy(l_buffer,""); sprintf(l_temp_buffer, " %-30s :", "Offset (uV)"); strcat(l_buffer, l_temp_buffer); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdd_sysparm.distoffset_uv), revle32(i_gppb->vdd_sysparm.distoffset_uv)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vcs_sysparm.distoffset_uv), revle32(i_gppb->vcs_sysparm.distoffset_uv)); HEX_DEC_STR(l_buffer, revle32(i_gppb->vdn_sysparm.distoffset_uv), revle32(i_gppb->vdn_sysparm.distoffset_uv)); FAPI_INF("%s", l_buffer); FAPI_INF("Safe Parameters:"); FAPI_INF(" %-30s : %04X (%3d) ", "Frequency", revle32(i_gppb->safe_frequency_khz), revle32(i_gppb->safe_frequency_khz)); FAPI_INF(" %-30s : %04X (%3d) ", "Voltage", revle32(i_gppb->safe_voltage_mv), revle32(i_gppb->safe_voltage_mv)); FAPI_INF("Pstate Stepping Parameters:"); FAPI_INF(" %-30s : %04X (%3d) ", "Delay range exponent", revle32(i_gppb->vrm_stepdelay_range), revle32(i_gppb->vrm_stepdelay_range)); FAPI_INF(" %-30s : %04X (%3d) ", "Significand", revle32(i_gppb->vrm_stepdelay_value), revle32(i_gppb->vrm_stepdelay_value)); FAPI_INF("External VRM Parameters:"); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Transition Start", revle32(i_gppb->ext_vrm_transition_start_ns), revle32(i_gppb->ext_vrm_transition_start_ns)); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Transition Rate - Rising", revle32(i_gppb->ext_vrm_transition_rate_inc_uv_per_us), revle32(i_gppb->ext_vrm_transition_rate_inc_uv_per_us)); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Transition Rate - Falling", revle32(i_gppb->ext_vrm_transition_rate_dec_uv_per_us), revle32(i_gppb->ext_vrm_transition_rate_dec_uv_per_us)); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Settling Time (us)", revle32(i_gppb->ext_vrm_transition_rate_dec_uv_per_us), revle32(i_gppb->ext_vrm_transition_rate_dec_uv_per_us)); FAPI_INF(" %-30s : %04X (%3d) ", "VRM Transition Step Size (mV)", revle32(i_gppb->ext_vrm_step_size_mv), revle32(i_gppb->ext_vrm_step_size_mv)); FAPI_INF(" %-30s : %04X (%3d) ", "Nest Frequency", revle32(i_gppb->nest_frequency_mhz), revle32(i_gppb->nest_frequency_mhz)); // 2 Slope sets sprintf(l_buffer, "PsVSlopes:"); sprintf( l_temp_buffer, "%9s", ""); strcat(l_buffer, l_temp_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, " %s ", prt_region_names[j]); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < VPD_NUM_SLOPES_SET; ++i) { sprintf(l_buffer, " %-16s : ", vpdSetStr[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, "%6s%04X%7s ", " ",revle16(i_gppb->PsVSlopes[i][j])," "); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "VPsSlopes:"); sprintf( l_temp_buffer, "%9s", ""); strcat(l_buffer, l_temp_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, " %s ", prt_region_names[j]); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < VPD_NUM_SLOPES_SET; ++i) { sprintf(l_buffer, " %-16s : ", vpdSetStr[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, "%6s%04X%7s ", " ",revle16(i_gppb->VPsSlopes[i][j])," "); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } // 4 Slope sets sprintf(l_buffer, "PstateVSlopes:"); sprintf( l_temp_buffer, "%5s", ""); strcat(l_buffer, l_temp_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, " %s ", prt_region_names[j]); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < NUM_VPD_PTS_SET; ++i) { sprintf(l_buffer, " %-16s : ", vpdSetStr[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, "%6s%04X%7s ", " ",revle16(i_gppb->PStateVSlopes[i][j])," "); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "VPstateSlopes:"); sprintf( l_temp_buffer, "%5s", ""); strcat(l_buffer, l_temp_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, " %s ", prt_region_names[j]); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < NUM_VPD_PTS_SET; ++i) { sprintf(l_buffer, " %-16s : ", vpdSetStr[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer, "%6s%04X%7s ", " ",revle16(i_gppb->VPStateSlopes[i][j])," "); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } FAPI_INF ("VID Operating Points"); for (auto i = 0; i < NUM_OP_POINTS; ++i) { sprintf (l_buffer, " %-16s : %02X ",pv_op_str[i], i_gppb->vid_point_set[i]); FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "%-25s", "Thrshod Op Points: "); for (auto j = 0; j < NUM_THRESHOLD_POINTS; ++j) { CENTER_STR(l_temp_buffer, thresh_op_str[j], 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); strcpy(l_buffer,""); for (auto i = 0; i < NUM_OP_POINTS; ++i) { sprintf(l_buffer, " %-16s : ", pv_op_str[i]); for (auto j = 0; j < NUM_THRESHOLD_POINTS; ++j) { sprintf(l_temp_buffer1, "%04X", i_gppb->threshold_set[i][j]); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "VID Compare Slopes:"); int l_len = strlen(l_buffer); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer1, "%s", prt_region_names[j]); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); sprintf( l_buffer, "%*s", l_len+6," "); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer1, "%04X", revle16(i_gppb->PsVIDCompSlopes[j])); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); sprintf(l_buffer, "%-18s", "VDM Thrshld Slopes:"); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { CENTER_STR(l_temp_buffer, slope_region_str[j], 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < NUM_THRESHOLD_POINTS; ++i) { sprintf(l_buffer, " %-16s : ", thresh_op_str[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer1, " %3i ", i_gppb->PsVDMThreshSlopes[i][j]); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } sprintf(l_buffer, "%-18s", "VDM Jump Slopes: "); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { CENTER_STR(l_temp_buffer, slope_region_str[j], 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); for (auto i = 0; i < NUM_THRESHOLD_POINTS; ++i) { sprintf(l_buffer, " %-16s : ", thresh_op_str[i]); for (auto j = 0; j < VPD_NUM_SLOPES_REGION; ++j) { sprintf(l_temp_buffer1, " %02X ", i_gppb->PsVDMJumpSlopes[i][j]); CENTER_STR(l_temp_buffer, l_temp_buffer1, 8); strcat(l_buffer, l_temp_buffer); } FAPI_INF("%s", l_buffer); } // // // // FAPI_INF ("VDM THRESHOLD SLOPES"); // // for (uint8_t i = 0; i < VPD_NUM_SLOPES_REGION; ++i) // { // strcpy(l_buffer,""); // sprintf (l_temp_buffer, " %s ",slope_region_str[i]); // FAPI_INF("%s", l_temp_buffer); // for (uint8_t j = 0; j < NUM_THRESHOLD_POINTS; ++j) // { // sprintf (l_temp_buffer, " %s : %02X ",thresh_op_str[j], i_gppb->PsVDMThreshSlopes[i][j]); // strcat (l_buffer, l_temp_buffer); // } // FAPI_INF("%s", l_buffer); // } // // FAPI_INF ("VDM JUMP SLOPES"); // // for (uint8_t i = 0; i < VPD_NUM_SLOPES_REGION; ++i) // { // strcpy(l_buffer,""); // sprintf (l_temp_buffer, " %s ",slope_region_str[i]); // FAPI_INF("%s", l_temp_buffer); // for (uint8_t j = 0; j < NUM_JUMP_VALUES; ++j) // { // sprintf (l_temp_buffer, " %s : %02X ",thresh_op_str[j], i_gppb->PsVDMJumpSlopes[i][j]); // strcat (l_buffer, l_temp_buffer); // } // FAPI_INF("%s", l_buffer); // } // Resonant Clocking FAPI_DBG("Resonant Clocking Setup:"); FAPI_DBG("Pstates ResClk Index"); for (auto i = 0; i < RESCLK_FREQ_REGIONS; ++i) { FAPI_DBG(" %03d %02d", i_gppb->resclk.resclk_freq[i], i_gppb->resclk.resclk_index[i]); } FAPI_INF("---------------------------------------------------------------------------------------"); } /// Print an OCCPstateParameterBlock structure on a given stream /// /// \param oppb The OCC Pstate Parameter Block print void oppb_print(OCCPstateParmBlock* i_oppb) { static const uint32_t BUFFSIZE = 256; char l_buffer[BUFFSIZE]; char l_temp_buffer[BUFFSIZE]; // Put out the endian-corrected scalars FAPI_INF("---------------------------------------------------------------------------------------"); FAPI_INF("OCC Pstate Parameter Block @ %p", i_oppb); FAPI_INF("---------------------------------------------------------------------------------------"); // fprintf(stream, "Magic: %llu\n", revle64(i_oppb->magic)); FAPI_INF("Operating Points: Frequency VDD(mV) IDD(100mA) VCS(mV) ICS(100mA)"); for (auto i = 0; i < NUM_OP_POINTS; i++) { sprintf(l_buffer, " "); sprintf(l_temp_buffer, " %04X (%4d) ", revle32(i_oppb->operating_points[i].frequency_mhz), revle32(i_oppb->operating_points[i].frequency_mhz)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%4d) ", revle32(i_oppb->operating_points[i].vdd_mv), revle32(i_oppb->operating_points[i].vdd_mv)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%4d) ", revle32(i_oppb->operating_points[i].idd_100ma), revle32(i_oppb->operating_points[i].idd_100ma)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%4d) ", revle32(i_oppb->operating_points[i].vcs_mv), revle32(i_oppb->operating_points[i].vcs_mv)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->operating_points[i].ics_100ma), revle32(i_oppb->operating_points[i].ics_100ma)); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); } FAPI_INF("System Parameters: VDD VCS VDN"); sprintf(l_buffer, " Load line (uOhm) "); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdd_sysparm.loadline_uohm), revle32(i_oppb->vdd_sysparm.loadline_uohm)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vcs_sysparm.loadline_uohm), revle32(i_oppb->vcs_sysparm.loadline_uohm)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdn_sysparm.loadline_uohm), revle32(i_oppb->vdn_sysparm.loadline_uohm)); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); sprintf(l_buffer, " Distribution Loss (uOhm) "); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdd_sysparm.distloss_uohm), revle32(i_oppb->vdd_sysparm.distloss_uohm)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vcs_sysparm.distloss_uohm), revle32(i_oppb->vcs_sysparm.distloss_uohm)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdn_sysparm.distloss_uohm), revle32(i_oppb->vdn_sysparm.distloss_uohm)); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); sprintf(l_buffer, " Offset (uV) "); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdd_sysparm.distoffset_uv), revle32(i_oppb->vdd_sysparm.distoffset_uv)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vcs_sysparm.distoffset_uv), revle32(i_oppb->vcs_sysparm.distoffset_uv)); strcat(l_buffer, l_temp_buffer); sprintf(l_temp_buffer, " %04X (%3d) ", revle32(i_oppb->vdn_sysparm.distoffset_uv), revle32(i_oppb->vdn_sysparm.distoffset_uv)); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); FAPI_INF("Frequency Minumum (kHz): %04X (%3d)", revle32(i_oppb->frequency_min_khz), revle32(i_oppb->frequency_min_khz)); FAPI_INF("Frequency Maximum (kHz): %04X (%3d)", revle32(i_oppb->frequency_max_khz), revle32(i_oppb->frequency_max_khz)); FAPI_INF("Frequency Step (kHz): %04X (%3d)", revle32(i_oppb->frequency_step_khz), revle32(i_oppb->frequency_step_khz)); FAPI_INF("Pstate of Minimum Frequency: %02X (%3d)", i_oppb->pstate_min, i_oppb->pstate_min); FAPI_INF("Nest Frequency: %02X (%3d)", i_oppb->nest_frequency_mhz, i_oppb->nest_frequency_mhz); FAPI_INF("Nest Leakage Percent: %02X (%3d)", i_oppb->nest_leakage_percent, i_oppb->nest_leakage_percent); FAPI_INF("Ceff TDP Vdn: %02X (%3d)", i_oppb->ceff_tdp_vdn, i_oppb->ceff_tdp_vdn); FAPI_INF("Iac TDP VDD Turbo(10ma): %02X (%3d)", i_oppb->lac_tdp_vdd_turbo_10ma, i_oppb->lac_tdp_vdd_turbo_10ma); FAPI_INF("Iac TDP VDD Nominal(10ma): %02X (%3d)", i_oppb->lac_tdp_vdd_nominal_10ma, i_oppb->lac_tdp_vdd_nominal_10ma); FAPI_INF("WOF Elements"); sprintf(l_buffer, " WOF Enabled "); sprintf(l_temp_buffer, " %1d ", i_oppb->wof.wof_enabled); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); sprintf(l_buffer, " TDP RDP Factor "); sprintf(l_temp_buffer, " %04X (%3d) ", i_oppb->wof.tdp_rdp_factor, i_oppb->wof.tdp_rdp_factor); strcat(l_buffer, l_temp_buffer); FAPI_INF("%s", l_buffer); // Put out the structure to the trace iddq_print(&(i_oppb->iddq)); FAPI_INF("---------------------------------------------------------------------------------------"); } /// Print an iddq_print structure on a given stream /// /// \param i_iddqt pointer to Iddq structure to output void iddq_print(IddqTable* i_iddqt) { uint32_t i, j; const char* idd_meas_str[IDDQ_MEASUREMENTS] = IDDQ_ARRAY_VOLTAGES_STR; // char l_buffer_str[256]; // Temporary formatting string buffer // char l_line_str[256]; // Formatted output line string char l_buffer_str[1024]; // Temporary formatting string buffer char l_line_str[1024]; // Formatted output line string static const uint32_t IDDQ_DESC_SIZE = 56; static const uint32_t IDDQ_QUAD_SIZE = IDDQ_DESC_SIZE - strlen("Quad X:"); FAPI_INF("IDDQ"); // Put out the endian-corrected scalars // get IQ version and advance pointer 1-byte FAPI_INF(" IDDQ Version Number = %u", i_iddqt->iddq_version); FAPI_INF(" Sort Info: Good Quads = %02d Good Cores = %02d Good Caches = %02d", i_iddqt->good_quads_per_sort, i_iddqt->good_normal_cores_per_sort, i_iddqt->good_caches_per_sort); // get number of good normal cores in each quad strcpy(l_line_str, " Good normal cores:"); strcpy(l_buffer_str, ""); for (i = 0; i < MAXIMUM_QUADS; i++) { sprintf(l_buffer_str, " Quad %d = %u ", i, i_iddqt->good_normal_cores[i]); strcat(l_line_str, l_buffer_str); } FAPI_INF("%s", l_line_str); // get number of good caches in each quad strcpy(l_line_str, " Good caches: "); strcpy(l_buffer_str, ""); for (i = 0; i < MAXIMUM_QUADS; i++) { sprintf(l_buffer_str, " Quad %d = %u ", i, i_iddqt->good_caches[i]); strcat(l_line_str, l_buffer_str); } FAPI_INF("%s", l_line_str); // get RDP TO TDP scalling factor FAPI_INF(" RDP TO TDP scalling factor = %u", revle16(i_iddqt->rdp_to_tdp_scale_factor)); // get WOF IDDQ margin factor FAPI_INF(" WOF IDDQ margin factor = %u", revle16(i_iddqt->wof_iddq_margin_factor)); // get VDD Temperature scaling factor FAPI_INF(" VDD Temperature scaling factor = %u", revle16(i_iddqt->vdd_temperature_scale_factor)); // get VDN Temperature scaling factor FAPI_INF(" VDN Temperature scaling factor = %u", revle16(i_iddqt->vdn_temperature_scale_factor)); // All IQ IDDQ measurements are at 5mA resolution. The OCC wants to // consume these at 1mA values. thus, all values are multiplied by // 5 upon installation into the paramater block. static const uint32_t CONST_5MA_1MA = 5; FAPI_INF(" IDDQ data is converted 5mA units to 1mA units"); // Put out the measurement voltages to the trace. strcpy(l_line_str, " Measurement voltages:"); sprintf(l_buffer_str, "%-*s ", IDDQ_DESC_SIZE, l_line_str); strcpy(l_line_str, l_buffer_str); strcpy(l_buffer_str, ""); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { sprintf(l_buffer_str, " %*sV ", 5, idd_meas_str[i]); strcat(l_line_str, l_buffer_str); } FAPI_INF("%s", l_line_str); #define IDDQ_CURRENT_EXTRACT(_member) \ { \ uint16_t _temp = revle16(i_iddqt->_member) * CONST_5MA_1MA; \ sprintf(l_buffer_str, " %6.3f ", (double)_temp/1000); \ strcat(l_line_str, l_buffer_str); \ } // Temps are all 1B quantities. Not endianess issues. #define IDDQ_TEMP_EXTRACT(_member) \ sprintf(l_buffer_str, " %4.1f ", ((double)i_iddqt->_member)/2); \ strcat(l_line_str, l_buffer_str); #define IDDQ_TRACE(string, size) \ strcpy(l_line_str, string); \ sprintf(l_buffer_str, "%-*s", size, l_line_str);\ strcpy(l_line_str, l_buffer_str); \ strcpy(l_buffer_str, ""); // get IVDDQ measurements with all good cores ON IDDQ_TRACE (" IDDQ all good cores ON:", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_CURRENT_EXTRACT(ivdd_all_good_cores_on_caches_on[i]); } FAPI_INF("%s", l_line_str); // get IVDDQ measurements with all cores and caches OFF IDDQ_TRACE (" IVDDQ all cores and caches OFF:", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_CURRENT_EXTRACT(ivdd_all_cores_off_caches_off[i]); } FAPI_INF("%s", l_line_str);; // get IVDDQ measurements with all good cores OFF and caches ON IDDQ_TRACE (" IVDDQ all good cores OFF and caches ON:", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_CURRENT_EXTRACT(ivdd_all_good_cores_off_good_caches_on[i]); } FAPI_INF("%s", l_line_str); // get IVDDQ measurements with all good cores in each quad for (i = 0; i < MAXIMUM_QUADS; i++) { IDDQ_TRACE (" IVDDQ all good cores ON and caches ON ", IDDQ_QUAD_SIZE); sprintf(l_buffer_str, "Quad %d:", i); strcat(l_line_str, l_buffer_str); for (j = 0; j < IDDQ_MEASUREMENTS; j++) { IDDQ_CURRENT_EXTRACT(ivdd_quad_good_cores_on_good_caches_on[i][j]); } FAPI_INF("%s", l_line_str); } // get IVDN data IDDQ_TRACE (" IVDN", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_CURRENT_EXTRACT(ivdn[i]); } FAPI_INF("%s", l_line_str); // get average temperature measurements with all good cores ON IDDQ_TRACE (" Average temp all good cores ON:",IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_TEMP_EXTRACT(avgtemp_all_good_cores_on[i]); } FAPI_INF("%s", l_line_str); // get average temperature measurements with all cores and caches OFF IDDQ_TRACE (" Average temp all cores OFF, caches OFF:", IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_TEMP_EXTRACT(avgtemp_all_cores_off_caches_off[i]); } FAPI_INF("%s", l_line_str); // get average temperature measurements with all good cores OFF and caches ON IDDQ_TRACE (" Average temp all good cores OFF, caches ON:",IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_TEMP_EXTRACT(avgtemp_all_good_cores_off[i]); } FAPI_INF("%s", l_line_str); // get average temperature measurements with all good cores in each quad for (i = 0; i < MAXIMUM_QUADS; i++) { IDDQ_TRACE (" Average temp all good cores ON, good caches ON ",IDDQ_QUAD_SIZE); sprintf(l_buffer_str, "Quad %d:", i); strcat(l_line_str, l_buffer_str); for (j = 0; j < IDDQ_MEASUREMENTS; j++) { IDDQ_TEMP_EXTRACT(avgtemp_quad_good_cores_on[i][j]); } FAPI_INF("%s", l_line_str); } // get average nest temperature nest IDDQ_TRACE (" Average temp Nest:",IDDQ_DESC_SIZE); for (i = 0; i < IDDQ_MEASUREMENTS; i++) { IDDQ_TEMP_EXTRACT(avgtemp_vdn[i]); } FAPI_INF("%s", l_line_str); } // Convert frequency to Pstate number int freq2pState (const GlobalPstateParmBlock* gppb, const uint32_t freq_khz, Pstate* pstate, const FREQ2PSTATE_ROUNDING i_round) { int rc = 0; float pstate32 = 0; // ---------------------------------- // compute pstate for given frequency // ---------------------------------- pstate32 = ((float)(revle32(gppb->reference_frequency_khz) - (float)freq_khz)) / (float)revle32(gppb->frequency_step_khz); // @todo Bug fix from Characterization team to deal with VPD not being // exactly in step increments // - not yet included to separate changes // As higher Pstate numbers represent lower frequencies, the pstate must be // snapped to the nearest *higher* integer value for safety. (e.g. slower // frequencies are safer). if ((i_round == ROUND_SLOW) && (freq_khz)) { *pstate = (Pstate)internal_ceil(pstate32); FAPI_DBG("freq2pState: ROUND SLOW"); } else { *pstate = (Pstate)pstate32; FAPI_DBG("freq2pState: ROUND FAST"); } FAPI_DBG("freq2pState: freq_khz = %u (0x%X); pstate32 = %f; pstate = %u (0x%X)", freq_khz, freq_khz, pstate32, *pstate, *pstate); FAPI_DBG("freq2pState: ref_freq_khz = %u (0x%X); step_freq_khz= %u (0x%X)", revle32(gppb->reference_frequency_khz), revle32(gppb->reference_frequency_khz), revle32(gppb->frequency_step_khz), revle32(gppb->frequency_step_khz)); // ------------------------------ // perform pstate bounds checking // ------------------------------ if (pstate32 < PSTATE_MIN) { rc = -PSTATE_LT_PSTATE_MIN; *pstate = PSTATE_MIN; } if (pstate32 > PSTATE_MAX) { rc = -PSTATE_GT_PSTATE_MAX; *pstate = PSTATE_MAX; } return rc; } // Convert Pstate number to frequency int pState2freq (const GlobalPstateParmBlock* gppb, const Pstate i_pstate, uint32_t* o_freq_khz) { int rc = 0; float pstate32 = i_pstate; float l_freq_khz = 0; // ---------------------------------- // compute frequency from a pstate // ---------------------------------- l_freq_khz = ((float)(revle32(gppb->reference_frequency_khz)) - (pstate32 * (float)revle32(gppb->frequency_step_khz))); *o_freq_khz = (uint32_t)l_freq_khz; return rc; } fapi2::ReturnCode proc_get_mvpd_poundw(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t i_poundv_bucketId, LP_VDMParmBlock* o_vdmpb, PoundW_data* o_data, fapi2::voltageBucketData_t i_poundv_data, PSTATE_attribute_state* o_state) { std::vector<fapi2::Target<fapi2::TARGET_TYPE_EQ>> l_eqChiplets; fapi2::vdmData_t l_vdmBuf; uint8_t j = 0; uint8_t bucket_id = 0; uint8_t version_id = 0; const uint16_t VDM_VOLTAGE_IN_MV = 512; const uint16_t VDM_GRANULARITY = 4; const char* pv_op_str[NUM_OP_POINTS] = PV_OP_ORDER_STR; FAPI_DBG(">> proc_get_mvpd_poundw"); do { FAPI_DBG("proc_get_mvpd_poundw: VDM enable = %d, WOF enable %d", is_vdm_enabled(i_target,o_state), is_wof_enabled(i_target,o_state)); // Exit if both VDM and WOF is disabled if ((!is_vdm_enabled(i_target,o_state) && !is_wof_enabled(i_target,o_state))) { FAPI_INF(" proc_get_mvpd_poundw: BOTH VDM and WOF are disabled. Skipping remaining checks"); o_state->iv_vdm_enabled = false; o_state->iv_wof_enabled = false; break; } // Below fields for Nominal, Powersave, Turbo, Ultra Turbo // I-VDD Nominal TDP AC current 2B // I-VDD Nominal TDP DC current 2B // Overvolt Threshold 0.5 Upper nibble of byte // Small Threshold 0.5 Lower nibble of byte // Large Threshold 0.5 Upper nibble of byte // eXtreme Threshold 0.5 Lower nibble of byte // Small Frequency Drop 1B // Large Frequency Drop 1B // ----------------------------------------------------------------- l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ>(fapi2::TARGET_STATE_FUNCTIONAL); for (j = 0; j < l_eqChiplets.size(); j++) { uint8_t l_chipNum = 0xFF; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_eqChiplets[j], l_chipNum)); FAPI_INF("Chip Number => %u", l_chipNum); // clear out buffer to known value before calling fapiGetMvpdField memset(&l_vdmBuf, 0, sizeof(l_vdmBuf)); FAPI_TRY(p9_pm_get_poundw_bucket(l_eqChiplets[j], l_vdmBuf)); bucket_id = l_vdmBuf.bucketId; version_id = l_vdmBuf.version; FAPI_INF("#W chiplet = %u bucket id = %u", l_chipNum, bucket_id, version_id); //if we match with the bucket id, then we don't need to continue if (i_poundv_bucketId == bucket_id) { break; } } uint8_t l_poundw_static_data = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUND_W_STATIC_DATA_ENABLE, FAPI_SYSTEM, l_poundw_static_data), "Error from FAPI_ATTR_GET for attribute ATTR_POUND_W_STATIC_DATA_ENABLE"); if (l_poundw_static_data) { FAPI_INF("attribute ATTR_POUND_W_STATIC_DATA_ENABLE is set"); // copy the data to the pound w structure from a hardcoded table memcpy (o_data, &g_vpdData, sizeof (g_vpdData)); } else { FAPI_INF("attribute ATTR_POUND_W_STATIC_DATA_ENABLE is NOT set"); // copy the data to the pound w structure from the actual VPD image memcpy (o_data, l_vdmBuf.vdmData, sizeof (l_vdmBuf.vdmData)); } //Re-ordering to Natural order // When we read the data from VPD image the order will be N,PS,T,UT. // But we need the order PS,N,T,UT.. hence we are swapping the data // between PS and Nominal. poundw_entry_t l_tmp_data; memcpy (&l_tmp_data, &(o_data->poundw[VPD_PV_NOMINAL]), sizeof (poundw_entry_t)); memcpy (&(o_data->poundw[VPD_PV_NOMINAL]), &(o_data->poundw[VPD_PV_POWERSAVE]), sizeof(poundw_entry_t)); memcpy (&(o_data->poundw[VPD_PV_POWERSAVE]), &l_tmp_data, sizeof(poundw_entry_t)); // If the #W version is less than 3, validate Turbo VDM large threshold // not larger than -32mV. This filters out parts that have bad VPD. If // this check fails, log a recovered error, mark the VDMs disabled and // break out of the reset of the checks. uint32_t turbo_vdm_large_threshhold = (o_data->poundw[TURBO].vdm_large_extreme_thresholds >> 4) & 0x0F; FAPI_DBG("o_data->poundw[TURBO].vdm_large_thresholds 0x%X; grey code index %d; max grey code index %d", turbo_vdm_large_threshhold, g_GreyCodeIndexMapping[turbo_vdm_large_threshhold], GREYCODE_INDEX_M32MV); if (version_id < FULLY_VALID_POUNDW_VERSION && g_GreyCodeIndexMapping[turbo_vdm_large_threshhold] > GREYCODE_INDEX_M32MV) { o_state->iv_vdm_enabled = false; fapi2::ATTR_CHIP_EC_FEATURE_VDM_POUNDW_SUPPRESS_ERROR_Type l_suppress_pdw_error; FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_VDM_POUNDW_SUPPRESS_ERROR, i_target, l_suppress_pdw_error); if (l_suppress_pdw_error) { FAPI_INF("VDM #W ERROR: Turbo Large Threshold less than -32mV. Indicates bad VPD so VDMs being disabled and pressing on"); } else { FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_VERY_INVALID_VDM_DATA(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_TURBO_LARGE_THRESHOLD(o_data->poundw[TURBO].vdm_large_extreme_thresholds), "VDM #W ERROR: Turbo Large Threshold less than -32mV. Indicates bad VPD so VDMs being disabled and pressing on"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } break; } // Validate the WOF content is non-zero if WOF is enabled if (is_wof_enabled(i_target,o_state)) { bool b_tdp_ac = true; bool b_tdp_dc = true; // Check that the WOF currents are non-zero for (auto p = 0; p < NUM_OP_POINTS; ++p) { FAPI_INF("%s ivdd_tdp_ac_current %5d (10mA) %6.2f (A)", pv_op_str[p], revle16(o_data->poundw[p].ivdd_tdp_ac_current_10ma), ((double)revle16(o_data->poundw[p].ivdd_tdp_ac_current_10ma)/100)); FAPI_INF("%s ivdd_tdp_dc_current %5d (10mA) %6.2f (A)", pv_op_str[p], revle16(o_data->poundw[p].ivdd_tdp_dc_current_10ma), ((double)revle16(o_data->poundw[p].ivdd_tdp_dc_current_10ma)/100)); if (!o_data->poundw[p].ivdd_tdp_ac_current_10ma) { FAPI_ERR("%s.ivdd_tdp_ac_current_10ma is zero!!!", pv_op_str[p]); b_tdp_ac = false; o_state->iv_wof_enabled = false; } if (!o_data->poundw[p].ivdd_tdp_dc_current_10ma) { FAPI_ERR("%s.ivdd_tdp_dc_current_10ma is zero!!!", pv_op_str[p]); b_tdp_dc = false; o_state->iv_wof_enabled = false; } } FAPI_ASSERT_NOEXIT(b_tdp_ac, fapi2::PSTATE_PB_POUND_W_TDP_IAC_INVALID(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_NOMINAL_TDP_IAC(o_data->poundw[NOMINAL].ivdd_tdp_dc_current_10ma) .set_POWERSAVE_TDP_IAC(o_data->poundw[POWERSAVE].ivdd_tdp_dc_current_10ma) .set_TURBO_TDP_IAC(o_data->poundw[TURBO].ivdd_tdp_dc_current_10ma) .set_ULTRA_TDP_IAC(o_data->poundw[ULTRA].ivdd_tdp_dc_current_10ma), "Pstate Parameter Block #W : one or more Idd TDP AC values are zero"); FAPI_ASSERT_NOEXIT(b_tdp_dc, fapi2::PSTATE_PB_POUND_W_TDP_IDC_INVALID(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_NOMINAL_TDP_IDC(o_data->poundw[NOMINAL].ivdd_tdp_dc_current_10ma) .set_POWERSAVE_TDP_IDC(o_data->poundw[POWERSAVE].ivdd_tdp_dc_current_10ma) .set_TURBO_TDP_IDC(o_data->poundw[TURBO].ivdd_tdp_dc_current_10ma) .set_ULTRA_TDP_IDC(o_data->poundw[ULTRA].ivdd_tdp_dc_current_10ma), "o_dataPstate Parameter Block #W : one or more Idd TDP DC values are zero"); // Set the return code to success to keep going. fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; } // The rest of the processing here is all checking of the VDM content // within #W. If VDMs are not enabled (or supported), skip all of it if (!is_vdm_enabled(i_target,o_state)) { FAPI_INF(" proc_get_mvpd_poundw: VDM is disabled. Skipping remaining checks"); o_state->iv_vdm_enabled = false; break; } for (int i = 0; i < NUM_OP_POINTS; ++i) { uint32_t l_mv = 512 + (o_data->poundw[i].vdm_vid_compare_ivid << 2); FAPI_INF("%10s vdm_vid_compare_ivid %3d => %d mv", pv_op_str[i], o_data->poundw[i].vdm_vid_compare_ivid, l_mv); } //Validation of VPD Data // //If all VID compares are zero then use #V VDD voltage to populate local //data structure..So that we make progress in lab with early hardware if ( !(o_data->poundw[NOMINAL].vdm_vid_compare_ivid) && !(o_data->poundw[POWERSAVE].vdm_vid_compare_ivid) && !(o_data->poundw[TURBO].vdm_vid_compare_ivid) && !(o_data->poundw[ULTRA].vdm_vid_compare_ivid)) { //vdm_vid_compare_ivid will be in ivid units (eg HEX((Compare //Voltage (mv) - 512mV)/4mV). o_data->poundw[NOMINAL].vdm_vid_compare_ivid = (i_poundv_data.VddNomVltg - VDM_VOLTAGE_IN_MV ) / VDM_GRANULARITY; o_data->poundw[POWERSAVE].vdm_vid_compare_ivid = (i_poundv_data.VddPSVltg - VDM_VOLTAGE_IN_MV ) / VDM_GRANULARITY; o_data->poundw[TURBO].vdm_vid_compare_ivid = (i_poundv_data.VddTurboVltg - VDM_VOLTAGE_IN_MV ) / VDM_GRANULARITY; o_data->poundw[ULTRA].vdm_vid_compare_ivid = (i_poundv_data.VddUTurboVltg - VDM_VOLTAGE_IN_MV ) / VDM_GRANULARITY; }//if any one of the VID compares are zero, then need to fail because of BAD VPD image. else if ( !(o_data->poundw[NOMINAL].vdm_vid_compare_ivid) || !(o_data->poundw[POWERSAVE].vdm_vid_compare_ivid) || !(o_data->poundw[TURBO].vdm_vid_compare_ivid) || !(o_data->poundw[ULTRA].vdm_vid_compare_ivid)) { o_state->iv_vdm_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_INVALID_VID_VALUE(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_NOMINAL_VID_COMPARE_IVID_VALUE(o_data->poundw[NOMINAL].vdm_vid_compare_ivid) .set_POWERSAVE_VID_COMPARE_IVID_VALUE(o_data->poundw[POWERSAVE].vdm_vid_compare_ivid) .set_TURBO_VID_COMPARE_IVID_VALUE(o_data->poundw[TURBO].vdm_vid_compare_ivid) .set_ULTRA_VID_COMPARE_IVID_VALUE(o_data->poundw[ULTRA].vdm_vid_compare_ivid), "Pstate Parameter Block #W : one of the VID compare value is zero"); break; } // validate vid values bool l_compare_vid_value_state = 1; VALIDATE_VID_VALUES (o_data->poundw[POWERSAVE].vdm_vid_compare_ivid, o_data->poundw[NOMINAL].vdm_vid_compare_ivid, o_data->poundw[TURBO].vdm_vid_compare_ivid, o_data->poundw[ULTRA].vdm_vid_compare_ivid, l_compare_vid_value_state); if (!l_compare_vid_value_state) { o_state->iv_vdm_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_INVALID_VID_ORDER(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_NOMINAL_VID_COMPARE_IVID_VALUE(o_data->poundw[NOMINAL].vdm_vid_compare_ivid) .set_POWERSAVE_VID_COMPARE_IVID_VALUE(o_data->poundw[POWERSAVE].vdm_vid_compare_ivid) .set_TURBO_VID_COMPARE_IVID_VALUE(o_data->poundw[TURBO].vdm_vid_compare_ivid) .set_ULTRA_VID_COMPARE_IVID_VALUE(o_data->poundw[ULTRA].vdm_vid_compare_ivid), "Pstate Parameter Block #W VID compare data are not in increasing order"); break; } // validate threshold values bool l_threshold_value_state = 1; for (uint8_t p = 0; p < NUM_OP_POINTS; ++p) { FAPI_INF("o_data->poundw[%d].vdm_overvolt_thresholds 0x%X",p,(o_data->poundw[p].vdm_overvolt_small_thresholds >> 4) & 0x0F); FAPI_INF("o_data->poundw[%d].vdm_small_thresholds 0x%X",p,(o_data->poundw[p].vdm_overvolt_small_thresholds ) & 0x0F); FAPI_INF("o_data->poundw[%d].vdm_large_thresholds 0x%X",p,(o_data->poundw[p].vdm_large_extreme_thresholds >> 4) & 0x0F); FAPI_INF("o_data->poundw[%d].vdm_extreme_thresholds 0x%X",p,(o_data->poundw[p].vdm_large_extreme_thresholds) & 0x0F); VALIDATE_THRESHOLD_VALUES(((o_data->poundw[p].vdm_overvolt_small_thresholds >> 4) & 0x0F), // overvolt ((o_data->poundw[p].vdm_overvolt_small_thresholds) & 0x0F), //small ((o_data->poundw[p].vdm_large_extreme_thresholds >> 4) & 0x0F), //large ((o_data->poundw[p].vdm_large_extreme_thresholds) & 0x0F), //extreme l_threshold_value_state); if (!l_threshold_value_state) { o_state->iv_vdm_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_INVALID_THRESHOLD_VALUE(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_OP_POINT_TYPE(p) .set_VDM_OVERVOLT((o_data->poundw[p].vdm_overvolt_small_thresholds >> 4) & 0x0F) .set_VDM_SMALL(o_data->poundw[p].vdm_overvolt_small_thresholds & 0x0F) .set_VDM_EXTREME((o_data->poundw[p].vdm_large_extreme_thresholds >> 4) & 0x0F) .set_VDM_LARGE((o_data->poundw[p].vdm_large_extreme_thresholds) & 0x0F), "Pstate Parameter Block #W VDM threshold data are invalid"); break; } } bool l_frequency_value_state = 1; for (uint8_t p = 0; p < NUM_OP_POINTS; ++p) { // These fields are 4 bits wide, and stored in a uint8, hence the shifting // N_S, N_L, L_S, S_N FAPI_INF("o_data->poundw[%d] VDM_FREQ_DROP N_S = %d", p, ((o_data->poundw[p].vdm_normal_freq_drop >> 4) & 0x0F)); FAPI_INF("o_data->poundw[%d] VDM_FREQ_DROP N_L = %d", p, ((o_data->poundw[p].vdm_normal_freq_drop) & 0x0F)); FAPI_INF("o_data->poundw[%d] VDM_FREQ_RETURN L_S = %d", p, ((o_data->poundw[p].vdm_normal_freq_return >> 4) & 0x0F)); FAPI_INF("o_data->poundw[%d] VDM_FREQ_RETURN S_N = %d", p, ((o_data->poundw[p].vdm_normal_freq_return) & 0x0F)); VALIDATE_FREQUENCY_DROP_VALUES(((o_data->poundw[p].vdm_normal_freq_drop) & 0x0F), // N_L ((o_data->poundw[p].vdm_normal_freq_drop >> 4) & 0x0F), // N_S ((o_data->poundw[p].vdm_normal_freq_return >> 4) & 0x0F), // L_S ((o_data->poundw[p].vdm_normal_freq_return) & 0x0F), // S_N l_frequency_value_state); if (!l_frequency_value_state) { o_state->iv_vdm_enabled = false; FAPI_ASSERT_NOEXIT(false, fapi2::PSTATE_PB_POUND_W_INVALID_FREQ_DROP_VALUE(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_CHIP_TARGET(i_target) .set_OP_POINT_TYPE(p) .set_VDM_NORMAL_SMALL((o_data->poundw[p].vdm_normal_freq_drop >> 4) & 0x0F) .set_VDM_NORMAL_LARGE(o_data->poundw[p].vdm_normal_freq_drop & 0x0F) .set_VDM_LARGE_SMALL((o_data->poundw[p].vdm_normal_freq_return >> 4) & 0x0F) .set_VDM_SMALL_NORMAL((o_data->poundw[p].vdm_normal_freq_return) & 0x0F), "Pstate Parameter Block #W VDM frequency drop data are invalid"); break; } } //Biased compare vid data fapi2::ATTR_VDM_VID_COMPARE_BIAS_0P5PCT_Type l_bias_value; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDM_VID_COMPARE_BIAS_0P5PCT, i_target, l_bias_value), "Error from FAPI_ATTR_GET for attribute ATTR_VDM_VID_COMPARE_BIAS_0P5PCT"); float l_pound_w_points[NUM_OP_POINTS]; for (uint8_t i = 0; i < NUM_OP_POINTS; i++) { l_pound_w_points[i] = calc_bias(l_bias_value[i]); o_data->poundw[i].vdm_vid_compare_ivid = (uint32_t)(o_data->poundw[i].vdm_vid_compare_ivid * l_pound_w_points[i]); FAPI_INF("vdm_vid_compare_ivid %x %x, %x", o_data->poundw[i].vdm_vid_compare_ivid, o_data->poundw[i].vdm_vid_compare_ivid, l_pound_w_points[i]); } memcpy(&(o_vdmpb->vpd_w_data), o_data, sizeof(o_vdmpb->vpd_w_data)); } while(0); fapi_try_exit: // Given #W has both VDM and WOF content, a failure needs to disable both if (fapi2::current_err != fapi2::FAPI2_RC_SUCCESS) { o_state->iv_vdm_enabled = false; o_state->iv_wof_enabled = false; } if (!(o_state->iv_vdm_enabled)) { // With VDMs disabled, we have to ensure that we have some Large // Jump values to compute the safe mode frequency and voltage as some // part sorts assume that uplift in their guardbands. As systems are // offered assuming VDM operability which elevates the floor, default // values are needed. large_jump_defaults(o_data); } FAPI_DBG("<< proc_get_mvpd_poundw"); return fapi2::current_err; } fapi2::ReturnCode proc_set_resclk_table_attrs(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PSTATE_attribute_state* o_state) { uint8_t l_resclk_freq_index[RESCLK_FREQ_REGIONS]; uint8_t l_l3_steparray[RESCLK_L3_STEPS]; uint16_t l_resclk_freq_regions[RESCLK_FREQ_REGIONS]; uint16_t l_resclk_value[RESCLK_STEPS]; uint16_t l_l3_threshold_mv; o_state->iv_resclk_enabled = true; do { // Perform some basic sanity checks on the header data structures (since // the header values are provided by another team) FAPI_ASSERT_NOEXIT((p9_resclk_defines::RESCLK_INDEX_VEC.size() == RESCLK_FREQ_REGIONS), fapi2::PSTATE_PB_RESCLK_INDEX_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_FREQ_REGIONS(RESCLK_FREQ_REGIONS) .set_INDEX_VEC_SIZE(p9_resclk_defines::RESCLK_INDEX_VEC.size()), "p9_resclk_defines.h RESCLK_INDEX_VEC.size() mismatch"); FAPI_ASSERT_NOEXIT((p9_resclk_defines::RESCLK_TABLE_VEC.size() == RESCLK_STEPS), fapi2::PSTATE_PB_RESCLK_TABLE_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_STEPS(RESCLK_STEPS) .set_TABLE_VEC_SIZE(p9_resclk_defines::RESCLK_TABLE_VEC.size()), "p9_resclk_defines.h RESCLK_TABLE_VEC.size() mismatch"); FAPI_ASSERT_NOEXIT((p9_resclk_defines::L3CLK_TABLE_VEC.size() == RESCLK_L3_STEPS), fapi2::PSTATE_PB_RESCLK_L3_TABLE_ERROR(fapi2::FAPI2_ERRL_SEV_RECOVERED) .set_L3_STEPS(RESCLK_L3_STEPS) .set_L3_VEC_SIZE(p9_resclk_defines::L3CLK_TABLE_VEC.size()), "p9_resclk_defines.h L3CLK_TABLE_VEC.size() mismatch"); //FAPI_ASSERT_NOEXIT will log an error with recoverable.. but rc won't be //cleared.. So we are initializing again to continue further if (fapi2::current_err != fapi2::FAPI2_RC_SUCCESS) { o_state->iv_resclk_enabled = false; fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; break; } FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_L3_VALUE, i_target, l_l3_steparray)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGIONS, i_target, l_resclk_freq_regions)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGION_INDEX, i_target, l_resclk_freq_index)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_VALUE, i_target, l_resclk_value)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_RESCLK_L3_VOLTAGE_THRESHOLD_MV, i_target, l_l3_threshold_mv)); for (uint8_t i = 0; i < RESCLK_FREQ_REGIONS; ++i) { if (l_resclk_freq_regions[i] == 0) { l_resclk_freq_regions[i] = p9_resclk_defines::RESCLK_INDEX_VEC.at(i).freq; } if (l_resclk_freq_index[i] == 0) { l_resclk_freq_index[i] = p9_resclk_defines::RESCLK_INDEX_VEC.at(i).idx; } } for (uint8_t i = 0; i < RESCLK_STEPS; ++i) { if (l_resclk_value[i] == 0) { l_resclk_value[i] = p9_resclk_defines::RESCLK_TABLE_VEC.at(i); } } for (uint8_t i = 0; i < RESCLK_L3_STEPS; ++i) { if (l_l3_steparray[i] == 0) { l_l3_steparray[i] = p9_resclk_defines::L3CLK_TABLE_VEC.at(i); } } if(l_l3_threshold_mv == 0) { l_l3_threshold_mv = p9_resclk_defines::L3_VOLTAGE_THRESHOLD_MV; } FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_L3_VALUE, i_target, l_l3_steparray)); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGIONS, i_target, l_resclk_freq_regions)); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_FREQ_REGION_INDEX, i_target, l_resclk_freq_index)); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_VALUE, i_target, l_resclk_value)); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SYSTEM_RESCLK_L3_VOLTAGE_THRESHOLD_MV, i_target, l_l3_threshold_mv)); }while(0); fapi_try_exit: return fapi2::current_err; } //@brief Initialize HOMER VFRT data fapi2::ReturnCode p9_pstate_update_vfrt(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const GlobalPstateParmBlock* i_gppb, uint8_t* i_pBuffer, HomerVFRTLayout_t* o_vfrt_data, uint32_t i_reference_freq) { uint32_t l_index_0 = 0; uint32_t l_index_1 = 0; uint8_t l_type = 0; uint32_t l_freq_khz = 0; uint32_t l_step_freq_khz; Pstate l_ps; l_step_freq_khz = revle32(i_gppb->frequency_step_khz); FAPI_DBG("l_step_freq_khz = 0x%X (%d)", l_step_freq_khz, l_step_freq_khz); //Initialize VFRT header o_vfrt_data->vfrtHeader.magic_number = revle16(UINT16_GET(i_pBuffer)); i_pBuffer += 2; o_vfrt_data->vfrtHeader.reserved = revle16(UINT16_GET(i_pBuffer)); i_pBuffer += 2; o_vfrt_data->vfrtHeader.type_version = *i_pBuffer; i_pBuffer++; o_vfrt_data->vfrtHeader.res_vdnId = *i_pBuffer; // Future: this name is not accurate but takes a header change. i_pBuffer++; o_vfrt_data->vfrtHeader.VddId_QAId = *i_pBuffer; // Future: this name is not accurate but takes a header change. i_pBuffer++; o_vfrt_data->vfrtHeader.rsvd_QAId = *i_pBuffer; i_pBuffer++; //find type l_type = (o_vfrt_data->vfrtHeader.type_version) >> 4; char l_buffer_str[256]; // Temporary formatting string buffer char l_line_str[256]; // Formatted output line string // Filtering Tracing output to only only QID of 0 bool b_output_trace = false; if (o_vfrt_data->vfrtHeader.rsvd_QAId == QID_KEY && o_vfrt_data->vfrtHeader.res_vdnId <= VDN_PERCENT_KEY) { b_output_trace = true; } FAPI_DBG("res_vdnId = %X, VDN_PERCENT_KEY = %X, .rsvd_QAId = %X, QID_KEY = %X, trace = %u", o_vfrt_data->vfrtHeader.res_vdnId, VDN_PERCENT_KEY, o_vfrt_data->vfrtHeader.rsvd_QAId, QID_KEY, b_output_trace); if (b_output_trace) { strcpy(l_line_str, "VFRT:"); sprintf(l_buffer_str, " %X Ver/Type %X VDN%% %3d VDD%% %3d QID %d", revle16(o_vfrt_data->vfrtHeader.magic_number), revle16(o_vfrt_data->vfrtHeader.type_version), o_vfrt_data->vfrtHeader.res_vdnId, /// BUG: this should be VDN!!! o_vfrt_data->vfrtHeader.VddId_QAId, /// BUG: this should be VDD!!! o_vfrt_data->vfrtHeader.rsvd_QAId); /// BUG: this should be resvQID!!! strcat(l_line_str, l_buffer_str); } const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_WOF_ENABLE_FRATIO_Type l_enable_fratio; FAPI_ATTR_GET(fapi2::ATTR_WOF_ENABLE_FRATIO, FAPI_SYSTEM, l_enable_fratio); fapi2::ATTR_WOF_ENABLE_VRATIO_Type l_enable_vratio; FAPI_ATTR_GET(fapi2::ATTR_WOF_ENABLE_VRATIO, FAPI_SYSTEM, l_enable_vratio); bool b_fratio_set = true; bool b_first_vratio_set = true; // Get the frequency biases in place and check that they all match double f_freq_bias = 0; int freq_bias_value_hp = 0; int freq_bias_value_m1_hp = 0; bool b_bias_error = false; for (auto v = 0; v < NUM_OP_POINTS; ++v) { freq_bias_value_hp = i_gppb->ext_biases[v].frequency_hp; if (v > 0) { if (freq_bias_value_hp != freq_bias_value_m1_hp) { b_bias_error = true; FAPI_DBG("FATAL Bias mismatch error: v = %d; freq_bias_value_hp = %d; freq_bias_value_m1_hp = %d", v, freq_bias_value_hp, freq_bias_value_m1_hp ); } } freq_bias_value_m1_hp = freq_bias_value_hp; if (v == ULTRA) { f_freq_bias = calc_bias(freq_bias_value_hp); } } FAPI_ASSERT(!b_bias_error, fapi2::PSTATE_PB_VFRT_BIAS_ERROR() .set_CHIP_TARGET(i_target) .set_FREQ_BIAS_HP_ULTRATURBO(i_gppb->ext_biases[ULTRA].frequency_hp) .set_FREQ_BIAS_HP_TURBO(i_gppb->ext_biases[TURBO].frequency_hp) .set_FREQ_BIAS_HP_NOMINAL(i_gppb->ext_biases[NOMINAL].frequency_hp) .set_FREQ_BIAS_HP_POWERSAVE(i_gppb->ext_biases[POWERSAVE].frequency_hp) .set_UT_FREQ(i_reference_freq), "Frequency Biases do not match so VFRT biasing cannot occur"); if (f_freq_bias != 1) FAPI_INF("A frequency bias multiplier of %f being applied to all VFRT entries", f_freq_bias); //Initialize VFRT data part for (l_index_0 = 0; l_index_0 < VFRT_FRATIO_SIZE; ++l_index_0) { strcpy(l_buffer_str, ""); for (l_index_1 = 0; l_index_1 < VFRT_VRATIO_SIZE; ++l_index_1) { // Offset MHz*1000 (khz) + step (khz) * sysvalue float l_freq_raw_khz; float l_freq_biased_khz; l_freq_raw_khz = (float)(1000 * 1000 + (l_step_freq_khz * (*i_pBuffer))); l_freq_biased_khz = l_freq_raw_khz * f_freq_bias; // Round to nearest MHz as that is how the system tables are generated float l_freq_raw_up_mhz = (l_freq_biased_khz + 500)/1000; float l_freq_raw_dn_mhz = (l_freq_biased_khz)/1000; float l_freq_rounded_khz; if (l_freq_raw_up_mhz >= l_freq_raw_dn_mhz) l_freq_rounded_khz = (uint32_t)(l_freq_raw_up_mhz * 1000); else l_freq_rounded_khz = (uint32_t)(l_freq_raw_dn_mhz * 1000); l_freq_khz = (uint32_t)(l_freq_rounded_khz); FAPI_DBG("freq_raw_khz = %f; freq_biased_khz = %f; freq_rounded = 0x%X (%d); sysvalue = 0x%X (%d)", l_freq_raw_khz, l_freq_biased_khz, l_freq_khz, l_freq_khz, *i_pBuffer, *i_pBuffer); // Translate to Pstate. The called function will clip to the // legal range. The rc is only interesting if we care that // the pstate was clipped; in this case, we don't. freq2pState(i_gppb, l_freq_khz, &l_ps); o_vfrt_data->vfrt_data[l_index_0][l_index_1] = l_ps; if (b_first_vratio_set && l_index_1 >= 20 && b_output_trace) { sprintf(l_buffer_str, "[%2d][%2d] 0x%2X %4d; ", l_index_0, l_index_1, l_ps, l_freq_khz / 1000); strcat(l_line_str, l_buffer_str); } // Trace the last 8 values of the 24 for debug. As this is // in a loop that is processing over 1000 tables, the last // 8 gives a view that can correlate that the input data read // is correct without overfilling the HB trace buffer. if (l_index_1+1 == VFRT_VRATIO_SIZE && b_first_vratio_set && b_fratio_set && b_output_trace) { FAPI_INF("%s ", l_line_str); strcpy(l_buffer_str, ""); strcpy(l_line_str, " "); b_first_vratio_set = false; } i_pBuffer++; } // If fratio is not enabled, don't trace the remaining, duplicate entries. if (!l_enable_fratio) { b_fratio_set = false; b_first_vratio_set = false; } else { b_fratio_set = true; b_first_vratio_set = true; } } // Flip the type from System (0) to HOMER (1) l_type = 1; o_vfrt_data->vfrtHeader.type_version |= l_type << 4; fapi_try_exit: return fapi2::current_err; } /// Get IAC VDN vlue uint16_t get_iac_vdn_value (uint16_t i_vpd_vdn_mv, IddqTable i_iddq, uint8_t nest_leakage_percent, uint16_t i_vpd_idn_100ma) { uint16_t l_ac_vdn_value = 0; uint8_t l_iddq_index = 0; const uint8_t MIN_IDDQ_VALUE = 6; //considering 0.6 as 6 here for easy math const uint16_t IDDQ_MIN_VOLT_LEVEL = 600; uint8_t l_measured_temp_C[2] = {0}; uint16_t l_Ivdnq_5ma[2] = {0}; float l_scaled_leakage_ma[2] = {0}; uint16_t l_Ivdnq_vpd_ma = 0; uint8_t i = 0; uint8_t j = 0; //check bonunding is required or not uint16_t l_bounding_value = i_vpd_vdn_mv % 100; //Index to read from IDDQ table //Assumption here i_vpd_vdn_mv value will be greater than 600 and lesser //than 1100 mv l_iddq_index = (i_vpd_vdn_mv / 100) - MIN_IDDQ_VALUE; i = l_iddq_index; j = l_iddq_index + 1; uint16_t l_iq_mv[2] = {0}; l_iq_mv[0] = IDDQ_MIN_VOLT_LEVEL + (100 * i); l_iq_mv[1] = IDDQ_MIN_VOLT_LEVEL + (100 * (i + 1)); uint8_t l_diff_value = 0; do { if (!l_bounding_value) { //Read measured temp l_measured_temp_C[0] = i_iddq.avgtemp_vdn[i]; if ((l_measured_temp_C[0] == 0)) { FAPI_INF("Non Bounded measured temp value is 0"); break; } else if (l_measured_temp_C[0] < nest_leakage_percent) { l_diff_value = nest_leakage_percent - l_measured_temp_C[0]; } else { l_diff_value = l_measured_temp_C[0] - nest_leakage_percent; } //Read ivdnq_5ma l_Ivdnq_5ma[0] = i_iddq.ivdn[i]; //Scale each bounding Ivdnq_5ma value to 75C in mA l_scaled_leakage_ma[0] = l_Ivdnq_5ma[0] * 5 * pow (1.3, (l_diff_value / 10)); l_Ivdnq_vpd_ma = l_scaled_leakage_ma[0]; l_ac_vdn_value = (i_vpd_idn_100ma * 10) - (l_Ivdnq_vpd_ma * 10); } else { //Read measured temp l_measured_temp_C[0] = i_iddq.avgtemp_vdn[i]; l_measured_temp_C[1] = i_iddq.avgtemp_vdn[i + 1]; //Read ivdnq_5ma l_Ivdnq_5ma[0] = i_iddq.ivdn[i]; l_Ivdnq_5ma[1] = i_iddq.ivdn[i + 1]; //Scale each bounding Ivdnq_5ma value to 75C in mA for (j = 0; j < 2; j++) { if ((l_measured_temp_C[j] == 0)) { FAPI_INF("Bounded measured temp value is 0"); break; } else if (l_measured_temp_C[j] < nest_leakage_percent) { l_diff_value = nest_leakage_percent - l_measured_temp_C[j]; } else { l_diff_value = l_measured_temp_C[j] - nest_leakage_percent; } l_scaled_leakage_ma[j] = l_Ivdnq_5ma[j] * 5 * pow (1.3, (l_diff_value / 10)); } //Interpolate between scaled_leakage_ma[i] and scaled_leakage_ma[i+1] //using the same ratio as the VPD voltage is to the bounding volages) to //arrive at Ivdnq_vpd_ma l_Ivdnq_vpd_ma = l_scaled_leakage_ma[i] + roundUp((i_vpd_vdn_mv - 600 + (100 * i)) / ((l_iq_mv[1] - l_iq_mv[0]) * (l_scaled_leakage_ma[1] - l_scaled_leakage_ma[0]))); l_ac_vdn_value = (i_vpd_idn_100ma * 10) - (l_Ivdnq_vpd_ma * 10); } }while(0); return l_ac_vdn_value; } /** * calculate_effective_capacitance * * Description: Generic function to perform the effective capacitance * calculations. * C_eff = I / (V^1.3 * F) * * I is the AC component of Idd in 0.01 Amps (or10 mA) * V is the silicon voltage in 100 uV * F is the frequency in MHz * * Note: Caller must ensure they check for a 0 return value * and disable wof if that is the case * * Param[in]: i_iAC - the AC component * Param[in]: i_voltage - the voltage component in 100uV * Param[in]: i_frequency - the frequency component * * Return: The calculated effective capacitance */ uint16_t pstate_calculate_effective_capacitance( uint16_t i_iAC, uint16_t i_voltage, uint16_t i_frequency ) { // Compute V^1.3 using a best-fit equation // (V^1.3) = (21374 * (voltage in 100uV) - 50615296)>>10 uint32_t v_exp_1_dot_3 = (21374 * i_voltage - 50615296) >> 10; // Compute I / (V^1.3) uint32_t I = i_iAC << 14; // * 16384 // Prevent divide by zero if( v_exp_1_dot_3 == 0 ) { // Return 0 causing caller to disable wof. return 0; } uint32_t c_eff = (I / v_exp_1_dot_3); c_eff = c_eff << 14; // * 16384 // Divide by frequency and return the final value. // (I / (V^1.3 * F)) == I / V^1.3 /F return c_eff / i_frequency; } uint16_t roundUp(float i_value) { return ((uint16_t)(i_value == (uint16_t)i_value ? i_value : i_value + 1)); } // // p9_pstate_compute_vdm_threshold_pts // void p9_pstate_compute_vdm_threshold_pts(PoundW_data i_data, LocalPstateParmBlock* io_lppb) { int p = 0; //VID POINTS for (p = 0; p < NUM_OP_POINTS; p++) { io_lppb->vid_point_set[p] = i_data.poundw[p].vdm_vid_compare_ivid; FAPI_INF("Bi:VID=%x", io_lppb->vid_point_set[p]); } // Threshold points for (p = 0; p < NUM_OP_POINTS; p++) { // overvolt threshold io_lppb->threshold_set[p][VDM_OVERVOLT_INDEX] = g_GreyCodeIndexMapping[(i_data.poundw[p].vdm_overvolt_small_thresholds >> 4) & 0x0F]; FAPI_INF("Bi: OV TSHLD =%d", io_lppb->threshold_set[p][0]); // small threshold io_lppb->threshold_set[p][VDM_SMALL_INDEX] = (g_GreyCodeIndexMapping[i_data.poundw[p].vdm_overvolt_small_thresholds & 0x0F]); FAPI_INF("Bi: SM TSHLD =%d", io_lppb->threshold_set[p][1]); // large threshold io_lppb->threshold_set[p][VDM_LARGE_INDEX] = (g_GreyCodeIndexMapping[(i_data.poundw[p].vdm_large_extreme_thresholds >> 4) & 0x0F]); FAPI_INF("Bi: LG TSHLD =%d", io_lppb->threshold_set[p][2]); // extreme threshold io_lppb->threshold_set[p][VDM_XTREME_INDEX] = (g_GreyCodeIndexMapping[i_data.poundw[p].vdm_large_extreme_thresholds & 0x0F]); FAPI_INF("Bi: EX TSHLD =%d", io_lppb->threshold_set[p][3]); } // Jump value points for (p = 0; p < NUM_OP_POINTS; p++) { // N_L value io_lppb->jump_value_set[p][VDM_N_S_INDEX] = (i_data.poundw[p].vdm_normal_freq_drop >> 4) & 0x0F; FAPI_INF("Bi: N_S =%d", io_lppb->jump_value_set[p][0]); // N_S value io_lppb->jump_value_set[p][VDM_N_L_INDEX] = i_data.poundw[p].vdm_normal_freq_drop & 0x0F; FAPI_INF("Bi: N_L =%d", io_lppb->jump_value_set[p][1]); // L_S value io_lppb->jump_value_set[p][VDM_L_S_INDEX] = (i_data.poundw[p].vdm_normal_freq_return >> 4) & 0x0F; FAPI_INF("Bi: L_S =%d", io_lppb->jump_value_set[p][2]); // S_L value io_lppb->jump_value_set[p][VDM_S_N_INDEX] = i_data.poundw[p].vdm_normal_freq_return & 0x0F; FAPI_INF("Bi: S_L =%d", io_lppb->jump_value_set[p][3]); } } // // // p9_pstate_compute_PsVIDCompSlopes_slopes // void p9_pstate_compute_PsVIDCompSlopes_slopes(PoundW_data i_data, LocalPstateParmBlock* io_lppb, uint8_t* i_pstate) { do { char const* region_names[] = { "REGION_POWERSAVE_NOMINAL", "REGION_NOMINAL_TURBO", "REGION_TURBO_ULTRA" }; // ULTRA TURBO pstate check is not required..because its pstate will be // 0 if (!(i_pstate[POWERSAVE]) || !(i_pstate[NOMINAL]) || !(i_pstate[TURBO])) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero"); break; } for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { io_lppb->PsVIDCompSlopes[region] = revle16( compute_slope_4_12( io_lppb->vid_point_set[region + 1], io_lppb->vid_point_set[region], i_pstate[region], i_pstate[region + 1]) ); FAPI_DBG("PsVIDCompSlopes[%s] 0x%04x %d", region_names[region], revle16(io_lppb->PsVIDCompSlopes[region]), revle16(io_lppb->PsVIDCompSlopes[region])); } } while(0); } // // // p9_pstate_compute_PsVDMThreshSlopes // void p9_pstate_compute_PsVDMThreshSlopes( LocalPstateParmBlock* io_lppb, uint8_t* i_pstate) { do { // ULTRA TURBO pstate check is not required..because its pstate will be // 0 if (!(i_pstate[POWERSAVE]) || !(i_pstate[NOMINAL]) || !(i_pstate[TURBO])) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero"); break; } for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { for (uint8_t i = 0; i < NUM_THRESHOLD_POINTS; ++i) { io_lppb->PsVDMThreshSlopes[region][i] = revle16( compute_slope_thresh(io_lppb->threshold_set[region+1][i], io_lppb->threshold_set[region][i], i_pstate[region], i_pstate[region+1]) ); FAPI_INF("PsVDMThreshSlopes %s %x TH_N %d TH_P %d PS_P %d PS_N %d", prt_region_names[region], revle16(io_lppb->PsVDMThreshSlopes[region][i]), io_lppb->threshold_set[region+1][i], io_lppb->threshold_set[region][i], i_pstate[region], i_pstate[region+1]); } } } while(0); } // // p9_pstate_compute_PsVDMJumpSlopes // void p9_pstate_compute_PsVDMJumpSlopes( LocalPstateParmBlock* io_lppb, uint8_t* i_pstate) { do { // ULTRA TURBO pstate check is not required..because its pstate will be // 0 if (!(i_pstate[POWERSAVE]) || !(i_pstate[NOMINAL]) || !(i_pstate[TURBO])) { FAPI_ERR("Non-UltraTurbo PSTATE value shouldn't be zero"); break; } //Calculate slopes // for(auto region(REGION_POWERSAVE_NOMINAL); region <= REGION_TURBO_ULTRA; ++region) { for (uint8_t i = 0; i < NUM_JUMP_VALUES; ++i) { io_lppb->PsVDMJumpSlopes[region][i] = revle16( compute_slope_thresh(io_lppb->jump_value_set[region+1][i], io_lppb->jump_value_set[region][i], i_pstate[region], i_pstate[region+1]) ); FAPI_INF("PsVDMJumpSlopes %s %x N_S %d N_L %d L_S %d S_N %d", prt_region_names[region], revle16(io_lppb->PsVDMJumpSlopes[region][i]), io_lppb->jump_value_set[region+1][i], io_lppb->jump_value_set[region][i], i_pstate[region], i_pstate[region+1]); } } } while(0); } // p9_pstate_set_global_feature_attributes fapi2::ReturnCode p9_pstate_set_global_feature_attributes(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, PSTATE_attribute_state i_state, QuadManagerFlags* o_qm_flags) { // Quad Manager Flags fapi2::buffer<uint16_t> l_data16; fapi2::ATTR_PSTATES_ENABLED_Type l_ps_enabled = (fapi2::ATTR_PSTATES_ENABLED_Type)fapi2::ENUM_ATTR_PSTATES_ENABLED_FALSE; fapi2::ATTR_RESCLK_ENABLED_Type l_resclk_enabled = (fapi2::ATTR_RESCLK_ENABLED_Type)fapi2::ENUM_ATTR_RESCLK_ENABLED_FALSE; fapi2::ATTR_VDM_ENABLED_Type l_vdm_enabled = (fapi2::ATTR_VDM_ENABLED_Type)fapi2::ENUM_ATTR_VDM_ENABLED_FALSE; fapi2::ATTR_IVRM_ENABLED_Type l_ivrm_enabled = (fapi2::ATTR_IVRM_ENABLED_Type)fapi2::ENUM_ATTR_IVRM_ENABLED_FALSE; fapi2::ATTR_WOF_ENABLED_Type l_wof_enabled = (fapi2::ATTR_WOF_ENABLED_Type)fapi2::ENUM_ATTR_WOF_ENABLED_FALSE; if (i_state.iv_pstates_enabled) { l_ps_enabled = (fapi2::ATTR_PSTATES_ENABLED_Type)fapi2::ENUM_ATTR_PSTATES_ENABLED_TRUE; } if (i_state.iv_resclk_enabled) { l_resclk_enabled = (fapi2::ATTR_RESCLK_ENABLED_Type)fapi2::ENUM_ATTR_RESCLK_ENABLED_TRUE; } if (i_state.iv_vdm_enabled) { l_vdm_enabled = (fapi2::ATTR_VDM_ENABLED_Type)fapi2::ENUM_ATTR_VDM_ENABLED_TRUE; } if (i_state.iv_ivrm_enabled) { l_ivrm_enabled = (fapi2::ATTR_IVRM_ENABLED_Type)fapi2::ENUM_ATTR_IVRM_ENABLED_TRUE; } if (i_state.iv_wof_enabled) { l_wof_enabled = (fapi2::ATTR_WOF_ENABLED_Type)fapi2::ENUM_ATTR_WOF_ENABLED_TRUE; } #define SET_ATTR(attr_name, target, attr_assign) \ FAPI_TRY(FAPI_ATTR_SET(attr_name, target, attr_assign),"Attribute set failed"); \ FAPI_INF("%-60s = 0x%08x %d", #attr_name, attr_assign, attr_assign); SET_ATTR(fapi2::ATTR_PSTATES_ENABLED, i_target, l_ps_enabled); SET_ATTR(fapi2::ATTR_RESCLK_ENABLED, i_target, l_resclk_enabled); SET_ATTR(fapi2::ATTR_VDM_ENABLED, i_target, l_vdm_enabled); SET_ATTR(fapi2::ATTR_IVRM_ENABLED, i_target, l_ivrm_enabled); SET_ATTR(fapi2::ATTR_WOF_ENABLED, i_target, l_wof_enabled); // ---------------- // set CME QM flags // ---------------- l_data16.flush<0>(); l_data16.insertFromRight<0, 1>(l_resclk_enabled); l_data16.insertFromRight<1, 1>(l_ivrm_enabled); l_data16.insertFromRight<2, 1>(l_vdm_enabled); l_data16.insertFromRight<3, 1>(l_wof_enabled); // DROOP_PROTECT -> DPLL Mode 3 // DROOP_PROTECT_OVERVOLT -> DPLL Mode 3.5 // DYNAMIC -> DPLL Mode 4 // DYNAMIC_PROTECT -> DPLL Mode 5 // enable_fmin enable_fmax enable_jump // DPLL Mode 2 0 0 0 // DPLL Mode 3 0 0 1 // DPLL Mode 4 X 1 0 // DPLL Mode 4 1 X 0 // DPLL Mode 3.5 0 1 1 // DPLL Mode 5 1 X 1 switch (attr.attr_dpll_vdm_response) { case fapi2::ENUM_ATTR_DPLL_VDM_RESPONSE_DROOP_PROTECT: l_data16 |= CME_QM_FLAG_SYS_JUMP_PROTECT; FAPI_INF("%-60s", "DPLL Response"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_JUMP_PROTECT"); break; case fapi2::ENUM_ATTR_DPLL_VDM_RESPONSE_DROOP_PROTECT_OVERVOLT: l_data16 |= CME_QM_FLAG_SYS_DYN_FMAX_ENABLE; l_data16 |= CME_QM_FLAG_SYS_JUMP_PROTECT; FAPI_INF("%-60s", "DPLL Response"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_DYN_FMAX_ENABLE"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_JUMP_PROTECT"); break; case fapi2::ENUM_ATTR_DPLL_VDM_RESPONSE_DYNAMIC: l_data16 |= CME_QM_FLAG_SYS_DYN_FMIN_ENABLE; l_data16 |= CME_QM_FLAG_SYS_DYN_FMAX_ENABLE; FAPI_INF("%-60s", "DPLL Response"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_DYN_FMIN_ENABLEE"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_DYN_FMAX_ENABLE"); break; case fapi2::ENUM_ATTR_DPLL_VDM_RESPONSE_DYNAMIC_PROTECT: l_data16 |= CME_QM_FLAG_SYS_DYN_FMIN_ENABLE; l_data16 |= CME_QM_FLAG_SYS_JUMP_PROTECT; FAPI_INF("%-60s", "DPLL Response"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_DYN_FMIN_ENABLE"); FAPI_INF("%-60s = Set", "CME_QM_FLAG_SYS_JUMP_PROTECT"); break; } o_qm_flags->value = revle16(l_data16); FAPI_INF("%-60s = 0x%04x %d", "QM Flags", revle16(o_qm_flags->value)); fapi_try_exit: return fapi2::current_err; } //large_jump_interpolate uint32_t large_jump_interpolate(const Pstate i_pstate, const VpdOperatingPoint i_operating_points[NUM_OP_POINTS], const uint32_t i_step_frequency, const Pstate i_ps_pstate, const PoundW_data i_data) { uint8_t l_jump_value_set_ps = i_data.poundw[POWERSAVE].vdm_normal_freq_drop & 0x0F; uint8_t l_jump_value_set_nom = i_data.poundw[NOMINAL].vdm_normal_freq_drop & 0x0F; uint32_t l_slope_value = compute_slope_thresh(l_jump_value_set_nom, l_jump_value_set_ps, i_operating_points[POWERSAVE].pstate, i_operating_points[NOMINAL].pstate); uint32_t l_vdm_jump_value = (uint32_t)((int32_t)l_jump_value_set_ps + (((int32_t)l_slope_value * (i_ps_pstate - i_pstate)) >> THRESH_SLOPE_FP_SHIFT)); return l_vdm_jump_value; } //large_jump_defaults void large_jump_defaults(PoundW_data* io_data) { const float DEFAULT_VDM_DROP_PERCENT = 12.5; const float DEFAULT_VDM_DROP_DIVISOR = 32; float poundw_freq_drop_float = (DEFAULT_VDM_DROP_PERCENT/100)*DEFAULT_VDM_DROP_DIVISOR; uint8_t poundw_freq_drop_value = (uint8_t)poundw_freq_drop_float; FAPI_DBG ("DEFAULT_VDM_DROP_PERCENT = %6.3f%%; DEFAULT_VDM_DROP_DIVISOR = %6.3f; poundw_freq_drop_value = %f %X", DEFAULT_VDM_DROP_PERCENT, DEFAULT_VDM_DROP_DIVISOR, poundw_freq_drop_float, poundw_freq_drop_value); // N_S/N_L - each a nibble in a byte io_data->poundw[POWERSAVE].vdm_normal_freq_drop = poundw_freq_drop_value; io_data->poundw[NOMINAL].vdm_normal_freq_drop = poundw_freq_drop_value; FAPI_INF ("Using default Large Jump percentage (%6.3f%%) for N_L (%X) for both POWERSAVE and NOMINAL due to #W access failure ", DEFAULT_VDM_DROP_PERCENT, io_data->poundw[POWERSAVE].vdm_normal_freq_drop); return; } //ps2v_mv - Pstate to External Voltage in mV uint32_t ps2v_mv(const Pstate i_pstate, const VpdOperatingPoint i_operating_points[NUM_OP_POINTS], const uint32_t i_step_frequency) { uint32_t region_start, region_end; const char* pv_op_str[NUM_OP_POINTS] = PV_OP_ORDER_STR; FAPI_DBG("i_pstate = 0x%x, (%d)", i_pstate, i_pstate); // Determine the VPD region if(i_pstate > i_operating_points[NOMINAL].pstate) { region_start = POWERSAVE; region_end = NOMINAL; FAPI_DBG("Region POWERSAVE_NOMINAL detected"); } else if(i_pstate > i_operating_points[TURBO].pstate) { region_start = NOMINAL; region_end = TURBO; FAPI_DBG("Region NOMINAL_TURBO detected"); } else { region_start = TURBO; region_end = ULTRA; FAPI_DBG("Region TURBO_ULTRA detected"); } uint32_t l_SlopeValue = compute_slope_4_12(revle32(i_operating_points[region_end].vdd_mv), revle32(i_operating_points[region_start].vdd_mv), i_operating_points[region_start].pstate, i_operating_points[region_end].pstate); FAPI_INF("l_globalppb.i_operating_points[%s].vdd_mv 0x%-3x (%d)", pv_op_str[region_end], revle32(i_operating_points[region_end].vdd_mv), revle32(i_operating_points[region_end].vdd_mv)); FAPI_INF("l_globalppb.i_operating_points[%s].vdd_mv 0x%-3x (%d)", pv_op_str[region_start], revle32(i_operating_points[region_start].vdd_mv), revle32(i_operating_points[region_start].vdd_mv)); FAPI_INF("l_globalppb.i_operating_points[%s].pstate 0x%-3x (%d)", pv_op_str[region_end], i_operating_points[region_end].pstate, i_operating_points[region_end].pstate); FAPI_INF("l_globalppb.i_operating_points[%s].pstate 0x%-3x (%d)", pv_op_str[region_start], i_operating_points[region_start].pstate, i_operating_points[region_start].pstate); FAPI_INF ("l_SlopeValue %x",l_SlopeValue); uint32_t x = (l_SlopeValue * (-i_pstate + i_operating_points[region_start].pstate)); uint32_t y = x >> VID_SLOPE_FP_SHIFT_12; uint32_t l_vdd = (((l_SlopeValue * (-i_pstate + i_operating_points[region_start].pstate)) >> VID_SLOPE_FP_SHIFT_12) + revle32(i_operating_points[region_start].vdd_mv)); // Round up l_vdd = (l_vdd << 1) + 1; l_vdd = l_vdd >> 1; FAPI_DBG("i_pstate = %d " "i_operating_points[%s].pstate) = %d " "i_operating_points[%s].vdd_mv = %d " "VID_SLOPE_FP_SHIFT_12 = %X " "x = %x (%d) y = %x (%d)", i_pstate, pv_op_str[region_start], i_operating_points[region_start].pstate, pv_op_str[region_start], revle32(i_operating_points[region_start].vdd_mv), VID_SLOPE_FP_SHIFT_12, x, x, y, y); FAPI_INF ("l_vdd 0x%x (%d)", l_vdd, l_vdd); return l_vdd; } //p9_pstate_safe_mode_computation fapi2::ReturnCode p9_pstate_safe_mode_computation(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const VpdOperatingPoint i_operating_points[NUM_VPD_PTS_SET][NUM_OP_POINTS], const uint32_t i_reference_freq, const uint32_t i_step_frequency, const Pstate i_ps_pstate, Safe_mode_parameters *o_safe_mode_values, const PoundW_data i_poundw_data) { Safe_mode_parameters l_safe_mode_values; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; fapi2::ATTR_SAFE_MODE_FREQUENCY_MHZ_Type l_safe_mode_freq_mhz; fapi2::ATTR_SAFE_MODE_VOLTAGE_MV_Type l_safe_mode_mv; fapi2::ATTR_VDD_BOOT_VOLTAGE_Type l_boot_mv; uint32_t l_safe_mode_op_ps2freq_mhz; uint32_t l_core_floor_mhz; uint32_t l_op_pt; VpdOperatingPoint l_operating_point[NUM_OP_POINTS]; get_operating_point(i_operating_points, VPD_PT_SET_BIASED_SYSP, l_operating_point); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_CORE_FLOOR_MHZ, FAPI_SYSTEM, l_core_floor_mhz)); // Core floor frequency should be less than ultra turbo freq.. // if not log an error if ((l_core_floor_mhz*1000) > i_reference_freq) { FAPI_ERR("Core floor frequency %08x is greater than UltraTurbo frequency %08x", (l_core_floor_mhz*1000), i_reference_freq); FAPI_ASSERT(false, fapi2::PSTATE_PB_CORE_FLOOR_FREQ_GT_UT_FREQ() .set_CHIP_TARGET(i_target) .set_CORE_FLOOR_FREQ(l_core_floor_mhz*1000) .set_UT_FREQ(i_reference_freq), "Core floor freqency is greater than UltraTurbo frequency"); } FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SAFE_MODE_FREQUENCY_MHZ, i_target, l_safe_mode_freq_mhz)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SAFE_MODE_VOLTAGE_MV, i_target, l_safe_mode_mv)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDD_BOOT_VOLTAGE, i_target, l_boot_mv)); FAPI_DBG ("l_safe_mode_freq_mhz 0%08x (%d)", l_safe_mode_freq_mhz, l_safe_mode_freq_mhz); FAPI_DBG ("l_safe_mode_mv 0%08x (%d)", l_safe_mode_mv, l_safe_mode_mv); FAPI_DBG ("l_boot_mv 0%08x (%d)", l_boot_mv, l_boot_mv); FAPI_INF ("core_floor_mhz 0%08x (%d)", l_core_floor_mhz, l_core_floor_mhz); FAPI_INF("operating_point[POWERSAVE].frequency_mhz 0%08x (%d)", revle32(l_operating_point[POWERSAVE].frequency_mhz), revle32(l_operating_point[POWERSAVE].frequency_mhz)); FAPI_INF ("reference_freq 0%08x (%d)", i_reference_freq, i_reference_freq); FAPI_INF ("step_frequency 0%08x (%d)", i_step_frequency, i_step_frequency); l_op_pt = revle32(l_operating_point[POWERSAVE].frequency_mhz); // Safe operational frequency is the MAX(core floor, VPD Powersave). // PowerSave is the lowest operational frequency that the part was tested at if (l_core_floor_mhz > l_op_pt) { FAPI_INF("Core floor greater that POWERSAVE"); l_safe_mode_values.safe_op_freq_mhz = l_core_floor_mhz; } else { FAPI_INF("Core floor less than or equal to POWERSAVE"); l_safe_mode_values.safe_op_freq_mhz = l_op_pt; } FAPI_INF ("safe_mode_values.safe_op_freq_mhz 0%08x (%d)", l_safe_mode_values.safe_op_freq_mhz, l_safe_mode_values.safe_op_freq_mhz); // Calculate safe operational pstate. This must be rounded down to create // a faster Pstate than the floor l_safe_mode_values.safe_op_ps = ((float)(i_reference_freq) - (float)(l_safe_mode_values.safe_op_freq_mhz * 1000)) / (float)i_step_frequency; l_safe_mode_op_ps2freq_mhz = (i_reference_freq - (l_safe_mode_values.safe_op_ps * i_step_frequency)) / 1000; while (l_safe_mode_op_ps2freq_mhz < l_safe_mode_values.safe_op_freq_mhz) { l_safe_mode_values.safe_op_ps--; l_safe_mode_op_ps2freq_mhz = (i_reference_freq - (l_safe_mode_values.safe_op_ps * i_step_frequency)) / 1000; } // Calculate safe jump value for large frequency l_safe_mode_values.safe_vdm_jump_value = large_jump_interpolate(l_safe_mode_values.safe_op_ps, l_operating_point, i_step_frequency, i_ps_pstate, i_poundw_data); FAPI_INF ("l_safe_mode_values.safe_vdm_jump_value %x -> %5.2f %%", l_safe_mode_values.safe_vdm_jump_value, ((float)l_safe_mode_values.safe_vdm_jump_value/32)*100); // Calculate safe mode frequency - Round up to nearest MHz // The uplifted frequency is based on the fact that the DPLL percentage is a // "down" value. Hence: // X (uplifted safe) = Y (safe operating) / (1 - droop percentage) l_safe_mode_values.safe_mode_freq_mhz = (uint32_t) (((float)l_safe_mode_op_ps2freq_mhz * 1000 / (1 - (float)l_safe_mode_values.safe_vdm_jump_value/32) + 500) / 1000); if (l_safe_mode_freq_mhz) { l_safe_mode_values.safe_mode_freq_mhz = l_safe_mode_freq_mhz; FAPI_INF("Applying override safe mode freq value of %d MHz", l_safe_mode_freq_mhz); } else { FAPI_INF("Setting safe mode frequency to %d MHz (0x%x)", l_safe_mode_values.safe_mode_freq_mhz, l_safe_mode_values.safe_mode_freq_mhz); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SAFE_MODE_FREQUENCY_MHZ, i_target, l_safe_mode_values.safe_mode_freq_mhz)); } FAPI_INF ("l_safe_mode_values.safe_mode_freq_mhz 0x%0x (%d)", l_safe_mode_values.safe_mode_freq_mhz, l_safe_mode_values.safe_mode_freq_mhz); // Safe frequency must be less than ultra turbo freq. // if not log an error if ((l_safe_mode_values.safe_mode_freq_mhz*1000) > i_reference_freq) { FAPI_ERR("Safe mode frequency %08x is greater than UltraTurbo frequency %08x", (l_safe_mode_values.safe_op_freq_mhz*1000), i_reference_freq); FAPI_ASSERT(false, fapi2::PSTATE_PB_SAFE_FREQ_GT_UT_FREQ() .set_CHIP_TARGET(i_target) .set_SAFE_FREQ(l_safe_mode_values.safe_mode_freq_mhz*1000) .set_UT_FREQ(i_reference_freq), "Safe mode freqency is greater than UltraTurbo frequency"); } l_safe_mode_values.safe_mode_ps = ((float)(i_reference_freq) - (float)(l_safe_mode_values.safe_mode_freq_mhz * 1000)) / (float)i_step_frequency; FAPI_INF ("l_safe_mode_values.safe_mode_ps %x (%d)", l_safe_mode_values.safe_mode_ps, l_safe_mode_values.safe_mode_ps); // Calculate safe mode voltage // Use the biased with system parms operating points l_safe_mode_values.safe_mode_mv = ps2v_mv(l_safe_mode_values.safe_mode_ps, l_operating_point, i_step_frequency); if (l_safe_mode_mv) { l_safe_mode_values.safe_mode_mv = l_safe_mode_mv; FAPI_INF("Applying override safe mode voltage value of %d mV", l_safe_mode_mv); } else { FAPI_INF("Setting safe mode voltage to %d mv (0x%x)", l_safe_mode_values.safe_mode_mv, l_safe_mode_values.safe_mode_mv); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_SAFE_MODE_VOLTAGE_MV, i_target, l_safe_mode_values.safe_mode_mv)); } FAPI_INF ("l_safe_mode_values.safe_mode_mv 0x%x (%d)", l_safe_mode_values.safe_mode_mv, l_safe_mode_values.safe_mode_mv); fapi2::ATTR_SAFE_MODE_NOVDM_UPLIFT_MV_Type l_uplift_mv; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SAFE_MODE_NOVDM_UPLIFT_MV, i_target, l_uplift_mv)); // Calculate boot mode voltage l_safe_mode_values.boot_mode_mv = l_safe_mode_values.safe_mode_mv + l_uplift_mv; FAPI_INF("l_safe_mode_values.boot_mode_mv 0x%x (%d)", l_safe_mode_values.boot_mode_mv, l_safe_mode_values.boot_mode_mv); memcpy (o_safe_mode_values,&l_safe_mode_values, sizeof(Safe_mode_parameters)); fapi_try_exit: return fapi2::current_err; } // *INDENT-ON*
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "tools/debug.hxx" #include "tools/diagnose_ex.h" #include "tools/time.hxx" #include "vcl/window.hxx" #include "vcl/event.hxx" #include "vcl/svapp.hxx" #include "vcl/wrkwin.hxx" #include "vcl/help.hxx" #include "helpwin.hxx" #include "svdata.hxx" // ======================================================================= #define HELPWINSTYLE_QUICK 0 #define HELPWINSTYLE_BALLOON 1 #define HELPTEXTMARGIN_QUICK 3 #define HELPTEXTMARGIN_BALLOON 6 #define HELPDELAY_NORMAL 1 #define HELPDELAY_SHORT 2 #define HELPDELAY_NONE 3 #define HELPTEXTMAXLEN 150 // ======================================================================= Help::Help() { } Help::~Help() { } // ----------------------------------------------------------------------- void Help::OpenHelpAgent( const rtl::OString& ) { } // ----------------------------------------------------------------------- sal_Bool Help::Start( const XubString&, const Window* ) { return sal_False; } sal_Bool Help::SearchKeyword( const XubString& ) { return sal_False; } // ----------------------------------------------------------------------- XubString Help::GetHelpText( const String&, const Window* ) { return ImplGetSVEmptyStr(); } // ----------------------------------------------------------------------- void Help::EnableContextHelp() { ImplGetSVData()->maHelpData.mbContextHelp = sal_True; } // ----------------------------------------------------------------------- void Help::DisableContextHelp() { ImplGetSVData()->maHelpData.mbContextHelp = sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::IsContextHelpEnabled() { return ImplGetSVData()->maHelpData.mbContextHelp; } // ----------------------------------------------------------------------- void Help::EnableExtHelp() { ImplGetSVData()->maHelpData.mbExtHelp = sal_True; } // ----------------------------------------------------------------------- void Help::DisableExtHelp() { ImplGetSVData()->maHelpData.mbExtHelp = sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::IsExtHelpEnabled() { return ImplGetSVData()->maHelpData.mbExtHelp; } // ----------------------------------------------------------------------- sal_Bool Help::StartExtHelp() { ImplSVData* pSVData = ImplGetSVData(); if ( pSVData->maHelpData.mbExtHelp && !pSVData->maHelpData.mbExtHelpMode ) { pSVData->maHelpData.mbExtHelpMode = sal_True; pSVData->maHelpData.mbOldBalloonMode = pSVData->maHelpData.mbBalloonHelp; pSVData->maHelpData.mbBalloonHelp = sal_True; if ( pSVData->maWinData.mpAppWin ) pSVData->maWinData.mpAppWin->ImplGenerateMouseMove(); return sal_True; } return sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::EndExtHelp() { ImplSVData* pSVData = ImplGetSVData(); if ( pSVData->maHelpData.mbExtHelp && pSVData->maHelpData.mbExtHelpMode ) { pSVData->maHelpData.mbExtHelpMode = sal_False; pSVData->maHelpData.mbBalloonHelp = pSVData->maHelpData.mbOldBalloonMode; if ( pSVData->maWinData.mpAppWin ) pSVData->maWinData.mpAppWin->ImplGenerateMouseMove(); return sal_True; } return sal_False; } // ----------------------------------------------------------------------- void Help::EnableBalloonHelp() { ImplGetSVData()->maHelpData.mbBalloonHelp = sal_True; } // ----------------------------------------------------------------------- void Help::DisableBalloonHelp() { ImplGetSVData()->maHelpData.mbBalloonHelp = sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::IsBalloonHelpEnabled() { return ImplGetSVData()->maHelpData.mbBalloonHelp; } // ----------------------------------------------------------------------- sal_Bool Help::ShowBalloon( Window* pParent, const Point& rScreenPos, const XubString& rHelpText ) { ImplShowHelpWindow( pParent, HELPWINSTYLE_BALLOON, 0, rHelpText, ImplGetSVEmptyStr(), rScreenPos ); return sal_True; } // ----------------------------------------------------------------------- sal_Bool Help::ShowBalloon( Window* pParent, const Point& rScreenPos, const Rectangle& rRect, const XubString& rHelpText ) { ImplShowHelpWindow( pParent, HELPWINSTYLE_BALLOON, 0, rHelpText, ImplGetSVEmptyStr(), rScreenPos, &rRect ); return sal_True; } // ----------------------------------------------------------------------- void Help::EnableQuickHelp() { ImplGetSVData()->maHelpData.mbQuickHelp = sal_True; } // ----------------------------------------------------------------------- void Help::DisableQuickHelp() { ImplGetSVData()->maHelpData.mbQuickHelp = sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::IsQuickHelpEnabled() { return ImplGetSVData()->maHelpData.mbQuickHelp; } // ----------------------------------------------------------------------- sal_Bool Help::ShowQuickHelp( Window* pParent, const Rectangle& rScreenRect, const XubString& rHelpText, const XubString& rLongHelpText, sal_uInt16 nStyle ) { ImplShowHelpWindow( pParent, HELPWINSTYLE_QUICK, nStyle, rHelpText, rLongHelpText, pParent->OutputToScreenPixel( pParent->GetPointerPosPixel() ), &rScreenRect ); return sal_True; } // ----------------------------------------------------------------------- void Help::HideBalloonAndQuickHelp() { HelpTextWindow const * pHelpWin = ImplGetSVData()->maHelpData.mpHelpWin; bool const bIsVisible = ( pHelpWin != NULL ) && pHelpWin->IsVisible(); ImplDestroyHelpWindow( bIsVisible ); } // ----------------------------------------------------------------------- sal_uIntPtr Help::ShowTip( Window* pParent, const Rectangle& rScreenRect, const XubString& rText, sal_uInt16 nStyle ) { sal_uInt16 nHelpWinStyle = ( ( nStyle & QUICKHELP_TIP_STYLE_BALLOON ) != 0 ) ? HELPWINSTYLE_BALLOON : HELPWINSTYLE_QUICK; HelpTextWindow* pHelpWin = new HelpTextWindow( pParent, rText, nHelpWinStyle, nStyle ); sal_uIntPtr nId = reinterpret_cast< sal_uIntPtr >( pHelpWin ); UpdateTip( nId, pParent, rScreenRect, rText ); pHelpWin->ShowHelp( HELPDELAY_NONE ); return nId; } // ----------------------------------------------------------------------- void Help::UpdateTip( sal_uIntPtr nId, Window* pParent, const Rectangle& rScreenRect, const XubString& rText ) { HelpTextWindow* pHelpWin = reinterpret_cast< HelpTextWindow* >( nId ); ENSURE_OR_RETURN_VOID( pHelpWin != NULL, "Help::UpdateTip: invalid ID!" ); Size aSz = pHelpWin->CalcOutSize(); pHelpWin->SetOutputSizePixel( aSz ); ImplSetHelpWindowPos( pHelpWin, pHelpWin->GetWinStyle(), pHelpWin->GetStyle(), pParent->OutputToScreenPixel( pParent->GetPointerPosPixel() ), &rScreenRect ); pHelpWin->SetHelpText( rText ); } // ----------------------------------------------------------------------- void Help::HideTip( sal_uLong nId ) { HelpTextWindow* pHelpWin = (HelpTextWindow*)nId; Window* pFrameWindow = pHelpWin->ImplGetFrameWindow(); pHelpWin->Hide(); // trigger update, so that a Paint is instantly triggered since we do not save the background pFrameWindow->ImplUpdateAll(); delete pHelpWin; ImplGetSVData()->maHelpData.mnLastHelpHideTime = Time::GetSystemTicks(); } // ======================================================================= HelpTextWindow::HelpTextWindow( Window* pParent, const XubString& rText, sal_uInt16 nHelpWinStyle, sal_uInt16 nStyle ) : //FloatingWindow( pParent->ImplGetFrameWindow(), WB_SYSTEMWINDOW ), FloatingWindow( pParent, WB_SYSTEMWINDOW|WB_TOOLTIPWIN ), // #105827# if we change the parent, mirroring will not work correctly when positioning this window maHelpText( rText ) { SetType( WINDOW_HELPTEXTWINDOW ); ImplSetMouseTransparent( sal_True ); mnHelpWinStyle = nHelpWinStyle; mnStyle = nStyle; // on windows this will raise the application window, because help windows are system windows now // EnableAlwaysOnTop(); EnableSaveBackground(); const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); SetPointFont( rStyleSettings.GetHelpFont() ); SetTextColor( rStyleSettings.GetHelpTextColor() ); SetTextAlign( ALIGN_TOP ); if ( IsNativeControlSupported( CTRL_TOOLTIP, PART_ENTIRE_CONTROL ) ) { EnableChildTransparentMode( sal_True ); SetParentClipMode( PARENTCLIPMODE_NOCLIP ); SetPaintTransparent( sal_True ); SetBackground(); } else SetBackground( Wallpaper( rStyleSettings.GetHelpColor() ) ); if( rStyleSettings.GetHelpColor().IsDark() ) SetLineColor( COL_WHITE ); else SetLineColor( COL_BLACK ); SetFillColor(); if( mnStyle & QUICKHELP_BIDI_RTL ) { sal_uLong nLayoutMode = GetLayoutMode(); nLayoutMode |= TEXT_LAYOUT_BIDI_RTL | TEXT_LAYOUT_TEXTORIGIN_LEFT; SetLayoutMode( nLayoutMode ); } SetHelpText( rText ); Window::SetHelpText( rText ); ImplSVData* pSVData = ImplGetSVData(); if ( pSVData->maHelpData.mbSetKeyboardHelp ) pSVData->maHelpData.mbKeyboardHelp = sal_True; const HelpSettings& rHelpSettings = pParent->GetSettings().GetHelpSettings(); maShowTimer.SetTimeoutHdl( LINK( this, HelpTextWindow, TimerHdl ) ); maHideTimer.SetTimeoutHdl( LINK( this, HelpTextWindow, TimerHdl ) ); maHideTimer.SetTimeout( rHelpSettings.GetTipTimeout() ); } // ----------------------------------------------------------------------- HelpTextWindow::~HelpTextWindow() { maShowTimer.Stop(); maHideTimer.Stop(); if( this == ImplGetSVData()->maHelpData.mpHelpWin ) ImplGetSVData()->maHelpData.mpHelpWin = NULL; } // ----------------------------------------------------------------------- void HelpTextWindow::SetHelpText( const String& rHelpText ) { maHelpText = rHelpText; if ( mnHelpWinStyle == HELPWINSTYLE_QUICK && maHelpText.Len() < HELPTEXTMAXLEN) { Size aSize; aSize.Height() = GetTextHeight(); if ( mnStyle & QUICKHELP_CTRLTEXT ) aSize.Width() = GetCtrlTextWidth( maHelpText ); else aSize.Width() = GetTextWidth( maHelpText ); maTextRect = Rectangle( Point( HELPTEXTMARGIN_QUICK, HELPTEXTMARGIN_QUICK ), aSize ); } else // HELPWINSTYLE_BALLOON { Point aTmpPoint; sal_uInt16 nCharsInLine = 35 + ((maHelpText.Len()/100)*5); XubString aXXX; aXXX.Fill( nCharsInLine, 'x' ); // average width to have all windows consistent long nWidth = GetTextWidth( aXXX ); Size aTmpSize( nWidth, 0x7FFFFFFF ); Rectangle aTry1( aTmpPoint, aTmpSize ); sal_uInt16 nDrawFlags = TEXT_DRAW_MULTILINE | TEXT_DRAW_WORDBREAK | TEXT_DRAW_LEFT | TEXT_DRAW_TOP; if ( mnStyle & QUICKHELP_CTRLTEXT ) nDrawFlags |= TEXT_DRAW_MNEMONIC; Rectangle aTextRect = GetTextRect( aTry1, maHelpText, nDrawFlags ); // get a better width later... maTextRect = aTextRect; // safety distance... maTextRect.SetPos( Point( HELPTEXTMARGIN_BALLOON, HELPTEXTMARGIN_BALLOON ) ); } Size aSize( CalcOutSize() ); SetOutputSizePixel( aSize ); } // ----------------------------------------------------------------------- void HelpTextWindow::ImplShow() { ImplDelData aDogTag( this ); Show( sal_True, SHOW_NOACTIVATE ); if( !aDogTag.IsDead() ) Update(); } // ----------------------------------------------------------------------- void HelpTextWindow::Paint( const Rectangle& ) { // paint native background bool bNativeOK = false; if ( IsNativeControlSupported( CTRL_TOOLTIP, PART_ENTIRE_CONTROL ) ) { // #i46472# workaround gcc3.3 temporary problem Rectangle aCtrlRegion( Point( 0, 0 ), GetOutputSizePixel() ); ImplControlValue aControlValue; bNativeOK = DrawNativeControl( CTRL_TOOLTIP, PART_ENTIRE_CONTROL, aCtrlRegion, 0, aControlValue, rtl::OUString() ); } // paint text if ( mnHelpWinStyle == HELPWINSTYLE_QUICK && maHelpText.Len() < HELPTEXTMAXLEN) { if ( mnStyle & QUICKHELP_CTRLTEXT ) DrawCtrlText( maTextRect.TopLeft(), maHelpText ); else DrawText( maTextRect.TopLeft(), maHelpText ); } else // HELPWINSTYLE_BALLOON { sal_uInt16 nDrawFlags = TEXT_DRAW_MULTILINE|TEXT_DRAW_WORDBREAK| TEXT_DRAW_LEFT|TEXT_DRAW_TOP; if ( mnStyle & QUICKHELP_CTRLTEXT ) nDrawFlags |= TEXT_DRAW_MNEMONIC; DrawText( maTextRect, maHelpText, nDrawFlags ); } // border if( ! bNativeOK ) { Size aSz = GetOutputSizePixel(); DrawRect( Rectangle( Point(), aSz ) ); if ( mnHelpWinStyle == HELPWINSTYLE_BALLOON ) { aSz.Width() -= 2; aSz.Height() -= 2; Color aColor( GetLineColor() ); SetLineColor( ( COL_GRAY ) ); DrawRect( Rectangle( Point( 1, 1 ), aSz ) ); SetLineColor( aColor ); } } } // ----------------------------------------------------------------------- void HelpTextWindow::ShowHelp( sal_uInt16 nDelayMode ) { sal_uLong nTimeout = 0; if ( nDelayMode != HELPDELAY_NONE ) { // In case of ExtendedHelp display help sooner if ( ImplGetSVData()->maHelpData.mbExtHelpMode ) nTimeout = 15; else { const HelpSettings& rHelpSettings = GetSettings().GetHelpSettings(); if ( mnHelpWinStyle == HELPWINSTYLE_QUICK ) nTimeout = rHelpSettings.GetTipDelay(); else nTimeout = rHelpSettings.GetBalloonDelay(); } if ( nDelayMode == HELPDELAY_SHORT ) nTimeout /= 3; } maShowTimer.SetTimeout( nTimeout ); maShowTimer.Start(); } // ----------------------------------------------------------------------- IMPL_LINK( HelpTextWindow, TimerHdl, Timer*, pTimer) { if ( pTimer == &maShowTimer ) { if ( mnHelpWinStyle == HELPWINSTYLE_QUICK ) { // start auto-hide-timer for non-ShowTip windows ImplSVData* pSVData = ImplGetSVData(); if ( this == pSVData->maHelpData.mpHelpWin ) maHideTimer.Start(); } ImplShow(); } else { DBG_ASSERT( pTimer == &maHideTimer, "HelpTextWindow::TimerHdl with bad Timer" ); ImplDestroyHelpWindow( true ); } return 1; } // ----------------------------------------------------------------------- Size HelpTextWindow::CalcOutSize() const { Size aSz = maTextRect.GetSize(); aSz.Width() += 2*maTextRect.Left(); aSz.Height() += 2*maTextRect.Top(); return aSz; } // ----------------------------------------------------------------------- void HelpTextWindow::RequestHelp( const HelpEvent& /*rHEvt*/ ) { // Just to assure that Window::RequestHelp() is not called by // ShowQuickHelp/ShowBalloonHelp in the HelpTextWindow. } // ----------------------------------------------------------------------- String HelpTextWindow::GetText() const { return maHelpText; } // ----------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > HelpTextWindow::CreateAccessible() { return FloatingWindow::CreateAccessible(); } // ======================================================================= void ImplShowHelpWindow( Window* pParent, sal_uInt16 nHelpWinStyle, sal_uInt16 nStyle, const XubString& rHelpText, const XubString& rStatusText, const Point& rScreenPos, const Rectangle* pHelpArea ) { ImplSVData* pSVData = ImplGetSVData(); if( !rHelpText.Len() && !pSVData->maHelpData.mbRequestingHelp ) return; HelpTextWindow* pHelpWin = pSVData->maHelpData.mpHelpWin; sal_uInt16 nDelayMode = HELPDELAY_NORMAL; if ( pHelpWin ) { DBG_ASSERT( pHelpWin != pParent, "HelpInHelp ?!" ); if ( ( ( pHelpWin->GetHelpText() != rHelpText ) || ( pHelpWin->GetWinStyle() != nHelpWinStyle ) || ( pHelpArea && ( pHelpWin->GetHelpArea() != *pHelpArea ) ) ) && pSVData->maHelpData.mbRequestingHelp ) { // remove help window if no HelpText or other HelpText or // other help mode. but keep it if we are scrolling, ie not requesting help bool bWasVisible = pHelpWin->IsVisible(); if ( bWasVisible ) nDelayMode = HELPDELAY_NONE; // display it quickly if we were already in quick help mode pHelpWin = NULL; ImplDestroyHelpWindow( bWasVisible ); } else { bool const bTextChanged = rHelpText != pHelpWin->GetHelpText(); if ( bTextChanged || ( ( nStyle & QUICKHELP_FORCE_REPOSITION ) != 0 ) ) { Window * pWindow = pHelpWin->GetParent()->ImplGetFrameWindow(); Rectangle aInvRect( pHelpWin->GetWindowExtentsRelative( pWindow ) ); if( pHelpWin->IsVisible() ) pWindow->Invalidate( aInvRect ); pHelpWin->SetHelpText( rHelpText ); // approach mouse position ImplSetHelpWindowPos( pHelpWin, nHelpWinStyle, nStyle, rScreenPos, pHelpArea ); if( pHelpWin->IsVisible() ) pHelpWin->Invalidate(); } } } if ( !pHelpWin && rHelpText.Len() ) { sal_uLong nCurTime = Time::GetSystemTicks(); if ( ( ( nCurTime - pSVData->maHelpData.mnLastHelpHideTime ) < pParent->GetSettings().GetHelpSettings().GetTipDelay() ) || ( ( nStyle & QUICKHELP_NO_DELAY ) != 0 ) ) nDelayMode = HELPDELAY_NONE; DBG_ASSERT( !pHelpWin, "Noch ein HelpWin ?!" ); pHelpWin = new HelpTextWindow( pParent, rHelpText, nHelpWinStyle, nStyle ); pSVData->maHelpData.mpHelpWin = pHelpWin; pHelpWin->SetStatusText( rStatusText ); if ( pHelpArea ) pHelpWin->SetHelpArea( *pHelpArea ); // positioning Size aSz = pHelpWin->CalcOutSize(); pHelpWin->SetOutputSizePixel( aSz ); ImplSetHelpWindowPos( pHelpWin, nHelpWinStyle, nStyle, rScreenPos, pHelpArea ); // if not called from Window::RequestHelp, then without delay... if ( !pSVData->maHelpData.mbRequestingHelp ) nDelayMode = HELPDELAY_NONE; pHelpWin->ShowHelp( nDelayMode ); } } // ----------------------------------------------------------------------- void ImplDestroyHelpWindow( bool bUpdateHideTime ) { ImplSVData* pSVData = ImplGetSVData(); HelpTextWindow* pHelpWin = pSVData->maHelpData.mpHelpWin; if ( pHelpWin ) { Window * pWindow = pHelpWin->GetParent()->ImplGetFrameWindow(); // find out screen area covered by system help window Rectangle aInvRect( pHelpWin->GetWindowExtentsRelative( pWindow ) ); if( pHelpWin->IsVisible() ) pWindow->Invalidate( aInvRect ); pSVData->maHelpData.mpHelpWin = NULL; pSVData->maHelpData.mbKeyboardHelp = sal_False; pHelpWin->Hide(); delete pHelpWin; if( bUpdateHideTime ) pSVData->maHelpData.mnLastHelpHideTime = Time::GetSystemTicks(); } } // ----------------------------------------------------------------------- void ImplSetHelpWindowPos( Window* pHelpWin, sal_uInt16 nHelpWinStyle, sal_uInt16 nStyle, const Point& rPos, const Rectangle* pHelpArea ) { Point aPos = rPos; Size aSz = pHelpWin->GetSizePixel(); Rectangle aScreenRect = pHelpWin->ImplGetFrameWindow()->GetDesktopRectPixel(); aPos = pHelpWin->GetParent()->ImplGetFrameWindow()->OutputToAbsoluteScreenPixel( aPos ); // get mouse screen coords Point mPos( pHelpWin->GetParent()->ImplGetFrameWindow()->GetPointerPosPixel() ); mPos = pHelpWin->GetParent()->ImplGetFrameWindow()->OutputToAbsoluteScreenPixel( mPos ); if ( nHelpWinStyle == HELPWINSTYLE_QUICK ) { if ( !(nStyle & QUICKHELP_NOAUTOPOS) ) { long nScreenHeight = aScreenRect.GetHeight(); aPos.X() -= 4; if ( aPos.Y() > aScreenRect.Top()+nScreenHeight-(nScreenHeight/4) ) aPos.Y() -= aSz.Height()+4; else aPos.Y() += 21; } } else { // If it's the mouse position, move the window slightly // so the mouse pointer does not cover it if ( aPos == mPos ) { aPos.X() += 12; aPos.Y() += 16; } } if ( nStyle & QUICKHELP_NOAUTOPOS ) { if ( pHelpArea ) { // convert help area to screen coords Rectangle devHelpArea( pHelpWin->GetParent()->ImplGetFrameWindow()->OutputToAbsoluteScreenPixel( pHelpArea->TopLeft() ), pHelpWin->GetParent()->ImplGetFrameWindow()->OutputToAbsoluteScreenPixel( pHelpArea->BottomRight() ) ); // Welche Position vom Rechteck? aPos = devHelpArea.Center(); if ( nStyle & QUICKHELP_LEFT ) aPos.X() = devHelpArea.Left(); else if ( nStyle & QUICKHELP_RIGHT ) aPos.X() = devHelpArea.Right(); if ( nStyle & QUICKHELP_TOP ) aPos.Y() = devHelpArea.Top(); else if ( nStyle & QUICKHELP_BOTTOM ) aPos.Y() = devHelpArea.Bottom(); } // Welche Richtung? if ( nStyle & QUICKHELP_LEFT ) ; else if ( nStyle & QUICKHELP_RIGHT ) aPos.X() -= aSz.Width(); else aPos.X() -= aSz.Width()/2; if ( nStyle & QUICKHELP_TOP ) ; else if ( nStyle & QUICKHELP_BOTTOM ) aPos.Y() -= aSz.Height(); else aPos.Y() -= aSz.Height()/2; } if ( aPos.X() < aScreenRect.Left() ) aPos.X() = aScreenRect.Left(); else if ( ( aPos.X() + aSz.Width() ) > aScreenRect.Right() ) aPos.X() = aScreenRect.Right() - aSz.Width(); if ( aPos.Y() < aScreenRect.Top() ) aPos.Y() = aScreenRect.Top(); else if ( ( aPos.Y() + aSz.Height() ) > aScreenRect.Bottom() ) aPos.Y() = aScreenRect.Bottom() - aSz.Height(); if( ! (nStyle & QUICKHELP_NOEVADEPOINTER) ) { /* the remark below should be obsolete by now as the helpwindow should not be focusable, leaving it as a hint. However it is sensible in most conditions to evade the mouse pointer so the content window is fully visible. // the popup must not appear under the mouse // otherwise it would directly be closed due to a focus change... */ Rectangle aHelpRect( aPos, aSz ); if( aHelpRect.IsInside( mPos ) ) { Point delta(2,2); Point pSize( aSz.Width(), aSz.Height() ); Point pTest( mPos - pSize - delta ); if( pTest.X() > aScreenRect.Left() && pTest.Y() > aScreenRect.Top() ) aPos = pTest; else aPos = mPos + delta; } } Window* pWindow = pHelpWin->GetParent()->ImplGetFrameWindow(); aPos = pWindow->AbsoluteScreenToOutputPixel( aPos ); pHelpWin->SetPosPixel( aPos ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ gridfixes: UpdateTip: need a Invalidate after setting the help text, to really show the (possibly) new text /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "tools/debug.hxx" #include "tools/diagnose_ex.h" #include "tools/time.hxx" #include "vcl/window.hxx" #include "vcl/event.hxx" #include "vcl/svapp.hxx" #include "vcl/wrkwin.hxx" #include "vcl/help.hxx" #include "helpwin.hxx" #include "svdata.hxx" // ======================================================================= #define HELPWINSTYLE_QUICK 0 #define HELPWINSTYLE_BALLOON 1 #define HELPTEXTMARGIN_QUICK 3 #define HELPTEXTMARGIN_BALLOON 6 #define HELPDELAY_NORMAL 1 #define HELPDELAY_SHORT 2 #define HELPDELAY_NONE 3 #define HELPTEXTMAXLEN 150 // ======================================================================= Help::Help() { } Help::~Help() { } // ----------------------------------------------------------------------- void Help::OpenHelpAgent( const rtl::OString& ) { } // ----------------------------------------------------------------------- sal_Bool Help::Start( const XubString&, const Window* ) { return sal_False; } sal_Bool Help::SearchKeyword( const XubString& ) { return sal_False; } // ----------------------------------------------------------------------- XubString Help::GetHelpText( const String&, const Window* ) { return ImplGetSVEmptyStr(); } // ----------------------------------------------------------------------- void Help::EnableContextHelp() { ImplGetSVData()->maHelpData.mbContextHelp = sal_True; } // ----------------------------------------------------------------------- void Help::DisableContextHelp() { ImplGetSVData()->maHelpData.mbContextHelp = sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::IsContextHelpEnabled() { return ImplGetSVData()->maHelpData.mbContextHelp; } // ----------------------------------------------------------------------- void Help::EnableExtHelp() { ImplGetSVData()->maHelpData.mbExtHelp = sal_True; } // ----------------------------------------------------------------------- void Help::DisableExtHelp() { ImplGetSVData()->maHelpData.mbExtHelp = sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::IsExtHelpEnabled() { return ImplGetSVData()->maHelpData.mbExtHelp; } // ----------------------------------------------------------------------- sal_Bool Help::StartExtHelp() { ImplSVData* pSVData = ImplGetSVData(); if ( pSVData->maHelpData.mbExtHelp && !pSVData->maHelpData.mbExtHelpMode ) { pSVData->maHelpData.mbExtHelpMode = sal_True; pSVData->maHelpData.mbOldBalloonMode = pSVData->maHelpData.mbBalloonHelp; pSVData->maHelpData.mbBalloonHelp = sal_True; if ( pSVData->maWinData.mpAppWin ) pSVData->maWinData.mpAppWin->ImplGenerateMouseMove(); return sal_True; } return sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::EndExtHelp() { ImplSVData* pSVData = ImplGetSVData(); if ( pSVData->maHelpData.mbExtHelp && pSVData->maHelpData.mbExtHelpMode ) { pSVData->maHelpData.mbExtHelpMode = sal_False; pSVData->maHelpData.mbBalloonHelp = pSVData->maHelpData.mbOldBalloonMode; if ( pSVData->maWinData.mpAppWin ) pSVData->maWinData.mpAppWin->ImplGenerateMouseMove(); return sal_True; } return sal_False; } // ----------------------------------------------------------------------- void Help::EnableBalloonHelp() { ImplGetSVData()->maHelpData.mbBalloonHelp = sal_True; } // ----------------------------------------------------------------------- void Help::DisableBalloonHelp() { ImplGetSVData()->maHelpData.mbBalloonHelp = sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::IsBalloonHelpEnabled() { return ImplGetSVData()->maHelpData.mbBalloonHelp; } // ----------------------------------------------------------------------- sal_Bool Help::ShowBalloon( Window* pParent, const Point& rScreenPos, const XubString& rHelpText ) { ImplShowHelpWindow( pParent, HELPWINSTYLE_BALLOON, 0, rHelpText, ImplGetSVEmptyStr(), rScreenPos ); return sal_True; } // ----------------------------------------------------------------------- sal_Bool Help::ShowBalloon( Window* pParent, const Point& rScreenPos, const Rectangle& rRect, const XubString& rHelpText ) { ImplShowHelpWindow( pParent, HELPWINSTYLE_BALLOON, 0, rHelpText, ImplGetSVEmptyStr(), rScreenPos, &rRect ); return sal_True; } // ----------------------------------------------------------------------- void Help::EnableQuickHelp() { ImplGetSVData()->maHelpData.mbQuickHelp = sal_True; } // ----------------------------------------------------------------------- void Help::DisableQuickHelp() { ImplGetSVData()->maHelpData.mbQuickHelp = sal_False; } // ----------------------------------------------------------------------- sal_Bool Help::IsQuickHelpEnabled() { return ImplGetSVData()->maHelpData.mbQuickHelp; } // ----------------------------------------------------------------------- sal_Bool Help::ShowQuickHelp( Window* pParent, const Rectangle& rScreenRect, const XubString& rHelpText, const XubString& rLongHelpText, sal_uInt16 nStyle ) { ImplShowHelpWindow( pParent, HELPWINSTYLE_QUICK, nStyle, rHelpText, rLongHelpText, pParent->OutputToScreenPixel( pParent->GetPointerPosPixel() ), &rScreenRect ); return sal_True; } // ----------------------------------------------------------------------- void Help::HideBalloonAndQuickHelp() { HelpTextWindow const * pHelpWin = ImplGetSVData()->maHelpData.mpHelpWin; bool const bIsVisible = ( pHelpWin != NULL ) && pHelpWin->IsVisible(); ImplDestroyHelpWindow( bIsVisible ); } // ----------------------------------------------------------------------- sal_uIntPtr Help::ShowTip( Window* pParent, const Rectangle& rScreenRect, const XubString& rText, sal_uInt16 nStyle ) { sal_uInt16 nHelpWinStyle = ( ( nStyle & QUICKHELP_TIP_STYLE_BALLOON ) != 0 ) ? HELPWINSTYLE_BALLOON : HELPWINSTYLE_QUICK; HelpTextWindow* pHelpWin = new HelpTextWindow( pParent, rText, nHelpWinStyle, nStyle ); sal_uIntPtr nId = reinterpret_cast< sal_uIntPtr >( pHelpWin ); UpdateTip( nId, pParent, rScreenRect, rText ); pHelpWin->ShowHelp( HELPDELAY_NONE ); return nId; } // ----------------------------------------------------------------------- void Help::UpdateTip( sal_uIntPtr nId, Window* pParent, const Rectangle& rScreenRect, const XubString& rText ) { HelpTextWindow* pHelpWin = reinterpret_cast< HelpTextWindow* >( nId ); ENSURE_OR_RETURN_VOID( pHelpWin != NULL, "Help::UpdateTip: invalid ID!" ); Size aSz = pHelpWin->CalcOutSize(); pHelpWin->SetOutputSizePixel( aSz ); ImplSetHelpWindowPos( pHelpWin, pHelpWin->GetWinStyle(), pHelpWin->GetStyle(), pParent->OutputToScreenPixel( pParent->GetPointerPosPixel() ), &rScreenRect ); pHelpWin->SetHelpText( rText ); pHelpWin->Invalidate(); } // ----------------------------------------------------------------------- void Help::HideTip( sal_uLong nId ) { HelpTextWindow* pHelpWin = (HelpTextWindow*)nId; Window* pFrameWindow = pHelpWin->ImplGetFrameWindow(); pHelpWin->Hide(); // trigger update, so that a Paint is instantly triggered since we do not save the background pFrameWindow->ImplUpdateAll(); delete pHelpWin; ImplGetSVData()->maHelpData.mnLastHelpHideTime = Time::GetSystemTicks(); } // ======================================================================= HelpTextWindow::HelpTextWindow( Window* pParent, const XubString& rText, sal_uInt16 nHelpWinStyle, sal_uInt16 nStyle ) : //FloatingWindow( pParent->ImplGetFrameWindow(), WB_SYSTEMWINDOW ), FloatingWindow( pParent, WB_SYSTEMWINDOW|WB_TOOLTIPWIN ), // #105827# if we change the parent, mirroring will not work correctly when positioning this window maHelpText( rText ) { SetType( WINDOW_HELPTEXTWINDOW ); ImplSetMouseTransparent( sal_True ); mnHelpWinStyle = nHelpWinStyle; mnStyle = nStyle; // on windows this will raise the application window, because help windows are system windows now // EnableAlwaysOnTop(); EnableSaveBackground(); const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); SetPointFont( rStyleSettings.GetHelpFont() ); SetTextColor( rStyleSettings.GetHelpTextColor() ); SetTextAlign( ALIGN_TOP ); if ( IsNativeControlSupported( CTRL_TOOLTIP, PART_ENTIRE_CONTROL ) ) { EnableChildTransparentMode( sal_True ); SetParentClipMode( PARENTCLIPMODE_NOCLIP ); SetPaintTransparent( sal_True ); SetBackground(); } else SetBackground( Wallpaper( rStyleSettings.GetHelpColor() ) ); if( rStyleSettings.GetHelpColor().IsDark() ) SetLineColor( COL_WHITE ); else SetLineColor( COL_BLACK ); SetFillColor(); if( mnStyle & QUICKHELP_BIDI_RTL ) { sal_uLong nLayoutMode = GetLayoutMode(); nLayoutMode |= TEXT_LAYOUT_BIDI_RTL | TEXT_LAYOUT_TEXTORIGIN_LEFT; SetLayoutMode( nLayoutMode ); } SetHelpText( rText ); Window::SetHelpText( rText ); ImplSVData* pSVData = ImplGetSVData(); if ( pSVData->maHelpData.mbSetKeyboardHelp ) pSVData->maHelpData.mbKeyboardHelp = sal_True; const HelpSettings& rHelpSettings = pParent->GetSettings().GetHelpSettings(); maShowTimer.SetTimeoutHdl( LINK( this, HelpTextWindow, TimerHdl ) ); maHideTimer.SetTimeoutHdl( LINK( this, HelpTextWindow, TimerHdl ) ); maHideTimer.SetTimeout( rHelpSettings.GetTipTimeout() ); } // ----------------------------------------------------------------------- HelpTextWindow::~HelpTextWindow() { maShowTimer.Stop(); maHideTimer.Stop(); if( this == ImplGetSVData()->maHelpData.mpHelpWin ) ImplGetSVData()->maHelpData.mpHelpWin = NULL; } // ----------------------------------------------------------------------- void HelpTextWindow::SetHelpText( const String& rHelpText ) { maHelpText = rHelpText; if ( mnHelpWinStyle == HELPWINSTYLE_QUICK && maHelpText.Len() < HELPTEXTMAXLEN) { Size aSize; aSize.Height() = GetTextHeight(); if ( mnStyle & QUICKHELP_CTRLTEXT ) aSize.Width() = GetCtrlTextWidth( maHelpText ); else aSize.Width() = GetTextWidth( maHelpText ); maTextRect = Rectangle( Point( HELPTEXTMARGIN_QUICK, HELPTEXTMARGIN_QUICK ), aSize ); } else // HELPWINSTYLE_BALLOON { Point aTmpPoint; sal_uInt16 nCharsInLine = 35 + ((maHelpText.Len()/100)*5); XubString aXXX; aXXX.Fill( nCharsInLine, 'x' ); // average width to have all windows consistent long nWidth = GetTextWidth( aXXX ); Size aTmpSize( nWidth, 0x7FFFFFFF ); Rectangle aTry1( aTmpPoint, aTmpSize ); sal_uInt16 nDrawFlags = TEXT_DRAW_MULTILINE | TEXT_DRAW_WORDBREAK | TEXT_DRAW_LEFT | TEXT_DRAW_TOP; if ( mnStyle & QUICKHELP_CTRLTEXT ) nDrawFlags |= TEXT_DRAW_MNEMONIC; Rectangle aTextRect = GetTextRect( aTry1, maHelpText, nDrawFlags ); // get a better width later... maTextRect = aTextRect; // safety distance... maTextRect.SetPos( Point( HELPTEXTMARGIN_BALLOON, HELPTEXTMARGIN_BALLOON ) ); } Size aSize( CalcOutSize() ); SetOutputSizePixel( aSize ); } // ----------------------------------------------------------------------- void HelpTextWindow::ImplShow() { ImplDelData aDogTag( this ); Show( sal_True, SHOW_NOACTIVATE ); if( !aDogTag.IsDead() ) Update(); } // ----------------------------------------------------------------------- void HelpTextWindow::Paint( const Rectangle& ) { // paint native background bool bNativeOK = false; if ( IsNativeControlSupported( CTRL_TOOLTIP, PART_ENTIRE_CONTROL ) ) { // #i46472# workaround gcc3.3 temporary problem Rectangle aCtrlRegion( Point( 0, 0 ), GetOutputSizePixel() ); ImplControlValue aControlValue; bNativeOK = DrawNativeControl( CTRL_TOOLTIP, PART_ENTIRE_CONTROL, aCtrlRegion, 0, aControlValue, rtl::OUString() ); } // paint text if ( mnHelpWinStyle == HELPWINSTYLE_QUICK && maHelpText.Len() < HELPTEXTMAXLEN) { if ( mnStyle & QUICKHELP_CTRLTEXT ) DrawCtrlText( maTextRect.TopLeft(), maHelpText ); else DrawText( maTextRect.TopLeft(), maHelpText ); } else // HELPWINSTYLE_BALLOON { sal_uInt16 nDrawFlags = TEXT_DRAW_MULTILINE|TEXT_DRAW_WORDBREAK| TEXT_DRAW_LEFT|TEXT_DRAW_TOP; if ( mnStyle & QUICKHELP_CTRLTEXT ) nDrawFlags |= TEXT_DRAW_MNEMONIC; DrawText( maTextRect, maHelpText, nDrawFlags ); } // border if( ! bNativeOK ) { Size aSz = GetOutputSizePixel(); DrawRect( Rectangle( Point(), aSz ) ); if ( mnHelpWinStyle == HELPWINSTYLE_BALLOON ) { aSz.Width() -= 2; aSz.Height() -= 2; Color aColor( GetLineColor() ); SetLineColor( ( COL_GRAY ) ); DrawRect( Rectangle( Point( 1, 1 ), aSz ) ); SetLineColor( aColor ); } } } // ----------------------------------------------------------------------- void HelpTextWindow::ShowHelp( sal_uInt16 nDelayMode ) { sal_uLong nTimeout = 0; if ( nDelayMode != HELPDELAY_NONE ) { // In case of ExtendedHelp display help sooner if ( ImplGetSVData()->maHelpData.mbExtHelpMode ) nTimeout = 15; else { const HelpSettings& rHelpSettings = GetSettings().GetHelpSettings(); if ( mnHelpWinStyle == HELPWINSTYLE_QUICK ) nTimeout = rHelpSettings.GetTipDelay(); else nTimeout = rHelpSettings.GetBalloonDelay(); } if ( nDelayMode == HELPDELAY_SHORT ) nTimeout /= 3; } maShowTimer.SetTimeout( nTimeout ); maShowTimer.Start(); } // ----------------------------------------------------------------------- IMPL_LINK( HelpTextWindow, TimerHdl, Timer*, pTimer) { if ( pTimer == &maShowTimer ) { if ( mnHelpWinStyle == HELPWINSTYLE_QUICK ) { // start auto-hide-timer for non-ShowTip windows ImplSVData* pSVData = ImplGetSVData(); if ( this == pSVData->maHelpData.mpHelpWin ) maHideTimer.Start(); } ImplShow(); } else { DBG_ASSERT( pTimer == &maHideTimer, "HelpTextWindow::TimerHdl with bad Timer" ); ImplDestroyHelpWindow( true ); } return 1; } // ----------------------------------------------------------------------- Size HelpTextWindow::CalcOutSize() const { Size aSz = maTextRect.GetSize(); aSz.Width() += 2*maTextRect.Left(); aSz.Height() += 2*maTextRect.Top(); return aSz; } // ----------------------------------------------------------------------- void HelpTextWindow::RequestHelp( const HelpEvent& /*rHEvt*/ ) { // Just to assure that Window::RequestHelp() is not called by // ShowQuickHelp/ShowBalloonHelp in the HelpTextWindow. } // ----------------------------------------------------------------------- String HelpTextWindow::GetText() const { return maHelpText; } // ----------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > HelpTextWindow::CreateAccessible() { return FloatingWindow::CreateAccessible(); } // ======================================================================= void ImplShowHelpWindow( Window* pParent, sal_uInt16 nHelpWinStyle, sal_uInt16 nStyle, const XubString& rHelpText, const XubString& rStatusText, const Point& rScreenPos, const Rectangle* pHelpArea ) { ImplSVData* pSVData = ImplGetSVData(); if( !rHelpText.Len() && !pSVData->maHelpData.mbRequestingHelp ) return; HelpTextWindow* pHelpWin = pSVData->maHelpData.mpHelpWin; sal_uInt16 nDelayMode = HELPDELAY_NORMAL; if ( pHelpWin ) { DBG_ASSERT( pHelpWin != pParent, "HelpInHelp ?!" ); if ( ( ( pHelpWin->GetHelpText() != rHelpText ) || ( pHelpWin->GetWinStyle() != nHelpWinStyle ) || ( pHelpArea && ( pHelpWin->GetHelpArea() != *pHelpArea ) ) ) && pSVData->maHelpData.mbRequestingHelp ) { // remove help window if no HelpText or other HelpText or // other help mode. but keep it if we are scrolling, ie not requesting help bool bWasVisible = pHelpWin->IsVisible(); if ( bWasVisible ) nDelayMode = HELPDELAY_NONE; // display it quickly if we were already in quick help mode pHelpWin = NULL; ImplDestroyHelpWindow( bWasVisible ); } else { bool const bTextChanged = rHelpText != pHelpWin->GetHelpText(); if ( bTextChanged || ( ( nStyle & QUICKHELP_FORCE_REPOSITION ) != 0 ) ) { Window * pWindow = pHelpWin->GetParent()->ImplGetFrameWindow(); Rectangle aInvRect( pHelpWin->GetWindowExtentsRelative( pWindow ) ); if( pHelpWin->IsVisible() ) pWindow->Invalidate( aInvRect ); pHelpWin->SetHelpText( rHelpText ); // approach mouse position ImplSetHelpWindowPos( pHelpWin, nHelpWinStyle, nStyle, rScreenPos, pHelpArea ); if( pHelpWin->IsVisible() ) pHelpWin->Invalidate(); } } } if ( !pHelpWin && rHelpText.Len() ) { sal_uLong nCurTime = Time::GetSystemTicks(); if ( ( ( nCurTime - pSVData->maHelpData.mnLastHelpHideTime ) < pParent->GetSettings().GetHelpSettings().GetTipDelay() ) || ( ( nStyle & QUICKHELP_NO_DELAY ) != 0 ) ) nDelayMode = HELPDELAY_NONE; DBG_ASSERT( !pHelpWin, "Noch ein HelpWin ?!" ); pHelpWin = new HelpTextWindow( pParent, rHelpText, nHelpWinStyle, nStyle ); pSVData->maHelpData.mpHelpWin = pHelpWin; pHelpWin->SetStatusText( rStatusText ); if ( pHelpArea ) pHelpWin->SetHelpArea( *pHelpArea ); // positioning Size aSz = pHelpWin->CalcOutSize(); pHelpWin->SetOutputSizePixel( aSz ); ImplSetHelpWindowPos( pHelpWin, nHelpWinStyle, nStyle, rScreenPos, pHelpArea ); // if not called from Window::RequestHelp, then without delay... if ( !pSVData->maHelpData.mbRequestingHelp ) nDelayMode = HELPDELAY_NONE; pHelpWin->ShowHelp( nDelayMode ); } } // ----------------------------------------------------------------------- void ImplDestroyHelpWindow( bool bUpdateHideTime ) { ImplSVData* pSVData = ImplGetSVData(); HelpTextWindow* pHelpWin = pSVData->maHelpData.mpHelpWin; if ( pHelpWin ) { Window * pWindow = pHelpWin->GetParent()->ImplGetFrameWindow(); // find out screen area covered by system help window Rectangle aInvRect( pHelpWin->GetWindowExtentsRelative( pWindow ) ); if( pHelpWin->IsVisible() ) pWindow->Invalidate( aInvRect ); pSVData->maHelpData.mpHelpWin = NULL; pSVData->maHelpData.mbKeyboardHelp = sal_False; pHelpWin->Hide(); delete pHelpWin; if( bUpdateHideTime ) pSVData->maHelpData.mnLastHelpHideTime = Time::GetSystemTicks(); } } // ----------------------------------------------------------------------- void ImplSetHelpWindowPos( Window* pHelpWin, sal_uInt16 nHelpWinStyle, sal_uInt16 nStyle, const Point& rPos, const Rectangle* pHelpArea ) { Point aPos = rPos; Size aSz = pHelpWin->GetSizePixel(); Rectangle aScreenRect = pHelpWin->ImplGetFrameWindow()->GetDesktopRectPixel(); aPos = pHelpWin->GetParent()->ImplGetFrameWindow()->OutputToAbsoluteScreenPixel( aPos ); // get mouse screen coords Point mPos( pHelpWin->GetParent()->ImplGetFrameWindow()->GetPointerPosPixel() ); mPos = pHelpWin->GetParent()->ImplGetFrameWindow()->OutputToAbsoluteScreenPixel( mPos ); if ( nHelpWinStyle == HELPWINSTYLE_QUICK ) { if ( !(nStyle & QUICKHELP_NOAUTOPOS) ) { long nScreenHeight = aScreenRect.GetHeight(); aPos.X() -= 4; if ( aPos.Y() > aScreenRect.Top()+nScreenHeight-(nScreenHeight/4) ) aPos.Y() -= aSz.Height()+4; else aPos.Y() += 21; } } else { // If it's the mouse position, move the window slightly // so the mouse pointer does not cover it if ( aPos == mPos ) { aPos.X() += 12; aPos.Y() += 16; } } if ( nStyle & QUICKHELP_NOAUTOPOS ) { if ( pHelpArea ) { // convert help area to screen coords Rectangle devHelpArea( pHelpWin->GetParent()->ImplGetFrameWindow()->OutputToAbsoluteScreenPixel( pHelpArea->TopLeft() ), pHelpWin->GetParent()->ImplGetFrameWindow()->OutputToAbsoluteScreenPixel( pHelpArea->BottomRight() ) ); // Welche Position vom Rechteck? aPos = devHelpArea.Center(); if ( nStyle & QUICKHELP_LEFT ) aPos.X() = devHelpArea.Left(); else if ( nStyle & QUICKHELP_RIGHT ) aPos.X() = devHelpArea.Right(); if ( nStyle & QUICKHELP_TOP ) aPos.Y() = devHelpArea.Top(); else if ( nStyle & QUICKHELP_BOTTOM ) aPos.Y() = devHelpArea.Bottom(); } // Welche Richtung? if ( nStyle & QUICKHELP_LEFT ) ; else if ( nStyle & QUICKHELP_RIGHT ) aPos.X() -= aSz.Width(); else aPos.X() -= aSz.Width()/2; if ( nStyle & QUICKHELP_TOP ) ; else if ( nStyle & QUICKHELP_BOTTOM ) aPos.Y() -= aSz.Height(); else aPos.Y() -= aSz.Height()/2; } if ( aPos.X() < aScreenRect.Left() ) aPos.X() = aScreenRect.Left(); else if ( ( aPos.X() + aSz.Width() ) > aScreenRect.Right() ) aPos.X() = aScreenRect.Right() - aSz.Width(); if ( aPos.Y() < aScreenRect.Top() ) aPos.Y() = aScreenRect.Top(); else if ( ( aPos.Y() + aSz.Height() ) > aScreenRect.Bottom() ) aPos.Y() = aScreenRect.Bottom() - aSz.Height(); if( ! (nStyle & QUICKHELP_NOEVADEPOINTER) ) { /* the remark below should be obsolete by now as the helpwindow should not be focusable, leaving it as a hint. However it is sensible in most conditions to evade the mouse pointer so the content window is fully visible. // the popup must not appear under the mouse // otherwise it would directly be closed due to a focus change... */ Rectangle aHelpRect( aPos, aSz ); if( aHelpRect.IsInside( mPos ) ) { Point delta(2,2); Point pSize( aSz.Width(), aSz.Height() ); Point pTest( mPos - pSize - delta ); if( pTest.X() > aScreenRect.Left() && pTest.Y() > aScreenRect.Top() ) aPos = pTest; else aPos = mPos + delta; } } Window* pWindow = pHelpWin->GetParent()->ImplGetFrameWindow(); aPos = pWindow->AbsoluteScreenToOutputPixel( aPos ); pHelpWin->SetPosPixel( aPos ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* This file is part of Zanshin Copyright 2014 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "akonaditagqueries.h" #include "akonadicollectionfetchjobinterface.h" #include "akonadiitemfetchjobinterface.h" #include "akonaditagfetchjobinterface.h" #include "akonadimonitorimpl.h" #include "akonadiserializer.h" #include "akonadistorage.h" #include "utils/jobhandler.h" using namespace Akonadi; TagQueries::TagQueries(QObject *parent) : QObject(parent), m_storage(new Storage), m_serializer(new Serializer), m_monitor(new MonitorImpl), m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes), m_ownInterfaces(true) { connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag))); connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item))); connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item))); connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item))); } TagQueries::TagQueries(StorageInterface *storage, SerializerInterface *serializer, MonitorInterface *monitor) : m_storage(storage), m_serializer(serializer), m_monitor(monitor), m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes), m_ownInterfaces(false) { connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag))); connect(monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item))); connect(monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item))); connect(monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item))); } TagQueries::~TagQueries() { if (m_ownInterfaces) { delete m_storage; delete m_serializer; delete m_monitor; } } void TagQueries::setApplicationMode(TagQueries::ApplicationMode mode) { if (mode == TasksOnly) { m_fetchContentTypeFilter = StorageInterface::Tasks; } else if (mode == NotesOnly) { m_fetchContentTypeFilter = StorageInterface::Notes; } } TagQueries::TagResult::Ptr TagQueries::findAll() const { if (!m_findAll) { { TagQueries *self = const_cast<TagQueries*>(this); self->m_findAll = self->createTagQuery(); } m_findAll->setFetchFunction([this] (const TagQuery::AddFunction &add) { TagFetchJobInterface *job = m_storage->fetchTags(); Utils::JobHandler::install(job->kjob(), [this, job, add] { for (Akonadi::Tag tag : job->tags()) add(tag); }); }); m_findAll->setConvertFunction([this] (const Akonadi::Tag &tag) { return m_serializer->createTagFromAkonadiTag(tag); }); m_findAll->setUpdateFunction([this] (const Akonadi::Tag &akonadiTag, Domain::Tag::Ptr &tag) { m_serializer->updateTagFromAkonadiTag(tag, akonadiTag); }); m_findAll->setPredicateFunction([this] (const Akonadi::Tag &akonadiTag) { return akonadiTag.type() == Akonadi::Tag::PLAIN; }); m_findAll->setRepresentsFunction([this] (const Akonadi::Tag &akonadiTag, const Domain::Tag::Ptr &tag) { return m_serializer->representsAkonadiTag(tag, akonadiTag); }); } return m_findAll->result(); } TagQueries::ArtifactResult::Ptr TagQueries::findTopLevelArtifacts(Domain::Tag::Ptr tag) const { Akonadi::Tag akonadiTag = m_serializer->createAkonadiTagFromTag(tag); if (!m_findTopLevel.contains(akonadiTag.id())) { ArtifactQuery::Ptr query; { TagQueries *self = const_cast<TagQueries*>(this); query = self->createArtifactQuery(); self->m_findTopLevel.insert(akonadiTag.id(), query); } query->setFetchFunction([this, akonadiTag] (const ArtifactQuery::AddFunction &add) { CollectionFetchJobInterface *job = m_storage->fetchCollections(Akonadi::Collection::root(), StorageInterface::Recursive, m_fetchContentTypeFilter); Utils::JobHandler::install(job->kjob(), [this, job, add] { if (job->kjob()->error() != KJob::NoError) return; for (auto collection : job->collections()) { ItemFetchJobInterface *job = m_storage->fetchItems(collection); Utils::JobHandler::install(job->kjob(), [this, job, add] { if (job->kjob()->error() != KJob::NoError) return; for (auto item : job->items()) add(item); }); } }); }); query->setConvertFunction([this] (const Akonadi::Item &item) { if (m_serializer->isTaskItem(item)) { auto task = m_serializer->createTaskFromItem(item); return Domain::Artifact::Ptr(task); } else if (m_serializer->isNoteItem(item)) { auto note = m_serializer->createNoteFromItem(item); return Domain::Artifact::Ptr(note); } //The conversion must never fail, otherwise we create an endless loop (child of invalid node is invalid). //We therefore catch this case in the predicate. Q_ASSERT(false); return Domain::Artifact::Ptr(); }); query->setUpdateFunction([this] (const Akonadi::Item &item, Domain::Artifact::Ptr &artifact) { if (auto task = artifact.dynamicCast<Domain::Task>()) { m_serializer->updateTaskFromItem(task, item); } else if (auto note = artifact.dynamicCast<Domain::Note>()) { m_serializer->updateNoteFromItem(note, item); } }); query->setPredicateFunction([this, tag] (const Akonadi::Item &item) { if (m_serializer->isTaskItem(item)) { return false; } if (!m_serializer->isNoteItem(item)) { return false; } return m_serializer->isTagChild(tag, item); }); query->setRepresentsFunction([this] (const Akonadi::Item &item, const Domain::Artifact::Ptr &artifact) { return m_serializer->representsItem(artifact, item); }); } return m_findTopLevel.value(akonadiTag.id())->result(); } void TagQueries::onTagAdded(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onAdded(tag); } void TagQueries::onTagRemoved(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onRemoved(tag); } void TagQueries::onTagChanged(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onChanged(tag); } void TagQueries::onItemAdded(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onAdded(item); } void TagQueries::onItemRemoved(const Item &item) { Q_UNUSED(item); } void TagQueries::onItemChanged(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onChanged(item); } TagQueries::TagQuery::Ptr TagQueries::createTagQuery() { auto query = TagQueries::TagQuery::Ptr::create(); m_tagQueries << query; return query; } TagQueries::ArtifactQuery::Ptr TagQueries::createArtifactQuery() { auto query = TagQueries::ArtifactQuery::Ptr::create(); m_artifactQueries << query; return query; } TagQueries: react to item removals /* This file is part of Zanshin Copyright 2014 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "akonaditagqueries.h" #include "akonadicollectionfetchjobinterface.h" #include "akonadiitemfetchjobinterface.h" #include "akonaditagfetchjobinterface.h" #include "akonadimonitorimpl.h" #include "akonadiserializer.h" #include "akonadistorage.h" #include "utils/jobhandler.h" using namespace Akonadi; TagQueries::TagQueries(QObject *parent) : QObject(parent), m_storage(new Storage), m_serializer(new Serializer), m_monitor(new MonitorImpl), m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes), m_ownInterfaces(true) { connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag))); connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item))); connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item))); connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item))); } TagQueries::TagQueries(StorageInterface *storage, SerializerInterface *serializer, MonitorInterface *monitor) : m_storage(storage), m_serializer(serializer), m_monitor(monitor), m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes), m_ownInterfaces(false) { connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag))); connect(monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item))); connect(monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item))); connect(monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item))); } TagQueries::~TagQueries() { if (m_ownInterfaces) { delete m_storage; delete m_serializer; delete m_monitor; } } void TagQueries::setApplicationMode(TagQueries::ApplicationMode mode) { if (mode == TasksOnly) { m_fetchContentTypeFilter = StorageInterface::Tasks; } else if (mode == NotesOnly) { m_fetchContentTypeFilter = StorageInterface::Notes; } } TagQueries::TagResult::Ptr TagQueries::findAll() const { if (!m_findAll) { { TagQueries *self = const_cast<TagQueries*>(this); self->m_findAll = self->createTagQuery(); } m_findAll->setFetchFunction([this] (const TagQuery::AddFunction &add) { TagFetchJobInterface *job = m_storage->fetchTags(); Utils::JobHandler::install(job->kjob(), [this, job, add] { for (Akonadi::Tag tag : job->tags()) add(tag); }); }); m_findAll->setConvertFunction([this] (const Akonadi::Tag &tag) { return m_serializer->createTagFromAkonadiTag(tag); }); m_findAll->setUpdateFunction([this] (const Akonadi::Tag &akonadiTag, Domain::Tag::Ptr &tag) { m_serializer->updateTagFromAkonadiTag(tag, akonadiTag); }); m_findAll->setPredicateFunction([this] (const Akonadi::Tag &akonadiTag) { return akonadiTag.type() == Akonadi::Tag::PLAIN; }); m_findAll->setRepresentsFunction([this] (const Akonadi::Tag &akonadiTag, const Domain::Tag::Ptr &tag) { return m_serializer->representsAkonadiTag(tag, akonadiTag); }); } return m_findAll->result(); } TagQueries::ArtifactResult::Ptr TagQueries::findTopLevelArtifacts(Domain::Tag::Ptr tag) const { Akonadi::Tag akonadiTag = m_serializer->createAkonadiTagFromTag(tag); if (!m_findTopLevel.contains(akonadiTag.id())) { ArtifactQuery::Ptr query; { TagQueries *self = const_cast<TagQueries*>(this); query = self->createArtifactQuery(); self->m_findTopLevel.insert(akonadiTag.id(), query); } query->setFetchFunction([this, akonadiTag] (const ArtifactQuery::AddFunction &add) { CollectionFetchJobInterface *job = m_storage->fetchCollections(Akonadi::Collection::root(), StorageInterface::Recursive, m_fetchContentTypeFilter); Utils::JobHandler::install(job->kjob(), [this, job, add] { if (job->kjob()->error() != KJob::NoError) return; for (auto collection : job->collections()) { ItemFetchJobInterface *job = m_storage->fetchItems(collection); Utils::JobHandler::install(job->kjob(), [this, job, add] { if (job->kjob()->error() != KJob::NoError) return; for (auto item : job->items()) add(item); }); } }); }); query->setConvertFunction([this] (const Akonadi::Item &item) { if (m_serializer->isTaskItem(item)) { auto task = m_serializer->createTaskFromItem(item); return Domain::Artifact::Ptr(task); } else if (m_serializer->isNoteItem(item)) { auto note = m_serializer->createNoteFromItem(item); return Domain::Artifact::Ptr(note); } //The conversion must never fail, otherwise we create an endless loop (child of invalid node is invalid). //We therefore catch this case in the predicate. Q_ASSERT(false); return Domain::Artifact::Ptr(); }); query->setUpdateFunction([this] (const Akonadi::Item &item, Domain::Artifact::Ptr &artifact) { if (auto task = artifact.dynamicCast<Domain::Task>()) { m_serializer->updateTaskFromItem(task, item); } else if (auto note = artifact.dynamicCast<Domain::Note>()) { m_serializer->updateNoteFromItem(note, item); } }); query->setPredicateFunction([this, tag] (const Akonadi::Item &item) { if (m_serializer->isTaskItem(item)) { return false; } if (!m_serializer->isNoteItem(item)) { return false; } return m_serializer->isTagChild(tag, item); }); query->setRepresentsFunction([this] (const Akonadi::Item &item, const Domain::Artifact::Ptr &artifact) { return m_serializer->representsItem(artifact, item); }); } return m_findTopLevel.value(akonadiTag.id())->result(); } void TagQueries::onTagAdded(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onAdded(tag); } void TagQueries::onTagRemoved(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onRemoved(tag); } void TagQueries::onTagChanged(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onChanged(tag); } void TagQueries::onItemAdded(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onAdded(item); } void TagQueries::onItemRemoved(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onRemoved(item); } void TagQueries::onItemChanged(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onChanged(item); } TagQueries::TagQuery::Ptr TagQueries::createTagQuery() { auto query = TagQueries::TagQuery::Ptr::create(); m_tagQueries << query; return query; } TagQueries::ArtifactQuery::Ptr TagQueries::createArtifactQuery() { auto query = TagQueries::ArtifactQuery::Ptr::create(); m_artifactQueries << query; return query; }
/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "audioloader.h" #include "algorithmfactory.h" using namespace std; namespace essentia { namespace streaming { const char* AudioLoader::name = "AudioLoader"; const char* AudioLoader::description = DOC("This algorithm loads the single audio stream contained in the given audio or video file, as well as the samplerate and the number of channels. Supported formats are all those supported by the ffmpeg library, which is, virtually everything.\n" "\n" "This algorithm will throw an exception if it hasn't been properly configured which is normally due to not specifying a valid filename.\n" "Note: ogg files are decoded in reverse phase, due to a (possible) bug in the ffmpeg library.\n" "\n" "References:\n" " [1] WAV - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Wav\n" " [2] Audio Interchange File Format - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Aiff\n" " [3] Free Lossless Audio Codec - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Flac\n" " [4] Vorbis - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Vorbis\n" " [5] MP3 - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Mp3"); AudioLoader::~AudioLoader() { closeAudioFile(); av_freep(&_buffer); #if LIBAVCODEC_VERSION_INT >= AVCODEC_AUDIO_DECODE4 av_freep(&_decodedFrame); #endif #if !HAVE_SWRESAMPLE av_freep(&_buff1); av_freep(&_buff2); if (_audioConvert) { av_audio_convert_free(_audioConvert); _audioConvert = NULL; } #endif } void AudioLoader::configure() { // set ffmpeg to be silent by default, so we don't have these annoying // "invalid new backstep" messages anymore, when everything is actually fine av_log_set_level(AV_LOG_QUIET); reset(); } void AudioLoader::openAudioFile(const string& filename) { E_DEBUG(EAlgorithm, "AudioLoader: opening file: " << parameter("filename").toString()); // Open file if (avformat_open_input(&_demuxCtx, filename.c_str(), NULL, NULL) != 0) { throw EssentiaException("AudioLoader: Could not open file \"", filename, "\""); } // Retrieve stream information if (avformat_find_stream_info(_demuxCtx, NULL) < 0) { avformat_close_input(&_demuxCtx); _demuxCtx = 0; throw EssentiaException("AudioLoader: Could not find stream information"); } // Dump information about file onto standard error //dump_format(_demuxCtx, 0, filename.c_str(), 0); // Check that we have only 1 audio stream in the file int nAudioStreams = 0; for (int i=0; i<(int)_demuxCtx->nb_streams; i++) { if (_demuxCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) { _streamIdx = i; nAudioStreams++; } } if (nAudioStreams != 1) { throw EssentiaException("AudioLoader ERROR: found ", nAudioStreams, " streams in the file, expecting only one audio stream"); } // Load corresponding audio codec _audioCtx = _demuxCtx->streams[_streamIdx]->codec; _audioCodec = avcodec_find_decoder(_audioCtx->codec_id); if (!_audioCodec) { throw EssentiaException("AudioLoader: Unsupported codec!"); } if (avcodec_open2(_audioCtx, _audioCodec, NULL) < 0) { throw EssentiaException("AudioLoader: Unable to instantiate codec..."); } if (_audioCtx->sample_fmt != AV_SAMPLE_FMT_S16) { #if HAVE_SWRESAMPLE E_DEBUG(EAlgorithm, "AudioLoader: using sample format conversion from libswresample"); // No samplerate conversion yet, only format int64_t layout = av_get_default_channel_layout(_audioCtx->channels); _convertCtx = swr_alloc_set_opts(_convertCtx, layout, AV_SAMPLE_FMT_S16, _audioCtx->sample_rate, layout, _audioCtx->sample_fmt, _audioCtx->sample_rate, 0, NULL); if (swr_init(_convertCtx) < 0) { throw EssentiaException("Could not initialize swresample context"); } /* const char* fmt = 0; get_format_from_sample_fmt(&fmt, _audioCtx->sample_fmt); E_DEBUG(EAlgorithm, "AudioLoader: converting from " << (fmt ? fmt : "unknown") << " to S16"); */ #else E_DEBUG(EAlgorithm, "AudioLoader: using sample format conversion from " "deprecated audioconvert"); _audioConvert = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1, _audioCtx->sample_fmt, 1, NULL, 0); // reserve some more space _buff1 = (int16_t*)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3); _buff2 = (int16_t*)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3); #endif } else { E_DEBUG(EAlgorithm, "AudioLoader: no sample format conversion, using direct copy"); } av_init_packet(&_packet); #if LIBAVCODEC_VERSION_INT >= AVCODEC_AUDIO_DECODE4 _decodedFrame = avcodec_alloc_frame(); if (!_decodedFrame) { throw EssentiaException("Could not allocate audio frame"); } #endif #if LIBAVCODEC_VERSION_INT < AVCODEC_51_28_0 E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio() function"); #elif LIBAVCODEC_VERSION_INT < AVCODEC_52_47_0 E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio2() function"); #elif LIBAVCODEC_VERSION_INT < AVCODEC_AUDIO_DECODE4 E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio3() function"); #else E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio4() function"); #endif } void AudioLoader::closeAudioFile() { if (!_demuxCtx) { return; } #if HAVE_SWRESAMPLE if (_convertCtx) swr_free(&_convertCtx); #endif // Close the codec avcodec_close(_audioCtx); // Close the audio file avformat_close_input(&_demuxCtx); _demuxCtx = 0; _audioCtx = 0; } void AudioLoader::pushChannelsSampleRateInfo(int nChannels, Real sampleRate) { if (nChannels > 2) { throw EssentiaException("AudioLoader: could not load audio. Audio file has more than 2 channels."); } if (sampleRate <= 0) { throw EssentiaException("AudioLoader: could not load audio. Audio sampling rate must be greater than 0."); } _nChannels = nChannels; _channels.push(nChannels); _sampleRate.push(sampleRate); } AlgorithmStatus AudioLoader::process() { if (!parameter("filename").isConfigured()) { throw EssentiaException("AudioLoader: Trying to call process() on an AudioLoader algo which hasn't been correctly configured."); } // read frames until we get a good one do { int result = av_read_frame(_demuxCtx, &_packet); //E_DEBUG(EAlgorithm, "AudioLoader: called av_read_frame(), got result = " << result); if (result != 0) { shouldStop(true); flushPacket(); closeAudioFile(); return FINISHED; } } while (_packet.stream_index != _streamIdx); decodePacket(); copyFFmpegOutput(); return OK; } int AudioLoader::decode_audio_frame(AVCodecContext* audioCtx, int16_t* output, int* outputSize, AVPacket* packet) { #if LIBAVCODEC_VERSION_INT < AVCODEC_51_28_0 int len = avcodec_decode_audio(audioCtx, output, outputSize, packet->data, packet->size); #elif LIBAVCODEC_VERSION_INT < AVCODEC_52_47_0 int len = avcodec_decode_audio2(audioCtx, output, outputSize, packet->data, packet->size); #elif LIBAVCODEC_VERSION_INT < AVCODEC_AUDIO_DECODE4 int len = avcodec_decode_audio3(audioCtx, output, outputSize, packet); #else int gotFrame = 0; avcodec_get_frame_defaults(_decodedFrame); int len = avcodec_decode_audio4(audioCtx, _decodedFrame, &gotFrame, packet); if (len < 0) return len; // error handling should be done outside if (gotFrame) { int nsamples = _decodedFrame->nb_samples; int inputDataSize = av_samples_get_buffer_size(NULL, audioCtx->channels, nsamples, audioCtx->sample_fmt, 1); # if HAVE_SWRESAMPLE if (_convertCtx) { int outputSamples = *outputSize / (2 /*sizeof(S16)*/ * _nChannels); //if (outputSamples < nsamples) { cout << "OOPS!!" << endl; } if (swr_convert(_convertCtx, (uint8_t**) &output, outputSamples, (const uint8_t**)_decodedFrame->data, nsamples) < 0) { ostringstream msg; msg << "AudioLoader: Error converting" << " from " << av_get_sample_fmt_name(_audioCtx->sample_fmt) << " to " << av_get_sample_fmt_name(AV_SAMPLE_FMT_S16); throw EssentiaException(msg); } *outputSize = nsamples * (2 /*sizeof(S16)*/ * _nChannels); } else { // no conversion needed, make a direct copy // copy and convert data from our frame to our output audio buffer //E_WARNING("Should use swresample always!"); memcpy(output, _decodedFrame->data[0], inputDataSize); *outputSize = inputDataSize; } # else // direct copy, we do the sample format conversion later if needed memcpy(output, _decodedFrame->data[0], inputDataSize); *outputSize = inputDataSize; # endif } else { E_DEBUG(EAlgorithm, "AudioLoader: tried to decode packet but didn't get any frame..."); *outputSize = 0; } #endif return len; } void AudioLoader::flushPacket() { AVPacket empty; do { _dataSize = FFMPEG_BUFFER_SIZE * sizeof(int16_t); empty.data = 0; empty.size = 0; decode_audio_frame(_audioCtx, _buffer, &_dataSize, &empty); copyFFmpegOutput(); } while (_dataSize > 0); } /** * Gets the AVPacket stored in _packet, and decodes all the samples it can from it, * putting them in _buffer, the total number of bytes written begin stored in _dataSize. */ int AudioLoader::decodePacket() { /* E_DEBUG(EAlgorithm, "-----------------------------------------------------"); E_DEBUG(EAlgorithm, "decoding packet of " << _packet.size << " bytes"); E_DEBUG(EAlgorithm, "pts: " << _packet.pts << " - dts: " << _packet.dts); //" - pos: " << pkt->pos); E_DEBUG(EAlgorithm, "flags: " << _packet.flags); E_DEBUG(EAlgorithm, "duration: " << _packet.duration); */ int len = 0; // buff is an offset in our output buffer, it points to where we should start // writing the next decoded samples int16_t* buff = _buffer; #if !HAVE_SWRESAMPLE if (_audioConvert) { buff = _buff1; } #endif // _dataSize gets the size of the buffer, in bytes _dataSize = FFMPEG_BUFFER_SIZE*sizeof(int16_t); // _dataSize input = number of bytes available for write in buff // output = number of bytes actually written (actual: S16 data) //E_DEBUG(EAlgorithm, "decode_audio_frame, available bytes in buffer = " << _dataSize); len = decode_audio_frame(_audioCtx, buff, &_dataSize, &_packet); if (len < 0) { // only print error msg when file is not an mp3, because mp3 streams can have tag // frames (id3v2?) which libavcodec tries to read as audio anyway, and we don't want // to print an error message for that... if (_audioCtx->codec_id == CODEC_ID_MP3) { E_DEBUG(EAlgorithm, "AudioLoader: invalid frame, probably an mp3 tag frame, skipping it"); } else { E_WARNING("AudioLoader: error while decoding, skipping frame"); } return 0; } if (_dataSize <= 0) { // No data yet, get more frames //cout << "no data yet, get more frames" << endl; _dataSize = 0; return 0; } #if !HAVE_SWRESAMPLE if (_audioConvert) { // this assumes that all audio is interleaved in the first channel // it works as we're only doing sample format conversion, but we // should be very careful const void* ibuf[6] = { buff }; void* obuf[6] = { _buff2 }; int istride[6] = { av_get_bytes_per_sample(_audioCtx->sample_fmt) }; int ostride[6] = { av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) }; int totalsamples = _dataSize / istride[0]; // == num_samp_per_channel * num_channels if (av_audio_convert(_audioConvert, obuf, ostride, ibuf, istride, totalsamples) < 0) { ostringstream msg; msg << "AudioLoader: Error converting " << " from " << avcodec_get_sample_fmt_name(_audioCtx->sample_fmt) << " to " << avcodec_get_sample_fmt_name(SAMPLE_FMT_S16); throw EssentiaException(msg); } // when entering the current block, dataSize contained the size in bytes // that the audio was taking in its native format. Now it needs to be set // to the size of the audio we're returning, after conversion _dataSize = totalsamples * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16); } #endif if (len != _packet.size) { // FIXME: the following doesn't seem to happen anymore, probably some old // workaround for ffmpeg. Complain loudly if something looks fishy // more than 1 frame in a packet, happens a lot with flac for instance... const char msg[] = "AudioLoader: more than 1 frame in packet, not supported anymore... " "Please report the issue with the file that caused it."; E_ERROR(msg); throw EssentiaException(msg); } return len; } inline Real scale(int16_t value) { return value / (Real)32767; } void AudioLoader::copyFFmpegOutput() { int nsamples = _dataSize / 2 / _nChannels; if (nsamples == 0) return; // acquire necessary data bool ok = _audio.acquire(nsamples); if (!ok) { throw EssentiaException("AudioLoader: could not acquire output for audio"); } vector<StereoSample>& audio = *((vector<StereoSample>*)_audio.getTokens()); // FIXME: use libswresample if (_nChannels == 1) { for (int i=0; i<nsamples; i++) { audio[i].left() = scale(_buffer[i]); } } else { // _nChannels == 2 for (int i=0; i<nsamples; i++) { audio[i].left() = scale(_buffer[2*i]); audio[i].right() = scale(_buffer[2*i+1]); } } // release data _audio.release(nsamples); } void AudioLoader::reset() { Algorithm::reset(); if (!parameter("filename").isConfigured()) return; string filename = parameter("filename").toString(); closeAudioFile(); openAudioFile(filename); pushChannelsSampleRateInfo(_audioCtx->channels, _audioCtx->sample_rate); } } // namespace streaming } // namespace essentia namespace essentia { namespace standard { const char* AudioLoader::name = "AudioLoader"; const char* AudioLoader::description = DOC("Given an audio file this algorithm loads an audio file and outputs the raw signal data, the samplerate and the number of channels. Supported formats are: wav, aiff, flac (not supported on Windows), ogg and mp3.\n" "\n" "This algorithm will throw an exception if it hasn't been properly configured which normally is due to not specifying a valid filename. Invalid names comprise those with extensions different than the supported formats and non existent files.\n" "Note: ogg files are decoded in reverse phase, due to be using ffmpeg library.\n" "\n" "References:\n" " [1] WAV - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Wav\n" " [2] Audio Interchange File Format - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Aiff\n" " [3] Free Lossless Audio Codec - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Flac\n" " [4] Vorbis - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Vorbis\n" " [5] MP3 - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Mp3"); void AudioLoader::createInnerNetwork() { _loader = streaming::AlgorithmFactory::create("AudioLoader"); _audioStorage = new streaming::VectorOutput<StereoSample>(); _srStorage = new streaming::VectorOutput<Real>(&_sampleRateStorage); _cStorage = new streaming::VectorOutput<int>(&_channelsStorage); _loader->output("audio") >> _audioStorage->input("data"); _loader->output("sampleRate") >> _srStorage->input("data"); _loader->output("numberChannels") >> _cStorage->input("data"); _network = new scheduler::Network(_loader); } void AudioLoader::configure() { _loader->configure(INHERIT("filename")); } void AudioLoader::compute() { if (!parameter("filename").isConfigured()) { throw EssentiaException("AudioLoader: Trying to call compute() on an " "AudioLoader algo which hasn't been correctly configured."); } Real& sampleRate = _sampleRate.get(); int& nChannels = _channels.get(); vector<StereoSample>& audio = _audio.get(); _audioStorage->setVector(&audio); // FIXME: // _audio.reserve(sth_meaningful); _network->run(); sampleRate = _sampleRateStorage[0]; nChannels = _channelsStorage[0]; // reset, so it is ready to load audio again reset(); } void AudioLoader::reset() { _network->reset(); } } // namespace standard } // namespace essentia fixed sample format convert in AudioLoader /* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "audioloader.h" #include "algorithmfactory.h" using namespace std; namespace essentia { namespace streaming { const char* AudioLoader::name = "AudioLoader"; const char* AudioLoader::description = DOC("This algorithm loads the single audio stream contained in the given audio or video file, as well as the samplerate and the number of channels. Supported formats are all those supported by the ffmpeg library, which is, virtually everything.\n" "\n" "This algorithm will throw an exception if it hasn't been properly configured which is normally due to not specifying a valid filename.\n" "Note: ogg files are decoded in reverse phase, due to a (possible) bug in the ffmpeg library.\n" "\n" "References:\n" " [1] WAV - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Wav\n" " [2] Audio Interchange File Format - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Aiff\n" " [3] Free Lossless Audio Codec - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Flac\n" " [4] Vorbis - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Vorbis\n" " [5] MP3 - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Mp3"); AudioLoader::~AudioLoader() { closeAudioFile(); av_freep(&_buffer); #if LIBAVCODEC_VERSION_INT >= AVCODEC_AUDIO_DECODE4 av_freep(&_decodedFrame); #endif #if !HAVE_SWRESAMPLE av_freep(&_buff1); av_freep(&_buff2); if (_audioConvert) { av_audio_convert_free(_audioConvert); _audioConvert = NULL; } #endif } void AudioLoader::configure() { // set ffmpeg to be silent by default, so we don't have these annoying // "invalid new backstep" messages anymore, when everything is actually fine av_log_set_level(AV_LOG_QUIET); reset(); } void AudioLoader::openAudioFile(const string& filename) { E_DEBUG(EAlgorithm, "AudioLoader: opening file: " << parameter("filename").toString()); // Open file if (avformat_open_input(&_demuxCtx, filename.c_str(), NULL, NULL) != 0) { throw EssentiaException("AudioLoader: Could not open file \"", filename, "\""); } // Retrieve stream information if (avformat_find_stream_info(_demuxCtx, NULL) < 0) { avformat_close_input(&_demuxCtx); _demuxCtx = 0; throw EssentiaException("AudioLoader: Could not find stream information"); } // Dump information about file onto standard error //dump_format(_demuxCtx, 0, filename.c_str(), 0); // Check that we have only 1 audio stream in the file int nAudioStreams = 0; for (int i=0; i<(int)_demuxCtx->nb_streams; i++) { if (_demuxCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) { _streamIdx = i; nAudioStreams++; } } if (nAudioStreams != 1) { throw EssentiaException("AudioLoader ERROR: found ", nAudioStreams, " streams in the file, expecting only one audio stream"); } // Load corresponding audio codec _audioCtx = _demuxCtx->streams[_streamIdx]->codec; _audioCodec = avcodec_find_decoder(_audioCtx->codec_id); if (!_audioCodec) { throw EssentiaException("AudioLoader: Unsupported codec!"); } if (avcodec_open2(_audioCtx, _audioCodec, NULL) < 0) { throw EssentiaException("AudioLoader: Unable to instantiate codec..."); } if (_audioCtx->sample_fmt != AV_SAMPLE_FMT_S16) { #if HAVE_SWRESAMPLE E_DEBUG(EAlgorithm, "AudioLoader: using sample format conversion from libswresample"); // No samplerate conversion yet, only format int64_t layout = av_get_default_channel_layout(_audioCtx->channels); _convertCtx = swr_alloc_set_opts(_convertCtx, layout, AV_SAMPLE_FMT_S16, _audioCtx->sample_rate, layout, _audioCtx->sample_fmt, _audioCtx->sample_rate, 0, NULL); if (swr_init(_convertCtx) < 0) { throw EssentiaException("Could not initialize swresample context"); } /* const char* fmt = 0; get_format_from_sample_fmt(&fmt, _audioCtx->sample_fmt); E_DEBUG(EAlgorithm, "AudioLoader: converting from " << (fmt ? fmt : "unknown") << " to S16"); */ #else E_DEBUG(EAlgorithm, "AudioLoader: using sample format conversion from " "deprecated audioconvert"); _audioConvert = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1, _audioCtx->sample_fmt, 1, NULL, 0); // reserve some more space _buff1 = (int16_t*)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3); _buff2 = (int16_t*)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3); #endif } else { E_DEBUG(EAlgorithm, "AudioLoader: no sample format conversion, using direct copy"); } av_init_packet(&_packet); #if LIBAVCODEC_VERSION_INT >= AVCODEC_AUDIO_DECODE4 _decodedFrame = avcodec_alloc_frame(); if (!_decodedFrame) { throw EssentiaException("Could not allocate audio frame"); } #endif #if LIBAVCODEC_VERSION_INT < AVCODEC_51_28_0 E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio() function"); #elif LIBAVCODEC_VERSION_INT < AVCODEC_52_47_0 E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio2() function"); #elif LIBAVCODEC_VERSION_INT < AVCODEC_AUDIO_DECODE4 E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio3() function"); #else E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio4() function"); #endif } void AudioLoader::closeAudioFile() { if (!_demuxCtx) { return; } #if HAVE_SWRESAMPLE if (_convertCtx) swr_free(&_convertCtx); #endif // Close the codec avcodec_close(_audioCtx); // Close the audio file avformat_close_input(&_demuxCtx); _demuxCtx = 0; _audioCtx = 0; } void AudioLoader::pushChannelsSampleRateInfo(int nChannels, Real sampleRate) { if (nChannels > 2) { throw EssentiaException("AudioLoader: could not load audio. Audio file has more than 2 channels."); } if (sampleRate <= 0) { throw EssentiaException("AudioLoader: could not load audio. Audio sampling rate must be greater than 0."); } _nChannels = nChannels; _channels.push(nChannels); _sampleRate.push(sampleRate); } AlgorithmStatus AudioLoader::process() { if (!parameter("filename").isConfigured()) { throw EssentiaException("AudioLoader: Trying to call process() on an AudioLoader algo which hasn't been correctly configured."); } // read frames until we get a good one do { int result = av_read_frame(_demuxCtx, &_packet); //E_DEBUG(EAlgorithm, "AudioLoader: called av_read_frame(), got result = " << result); if (result != 0) { shouldStop(true); flushPacket(); closeAudioFile(); return FINISHED; } } while (_packet.stream_index != _streamIdx); decodePacket(); copyFFmpegOutput(); return OK; } int AudioLoader::decode_audio_frame(AVCodecContext* audioCtx, int16_t* output, int* outputSize, AVPacket* packet) { #if LIBAVCODEC_VERSION_INT < AVCODEC_51_28_0 int len = avcodec_decode_audio(audioCtx, output, outputSize, packet->data, packet->size); #elif LIBAVCODEC_VERSION_INT < AVCODEC_52_47_0 int len = avcodec_decode_audio2(audioCtx, output, outputSize, packet->data, packet->size); #elif LIBAVCODEC_VERSION_INT < AVCODEC_AUDIO_DECODE4 int len = avcodec_decode_audio3(audioCtx, output, outputSize, packet); #else int gotFrame = 0; avcodec_get_frame_defaults(_decodedFrame); int len = avcodec_decode_audio4(audioCtx, _decodedFrame, &gotFrame, packet); if (len < 0) return len; // error handling should be done outside if (gotFrame) { int nsamples = _decodedFrame->nb_samples; int inputDataSize = av_samples_get_buffer_size(NULL, audioCtx->channels, nsamples, audioCtx->sample_fmt, 1); # if HAVE_SWRESAMPLE if (_convertCtx) { int outputSamples = *outputSize / (2 /*sizeof(S16)*/ * _nChannels); //if (outputSamples < nsamples) { cout << "OOPS!!" << endl; } if (swr_convert(_convertCtx, (uint8_t**) &output, outputSamples, (const uint8_t**)_decodedFrame->data, nsamples) < 0) { ostringstream msg; msg << "AudioLoader: Error converting" << " from " << av_get_sample_fmt_name(_audioCtx->sample_fmt) << " to " << av_get_sample_fmt_name(AV_SAMPLE_FMT_S16); throw EssentiaException(msg); } *outputSize = nsamples * (2 /*sizeof(S16)*/ * _nChannels); } else { // no conversion needed, make a direct copy // copy and convert data from our frame to our output audio buffer //E_WARNING("Should use swresample always!"); memcpy(output, _decodedFrame->data[0], inputDataSize); *outputSize = inputDataSize; } # else // direct copy, we do the sample format conversion later if needed memcpy(output, _decodedFrame->data[0], inputDataSize); *outputSize = inputDataSize; # endif } else { E_DEBUG(EAlgorithm, "AudioLoader: tried to decode packet but didn't get any frame..."); *outputSize = 0; } #endif return len; } void AudioLoader::flushPacket() { AVPacket empty; do { _dataSize = FFMPEG_BUFFER_SIZE * sizeof(int16_t); empty.data = 0; empty.size = 0; decode_audio_frame(_audioCtx, _buffer, &_dataSize, &empty); copyFFmpegOutput(); } while (_dataSize > 0); } /** * Gets the AVPacket stored in _packet, and decodes all the samples it can from it, * putting them in _buffer, the total number of bytes written begin stored in _dataSize. */ int AudioLoader::decodePacket() { /* E_DEBUG(EAlgorithm, "-----------------------------------------------------"); E_DEBUG(EAlgorithm, "decoding packet of " << _packet.size << " bytes"); E_DEBUG(EAlgorithm, "pts: " << _packet.pts << " - dts: " << _packet.dts); //" - pos: " << pkt->pos); E_DEBUG(EAlgorithm, "flags: " << _packet.flags); E_DEBUG(EAlgorithm, "duration: " << _packet.duration); */ int len = 0; // buff is an offset in our output buffer, it points to where we should start // writing the next decoded samples int16_t* buff = _buffer; #if !HAVE_SWRESAMPLE if (_audioConvert) { buff = _buff1; } #endif // _dataSize gets the size of the buffer, in bytes _dataSize = FFMPEG_BUFFER_SIZE*sizeof(int16_t); // _dataSize input = number of bytes available for write in buff // output = number of bytes actually written (actual: S16 data) //E_DEBUG(EAlgorithm, "decode_audio_frame, available bytes in buffer = " << _dataSize); len = decode_audio_frame(_audioCtx, buff, &_dataSize, &_packet); if (len < 0) { // only print error msg when file is not an mp3, because mp3 streams can have tag // frames (id3v2?) which libavcodec tries to read as audio anyway, and we don't want // to print an error message for that... if (_audioCtx->codec_id == CODEC_ID_MP3) { E_DEBUG(EAlgorithm, "AudioLoader: invalid frame, probably an mp3 tag frame, skipping it"); } else { E_WARNING("AudioLoader: error while decoding, skipping frame"); } return 0; } if (_dataSize <= 0) { // No data yet, get more frames //cout << "no data yet, get more frames" << endl; _dataSize = 0; return 0; } #if !HAVE_SWRESAMPLE if (_audioConvert) { // this assumes that all audio is interleaved in the first channel // it works as we're only doing sample format conversion, but we // should be very careful const void* ibuf[6] = { buff }; void* obuf[6] = { _buff2 }; int istride[6] = { av_get_bytes_per_sample(_audioCtx->sample_fmt) }; int ostride[6] = { av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) }; int totalsamples = _dataSize / istride[0]; // == num_samp_per_channel * num_channels if (av_audio_convert(_audioConvert, obuf, ostride, ibuf, istride, totalsamples) < 0) { ostringstream msg; msg << "AudioLoader: Error converting " << " from " << avcodec_get_sample_fmt_name(_audioCtx->sample_fmt) << " to " << avcodec_get_sample_fmt_name(SAMPLE_FMT_S16); throw EssentiaException(msg); } // when entering the current block, dataSize contained the size in bytes // that the audio was taking in its native format. Now it needs to be set // to the size of the audio we're returning, after conversion _dataSize = totalsamples * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16); memcpy(_buffer, _buff2, _dataSize); } #endif if (len != _packet.size) { // FIXME: the following doesn't seem to happen anymore, probably some old // workaround for ffmpeg. Complain loudly if something looks fishy // more than 1 frame in a packet, happens a lot with flac for instance... const char msg[] = "AudioLoader: more than 1 frame in packet, not supported anymore... " "Please report the issue with the file that caused it."; E_ERROR(msg); throw EssentiaException(msg); } return len; } inline Real scale(int16_t value) { return value / (Real)32767; } void AudioLoader::copyFFmpegOutput() { int nsamples = _dataSize / 2 / _nChannels; if (nsamples == 0) return; // acquire necessary data bool ok = _audio.acquire(nsamples); if (!ok) { throw EssentiaException("AudioLoader: could not acquire output for audio"); } vector<StereoSample>& audio = *((vector<StereoSample>*)_audio.getTokens()); // FIXME: use libswresample if (_nChannels == 1) { for (int i=0; i<nsamples; i++) { audio[i].left() = scale(_buffer[i]); } } else { // _nChannels == 2 for (int i=0; i<nsamples; i++) { audio[i].left() = scale(_buffer[2*i]); audio[i].right() = scale(_buffer[2*i+1]); } } // release data _audio.release(nsamples); } void AudioLoader::reset() { Algorithm::reset(); if (!parameter("filename").isConfigured()) return; string filename = parameter("filename").toString(); closeAudioFile(); openAudioFile(filename); pushChannelsSampleRateInfo(_audioCtx->channels, _audioCtx->sample_rate); } } // namespace streaming } // namespace essentia namespace essentia { namespace standard { const char* AudioLoader::name = "AudioLoader"; const char* AudioLoader::description = DOC("Given an audio file this algorithm loads an audio file and outputs the raw signal data, the samplerate and the number of channels. Supported formats are: wav, aiff, flac (not supported on Windows), ogg and mp3.\n" "\n" "This algorithm will throw an exception if it hasn't been properly configured which normally is due to not specifying a valid filename. Invalid names comprise those with extensions different than the supported formats and non existent files.\n" "Note: ogg files are decoded in reverse phase, due to be using ffmpeg library.\n" "\n" "References:\n" " [1] WAV - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Wav\n" " [2] Audio Interchange File Format - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Aiff\n" " [3] Free Lossless Audio Codec - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Flac\n" " [4] Vorbis - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Vorbis\n" " [5] MP3 - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Mp3"); void AudioLoader::createInnerNetwork() { _loader = streaming::AlgorithmFactory::create("AudioLoader"); _audioStorage = new streaming::VectorOutput<StereoSample>(); _srStorage = new streaming::VectorOutput<Real>(&_sampleRateStorage); _cStorage = new streaming::VectorOutput<int>(&_channelsStorage); _loader->output("audio") >> _audioStorage->input("data"); _loader->output("sampleRate") >> _srStorage->input("data"); _loader->output("numberChannels") >> _cStorage->input("data"); _network = new scheduler::Network(_loader); } void AudioLoader::configure() { _loader->configure(INHERIT("filename")); } void AudioLoader::compute() { if (!parameter("filename").isConfigured()) { throw EssentiaException("AudioLoader: Trying to call compute() on an " "AudioLoader algo which hasn't been correctly configured."); } Real& sampleRate = _sampleRate.get(); int& nChannels = _channels.get(); vector<StereoSample>& audio = _audio.get(); _audioStorage->setVector(&audio); // FIXME: // _audio.reserve(sth_meaningful); _network->run(); sampleRate = _sampleRateStorage[0]; nChannels = _channelsStorage[0]; // reset, so it is ready to load audio again reset(); } void AudioLoader::reset() { _network->reset(); } } // namespace standard } // namespace essentia
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" #include "adv2_image_layout.h" #include "utils.h" #include "math.h" #include <stdlib.h> #include "adv_profiling.h" namespace AdvLib2 { Adv2ImageLayout::Adv2ImageLayout(Adv2ImageSection* imageSection, unsigned int width, unsigned int height, unsigned char layoutId, const char* layoutType, const char* compression, unsigned char layoutBpp) { m_ImageSection = imageSection; LayoutId = layoutId; Width = width; Height = height; Compression = nullptr; Bpp = layoutBpp; m_BytesLayout = FullImageRaw; m_UsesCompression = false; m_UsesLagarith16Compression = false; AddOrUpdateTag("DATA-LAYOUT", layoutType); AddOrUpdateTag("SECTION-DATA-COMPRESSION", compression); InitialiseBuffers(); EnsureCompressors(); } Adv2ImageLayout::Adv2ImageLayout(Adv2ImageSection* imageSection, char layoutId, FILE* pFile) { m_ImageSection = imageSection; LayoutId = layoutId; Width = imageSection->Width; Height = imageSection->Height; m_PixelArrayBuffer = nullptr; m_CompressedPixels = nullptr; m_StateCompress = nullptr; m_StateDecompress = nullptr; m_Lagarith16Compressor = nullptr; m_BytesLayout = FullImageRaw; m_UsesCompression = false; m_UsesLagarith16Compression = false; unsigned char version; advfread(&version, 1, 1, pFile); /* Version */ advfread(&Bpp, 1, 1, pFile); unsigned char tagsCount; advfread(&tagsCount, 1, 1, pFile); for (int i = 0; i < tagsCount; i++) { char* tagName = ReadUTF8String(pFile); char* tagValue = ReadUTF8String(pFile); AddOrUpdateTag(tagName, tagValue); } InitialiseBuffers(); EnsureCompressors(); } void Adv2ImageLayout::InitialiseBuffers() { if (Bpp == 8) { MaxFrameBufferSize = Width * Height + 1 + 4 + 16; } else if (Bpp == 12) { MaxFrameBufferSize = (Width * Height * 3 / 2) + 1 + 4 + 2 * ((Width * Height) % 2) + 16; } else if (Bpp == 16) { MaxFrameBufferSize = (Width * Height * 2) + 1 + 4 + 16; } else MaxFrameBufferSize = Width * Height * 4 + 1 + 4 + 16; // In accordance with Lagarith16 specs if (m_UsesLagarith16Compression) MaxFrameBufferSize = Width * Height * sizeof(short) + 0x20000; m_PixelArrayBuffer = nullptr; m_CompressedPixels = nullptr; m_DecompressedPixels = nullptr; m_StateCompress = nullptr; m_StateDecompress = nullptr; m_Lagarith16Compressor = nullptr; m_PixelArrayBuffer = (unsigned char*)malloc(MaxFrameBufferSize); m_CompressedPixels = (char*)malloc(MaxFrameBufferSize); m_DecompressedPixels = (char*)malloc(MaxFrameBufferSize); } Adv2ImageLayout::~Adv2ImageLayout() { ResetBuffers(); if (nullptr != Compression) { delete Compression; Compression = nullptr; } } void Adv2ImageLayout::ResetBuffers() { if (nullptr != m_PixelArrayBuffer) delete m_PixelArrayBuffer; if (nullptr != m_CompressedPixels) delete m_CompressedPixels; if (nullptr != m_StateCompress) delete m_StateCompress; if (nullptr != m_StateDecompress) delete m_StateDecompress; if (nullptr != m_Lagarith16Compressor) delete m_Lagarith16Compressor; m_PixelArrayBuffer = nullptr; m_CompressedPixels = nullptr; m_StateCompress = nullptr; m_StateDecompress = nullptr; m_StateDecompress = nullptr; m_Lagarith16Compressor = nullptr; } void Adv2ImageLayout::AddOrUpdateTag(const char* tagName, const char* tagValue) { map<string, string>::iterator curr = m_LayoutTags.begin(); while (curr != m_LayoutTags.end()) { const char* existingTagName = curr->first.c_str(); if (0 == strcmp(existingTagName, tagName)) { m_LayoutTags.erase(curr); break; } curr++; } m_LayoutTags.insert(make_pair(string(tagName), string(tagValue == nullptr ? "" : tagValue))); if (0 == strcmp("SECTION-DATA-COMPRESSION", tagName)) { if (Compression == nullptr) delete Compression; Compression = new char[strlen(tagValue) + 1]; strcpy_s(const_cast<char*>(Compression), strlen(tagValue) + 1, tagValue); if (strcmp(tagValue, "UNCOMPRESSED") != 0) m_UsesCompression = true; if (strcmp(tagValue, "LAGARITH16") == 0) m_UsesLagarith16Compression = true; } if (0 == strcmp("DATA-LAYOUT", tagName)) { IsFullImageRaw = 0 == strcmp(tagValue, "FULL-IMAGE-RAW"); Is12BitImagePacked = 0 == strcmp(tagValue, "12BIT-IMAGE-PACKED"); Is8BitColourImage = 0 == strcmp(tagValue, "8BIT-COLOR-IMAGE"); } } void Adv2ImageLayout::WriteHeader(FILE* pFile) { unsigned char buffChar; buffChar = 2; advfwrite(&buffChar, 1, 1, pFile); /* Version */ advfwrite(&Bpp, 1, 1, pFile); buffChar = (unsigned char)m_LayoutTags.size(); advfwrite(&buffChar, 1, 1, pFile); map<string, string>::iterator curr = m_LayoutTags.begin(); while (curr != m_LayoutTags.end()) { char* tagName = const_cast<char*>(curr->first.c_str()); WriteUTF8String(pFile, tagName); char* tagValue = const_cast<char*>(curr->second.c_str()); WriteUTF8String(pFile, tagValue); curr++; } } void Adv2ImageLayout::EnsureCompressors() { m_StateCompress = (qlz_state_compress *)malloc(sizeof(qlz_state_compress)); m_StateDecompress = (qlz_state_decompress *)malloc(sizeof(qlz_state_decompress)); // Lagarith compressor is intended for 16bit images only. In order to use it for a different BPP we // calculate 'adjusted' width of the corresponding 16bit image if passed bytes are grouped into int16 values. int widthOf16BitData = Width; if (Bpp == 8) widthOf16BitData /= 2; else if (Bpp == 12) widthOf16BitData = Width * 3 / 4; m_Lagarith16Compressor = new Compressor(widthOf16BitData, Height); } unsigned char* Adv2ImageLayout::GetDataBytes(unsigned short* currFramePixels, unsigned int *bytesCount, unsigned char dataPixelsBpp, enum GetByteOperation operation) { unsigned char* bytesToCompress = GetFullImageRawDataBytes(currFramePixels, bytesCount, dataPixelsBpp, operation); if (0 == strcmp(Compression, "QUICKLZ")) { unsigned int frameSize = 0; AdvProfiling_StartFrameCompression(); // compress and write result size_t len2 = qlz_compress(bytesToCompress, m_CompressedPixels, *bytesCount, m_StateCompress); AdvProfiling_EndFrameCompression(); *bytesCount = (unsigned int)len2; return (unsigned char*)(m_CompressedPixels); } if (0 == strcmp(Compression, "LAGARITH16")) { *bytesCount = m_Lagarith16Compressor->CompressData(currFramePixels, m_CompressedPixels); return (unsigned char*)(m_CompressedPixels); } else if (0 == strcmp(Compression, "UNCOMPRESSED")) { return bytesToCompress; } return nullptr; } unsigned char* Adv2ImageLayout::GetFullImageRawDataBytes(unsigned short* currFramePixels, unsigned int *bytesCount, unsigned char dataPixelsBpp, enum GetByteOperation operation) { int buffLen = 0; if (dataPixelsBpp == 16) { buffLen = Width * Height * 2; memcpy(&m_PixelArrayBuffer[0], &currFramePixels[0], buffLen); } else if (dataPixelsBpp == 8) { buffLen = Width * Height; memcpy(&m_PixelArrayBuffer[0], &currFramePixels[0], buffLen); } else if (dataPixelsBpp == 12) { if (operation == GetByteOperation::ConvertTo12BitPacked) // 2 pixels saved in 3 bytes GetDataBytes12BppIndex16BppWords(currFramePixels, 0, bytesCount); else { buffLen = Width * Height * 3 / 2; memcpy(&m_PixelArrayBuffer[0], &currFramePixels[0], buffLen); } } *bytesCount = buffLen; return m_PixelArrayBuffer; } void Adv2ImageLayout::GetDataBytes12BppIndex12BppWords(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount, unsigned char dataPixelsBpp) { // Flags: 0 - no key frame used, 1 - key frame follows, 2 - diff corr data follows bool isKeyFrame = false; //mode == KeyFrameBytes; bool noKeyFrameUsed = true; //mode == Normal; bool isDiffCorrFrame = false; //mode == DiffCorrBytes; // Every 2 12-bit values can be encoded in 3 bytes // xxxxxxxx|xxxxyyyy|yyyyyyy //int arrayLength = 1 + 4 + 3 * (Width * Height) / 2 + 2 * ((Width * Height) % 2) + *bytesCount; //unsigned char *imageData = (unsigned char*)malloc(arrayLength); //int signsBytesCnt = *bytesCount; unsigned int bytesCounter = *bytesCount; m_PixelArrayBuffer[0] = noKeyFrameUsed ? (unsigned char)0 : (isKeyFrame ? (unsigned char)1 : (unsigned char)2); bytesCounter++; unsigned int* pPixelArrayWords = (unsigned int*)(&m_PixelArrayBuffer[0] + bytesCounter); unsigned int* pPixels = (unsigned int*)pixels; int counter = 0; int pixel8GroupCount = Height * Width / 8; for (int idx = 0; idx < pixel8GroupCount; ++idx) { unsigned int word1 = *pPixels; unsigned int word2 = *pPixels;pPixels++; unsigned int word3 = *pPixels;pPixels++; unsigned int word4 = *pPixels;pPixels++; // word1 word2 word3 word4 // | 00aa aaaa 00bb bbbb | 00cc cccc 00dd dddd | 00ee eeee 00ff ffff | 00gg gggg 00hh hhhh| // | aaaa aabb bbbb cccc | ccdd dddd eeee eeff | ffff gggg gghh hhhh | // encoded1 encoded2 encoded3 unsigned int encodedPixelWord1 = ((word1 << 4) && 0xFFF00000) + ((word1 << 8) && 0x000FFF00) + (word2 >> 20); unsigned int encodedPixelWord2 = ((word2 << 12) && 0xF0000000) + (word2 << 16) + ((word3 >> 12) && 0x0000FFF0)+ ((word3 >> 8) && 0x0000000F); unsigned int encodedPixelWord3 = (word4 << 24) + ((word4 >> 4) && 0x00FFF000) + (word4 && 0x00000FFF); *pPixelArrayWords = encodedPixelWord1;pPixelArrayWords++; *pPixelArrayWords = encodedPixelWord2;pPixelArrayWords++; *pPixelArrayWords = encodedPixelWord3;pPixelArrayWords++; bytesCounter += 12; }; *pPixelArrayWords = pixelsCRC32; pPixelArrayWords++; (*bytesCount) = bytesCounter + 4; //if (isDiffCorrFrame) // memcpy(&m_PixelArrayBuffer[1], &m_SignsBuffer[0], signsBytesCnt); } void Adv2ImageLayout::GetDataBytes12BppIndex16BppWords(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount) { // Flags: 0 - no key frame used, 1 - key frame follows, 2 - diff corr data follows bool isKeyFrame = false; //mode == KeyFrameBytes; bool noKeyFrameUsed = true; //mode == Normal; bool isDiffCorrFrame = false; //mode == DiffCorrBytes; // Every 2 12-bit values can be encoded in 3 bytes // xxxxxxxx|xxxxyyyy|yyyyyyy //int arrayLength = 1 + 4 + 3 * (Width * Height) / 2 + 2 * ((Width * Height) % 2) + *bytesCount; //unsigned char *imageData = (unsigned char*)malloc(arrayLength); //int signsBytesCnt = *bytesCount; unsigned int bytesCounter = *bytesCount; m_PixelArrayBuffer[0] = noKeyFrameUsed ? (unsigned char)0 : (isKeyFrame ? (unsigned char)1 : (unsigned char)2); bytesCounter++; unsigned int* pPixelArrayWords = (unsigned int*)(&m_PixelArrayBuffer[0] + bytesCounter); unsigned int* pPixels = (unsigned int*)pixels; int counter = 0; int pixel8GroupCount = Height * Width / 8; for (int idx = 0; idx < pixel8GroupCount; ++idx) { unsigned int word1 = *pPixels; unsigned int word2 = *pPixels;pPixels++; unsigned int word3 = *pPixels;pPixels++; unsigned int word4 = *pPixels;pPixels++; //(int)(pixels[x + y * Width] * 4095 / 65535) // word1 word2 word3 word4 // | 00aa aaaa 00bb bbbb | 00cc cccc 00dd dddd | 00ee eeee 00ff ffff | 00gg gggg 00hh hhhh| // | aaaa aabb bbbb cccc | ccdd dddd eeee eeff | ffff gggg gghh hhhh | // encoded1 encoded2 encoded3 unsigned int encodedPixelWord1 = ((word1 << 4) && 0xFFF00000) + ((word1 << 8) && 0x000FFF00) + (word2 >> 20); unsigned int encodedPixelWord2 = ((word2 << 12) && 0xF0000000) + (word2 << 16) + ((word3 >> 12) && 0x0000FFF0)+ ((word3 >> 8) && 0x0000000F); unsigned int encodedPixelWord3 = (word4 << 24) + ((word4 >> 4) && 0x00FFF000) + (word4 && 0x00000FFF); *pPixelArrayWords = encodedPixelWord1;pPixelArrayWords++; *pPixelArrayWords = encodedPixelWord2;pPixelArrayWords++; *pPixelArrayWords = encodedPixelWord3;pPixelArrayWords++; bytesCounter += 12; }; *pPixelArrayWords = pixelsCRC32; pPixelArrayWords++; (*bytesCount) = bytesCounter + 4; //if (isDiffCorrFrame) // memcpy(&m_PixelArrayBuffer[1], &m_SignsBuffer[0], signsBytesCnt); } void Adv2ImageLayout::GetDataBytes12BppIndexBytes(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount, unsigned char dataPixelsBpp) { // Flags: 0 - no key frame used, 1 - key frame follows, 2 - diff corr data follows bool isKeyFrame = false; //mode == KeyFrameBytes; bool noKeyFrameUsed = true; //mode == Normal; bool isDiffCorrFrame = false; //mode == DiffCorrBytes; // Every 2 12-bit values can be encoded in 3 bytes // xxxxxxxx|xxxxyyyy|yyyyyyy unsigned int bytesCounter = *bytesCount; //m_PixelArrayBuffer[0] = noKeyFrameUsed ? (unsigned char)0 : (isKeyFrame ? (unsigned char)1 : (unsigned char)2); //bytesCounter++; int counter = 0; for (unsigned int y = 0; y < Height; ++y) { for (unsigned int x = 0; x < Width; ++x) { unsigned short value = dataPixelsBpp == 12 ? (unsigned short)(pixels[x + y * Width] & 0xFFF) : (unsigned short)(pixels[x + y * Width] >> 4); counter++; switch (counter % 2) { case 1: m_PixelArrayBuffer[bytesCounter] = (unsigned char)(value >> 4); bytesCounter++; m_PixelArrayBuffer[bytesCounter] = (unsigned char)((value & 0x0F) << 4); break; case 0: m_PixelArrayBuffer[bytesCounter] += (unsigned char)(value >> 8); bytesCounter++; m_PixelArrayBuffer[bytesCounter] = (unsigned char)(value & 0xFF); bytesCounter++; break; } } } //m_PixelArrayBuffer[bytesCounter] = (unsigned char)(pixelsCRC32 & 0xFF); //m_PixelArrayBuffer[bytesCounter + 1] = (unsigned char)((pixelsCRC32 >> 8) & 0xFF); //m_PixelArrayBuffer[bytesCounter + 2] = (unsigned char)((pixelsCRC32 >> 16) & 0xFF); //m_PixelArrayBuffer[bytesCounter + 3] = (unsigned char)((pixelsCRC32 >> 24) & 0xFF); (*bytesCount) = bytesCounter; } void Adv2ImageLayout::GetDataBytes12Bpp(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount, unsigned char dataPixelsBpp) { GetDataBytes12BppIndexBytes(pixels, pixelsCRC32, bytesCount, dataPixelsBpp); } void Adv2ImageLayout::GetDataBytes16Bpp(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount, unsigned char dataPixelsBpp) { /* // Flags: 0 - no key frame used, 1 - key frame follows, 2 - diff corr data follows bool isKeyFrame = false; //mode == KeyFrameBytes; bool noKeyFrameUsed = true; // mode == Normal; bool isDiffCorrFrame = false; //mode == DiffCorrBytes; //int arrayLength = 1 + 4 + 2 * Width * Height + *bytesCount; //unsigned char *imageData = (unsigned char*)malloc(arrayLength); int signsBytesCnt = *bytesCount; unsigned int bytesCounter = *bytesCount; m_PixelArrayBuffer[0] = noKeyFrameUsed ? (unsigned char)0 : (isKeyFrame ? (unsigned char)1 : (unsigned char)2); bytesCounter++; for (int y = 0; y < Height; ++y) { for (int x = 0; x < Width; ++x) { unsigned char lo = (unsigned char)(pixels[x + y * Width] & 0xFF); unsigned char hi = (unsigned char)(pixels[x + y * Width] >> 8); m_PixelArrayBuffer[bytesCounter] = hi; bytesCounter++; m_PixelArrayBuffer[bytesCounter] = lo; bytesCounter++; } } m_PixelArrayBuffer[bytesCounter] = (unsigned char)(pixelsCRC32 & 0xFF); m_PixelArrayBuffer[bytesCounter + 1] = (unsigned char)((pixelsCRC32 >> 8) & 0xFF); m_PixelArrayBuffer[bytesCounter + 2] = (unsigned char)((pixelsCRC32 >> 16) & 0xFF); m_PixelArrayBuffer[bytesCounter + 3] = (unsigned char)((pixelsCRC32 >> 24) & 0xFF); *bytesCount = bytesCounter + 4; if (isDiffCorrFrame) memcpy(&m_PixelArrayBuffer[1], &m_SignsBuffer[0], signsBytesCnt); */ } void Adv2ImageLayout::GetDataFromDataBytes(unsigned char* data, unsigned int* pixels, int sectionDataLength, int startOffset) { unsigned char* layoutData; if (!m_UsesCompression) { layoutData = data + startOffset; } else if (0 == strcmp(Compression, "QUICKLZ")) { size_t size = qlz_size_decompressed((char*)(data + startOffset)); // MaxFrameBufferSize qlz_decompress((char*)(data + startOffset), m_DecompressedPixels, m_StateDecompress); layoutData = (unsigned char*)m_DecompressedPixels; } else if (0 == strcmp(Compression, "LAGARITH16")) { int size = m_Lagarith16Compressor->DecompressData((char*)(data + startOffset), (unsigned short*)m_DecompressedPixels); layoutData = (unsigned char*)m_DecompressedPixels; } bool crcOkay; int readIndex = 0; if (Bpp == 12) { GetPixelsFrom12BitByteArray(layoutData, pixels, &readIndex, &crcOkay); } else if (Bpp == 16) { GetPixelsFrom16BitByteArrayRawLayout(layoutData, pixels, &readIndex, &crcOkay); } else if (Bpp == 8) { GetPixelsFrom8BitByteArrayRawLayout(layoutData, pixels, &readIndex, &crcOkay); } } void Adv2ImageLayout::GetPixelsFrom8BitByteArrayRawLayout(unsigned char* layoutData, unsigned int* pixelsOut, int* readIndex, bool* crcOkay) { if (Bpp == 8) { unsigned int* pPixelsOut = pixelsOut; for (int y = 0; y < Height; ++y) { for (int x = 0; x < Width; ++x) { unsigned char bt1 = *layoutData; layoutData++; *pPixelsOut = (unsigned short)bt1; pPixelsOut++; } } *readIndex += Height * Width; } if (m_ImageSection->UsesCRC) { unsigned int savedFrameCrc = (unsigned int)(*layoutData + (*(layoutData + 1) << 8) + (*(layoutData + 2) << 16) + (*(layoutData + 3) << 24)); *readIndex += 4; } else *crcOkay = true; } void Adv2ImageLayout::GetPixelsFrom16BitByteArrayRawLayout(unsigned char* layoutData, unsigned int* pixelsOut, int* readIndex, bool* crcOkay) { if (Bpp == 12 || Bpp == 14 || Bpp == 16) { unsigned int* pPixelsOut = pixelsOut; bool isLittleEndian = m_ImageSection->ByteOrder == LittleEndian; for (int y = 0; y < Height; ++y) { for (int x = 0; x < Width; ++x) { unsigned char bt1 = *layoutData; layoutData++; unsigned char bt2 = *layoutData; layoutData++; unsigned short val = isLittleEndian ? (unsigned short)(((unsigned short)bt2 << 8) + bt1) : (unsigned short)(((unsigned short)bt1 << 8) + bt2); *pPixelsOut = val; pPixelsOut++; } } *readIndex += Height * Width * 2; } if (m_ImageSection->UsesCRC) { unsigned int savedFrameCrc = (unsigned int)(*layoutData + (*(layoutData + 1) << 8) + (*(layoutData + 2) << 16) + (*(layoutData + 3) << 24)); *readIndex += 4; } else *crcOkay = true; } void Adv2ImageLayout::GetPixelsFrom12BitByteArray(unsigned char* layoutData, unsigned int* pixelsOut, int* readIndex, bool* crcOkay) { //bool isLittleEndian = m_ImageSection->ByteOrder == LittleEndian; //bool convertTo12Bit = m_ImageSection->DataBpp == 12; //bool convertTo16Bit = m_ImageSection->DataBpp == 16; //bool isDiffCorrFrame = mode == DiffCorrBytes; //unsigned int* pPrevFrame = prevFrame; //int counter = 0; //for (int y = 0; y < Height; ++y) //{ // for (int x = 0; x < Width; ++x) // { // counter++; // // Every 2 12-bit values can be encoded in 3 bytes // // xxxxxxxx|xxxxyyyy|yyyyyyy // unsigned char bt1; // unsigned char bt2; // unsigned short val; // switch (counter % 2) // { // case 1: // bt1 = *layoutData; // layoutData++; // bt2 = *layoutData; // val = (unsigned short)(((unsigned short)bt1 << 4) + ((bt2 >> 4) & 0x0F)); // if (!isLittleEndian) // { // val = (unsigned short)(val << 4); // val = (unsigned short)((unsigned short)((val & 0xFF) << 8) + (unsigned short)(val >> 8)); // if (convertTo12Bit) // throw "NotSupportedException"; // } // else // if (convertTo16Bit) val = (unsigned short)(val << 4); // if (isDiffCorrFrame) // { // val = (unsigned short)((unsigned short)*pPrevFrame + (unsigned short)val); // pPrevFrame++; // if (convertTo12Bit && val > 4095) val -= 4095; // } // *pixelsOut = val; // pixelsOut++; // if (counter < 10 || counter > Height * Width - 10) // printf("%d: %d", counter, val); // break; // case 0: // bt1 = *layoutData; // layoutData++; // bt2 = *layoutData; // layoutData++; // val = (unsigned short)((((unsigned short)bt1 & 0x0F) << 8) + bt2); // if (!isLittleEndian) // { // val = (unsigned short)(val << 4); // val = (unsigned short)((unsigned short)((val & 0xFF) << 8) + (unsigned short)(val >> 8)); // if (convertTo12Bit) // throw "NotSupportedException"; // } // else // if (convertTo16Bit) val = (unsigned short)(val << 4); // if (isDiffCorrFrame) // { // val = (unsigned short)((unsigned short)*pPrevFrame + (unsigned short)val); // pPrevFrame++; // if (convertTo12Bit && val > 4095) val -= 4095; // } // *pixelsOut = val; // pixelsOut++; // if (counter < 10 || counter > Height * Width - 10) // printf("%d: %d", counter, val); // break; // } // } //} //if (m_ImageSection->UsesCRC) //{ // unsigned int savedFrameCrc = (unsigned int)(*layoutData + (*(layoutData + 1) << 8) + (*(layoutData + 2) << 16) + (*(layoutData + 3) << 24)); // *readIndex += 4; //} //else // *crcOkay = true; // // return; } } Work in progress on encoding/decoding 12bit packed data /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" #include "adv2_image_layout.h" #include "utils.h" #include "math.h" #include <stdlib.h> #include "adv_profiling.h" namespace AdvLib2 { Adv2ImageLayout::Adv2ImageLayout(Adv2ImageSection* imageSection, unsigned int width, unsigned int height, unsigned char layoutId, const char* layoutType, const char* compression, unsigned char layoutBpp) { m_ImageSection = imageSection; LayoutId = layoutId; Width = width; Height = height; Compression = nullptr; Bpp = layoutBpp; m_BytesLayout = FullImageRaw; m_UsesCompression = false; m_UsesLagarith16Compression = false; AddOrUpdateTag("DATA-LAYOUT", layoutType); AddOrUpdateTag("SECTION-DATA-COMPRESSION", compression); InitialiseBuffers(); EnsureCompressors(); } Adv2ImageLayout::Adv2ImageLayout(Adv2ImageSection* imageSection, char layoutId, FILE* pFile) { m_ImageSection = imageSection; LayoutId = layoutId; Width = imageSection->Width; Height = imageSection->Height; m_PixelArrayBuffer = nullptr; m_CompressedPixels = nullptr; m_StateCompress = nullptr; m_StateDecompress = nullptr; m_Lagarith16Compressor = nullptr; m_BytesLayout = FullImageRaw; m_UsesCompression = false; m_UsesLagarith16Compression = false; unsigned char version; advfread(&version, 1, 1, pFile); /* Version */ advfread(&Bpp, 1, 1, pFile); unsigned char tagsCount; advfread(&tagsCount, 1, 1, pFile); for (int i = 0; i < tagsCount; i++) { char* tagName = ReadUTF8String(pFile); char* tagValue = ReadUTF8String(pFile); AddOrUpdateTag(tagName, tagValue); } InitialiseBuffers(); EnsureCompressors(); } void Adv2ImageLayout::InitialiseBuffers() { if (Bpp == 8) { MaxFrameBufferSize = Width * Height + 1 + 4 + 16; } else if (Bpp == 12) { MaxFrameBufferSize = (Width * Height * 3 / 2) + 1 + 4 + 2 * ((Width * Height) % 2) + 16; } else if (Bpp == 16) { MaxFrameBufferSize = (Width * Height * 2) + 1 + 4 + 16; } else MaxFrameBufferSize = Width * Height * 4 + 1 + 4 + 16; // In accordance with Lagarith16 specs if (m_UsesLagarith16Compression) MaxFrameBufferSize = Width * Height * sizeof(short) + 0x20000; m_PixelArrayBuffer = nullptr; m_CompressedPixels = nullptr; m_DecompressedPixels = nullptr; m_StateCompress = nullptr; m_StateDecompress = nullptr; m_Lagarith16Compressor = nullptr; m_PixelArrayBuffer = (unsigned char*)malloc(MaxFrameBufferSize); m_CompressedPixels = (char*)malloc(MaxFrameBufferSize); m_DecompressedPixels = (char*)malloc(MaxFrameBufferSize); } Adv2ImageLayout::~Adv2ImageLayout() { ResetBuffers(); if (nullptr != Compression) { delete Compression; Compression = nullptr; } } void Adv2ImageLayout::ResetBuffers() { if (nullptr != m_PixelArrayBuffer) delete m_PixelArrayBuffer; if (nullptr != m_CompressedPixels) delete m_CompressedPixels; if (nullptr != m_StateCompress) delete m_StateCompress; if (nullptr != m_StateDecompress) delete m_StateDecompress; if (nullptr != m_Lagarith16Compressor) delete m_Lagarith16Compressor; m_PixelArrayBuffer = nullptr; m_CompressedPixels = nullptr; m_StateCompress = nullptr; m_StateDecompress = nullptr; m_StateDecompress = nullptr; m_Lagarith16Compressor = nullptr; } void Adv2ImageLayout::AddOrUpdateTag(const char* tagName, const char* tagValue) { map<string, string>::iterator curr = m_LayoutTags.begin(); while (curr != m_LayoutTags.end()) { const char* existingTagName = curr->first.c_str(); if (0 == strcmp(existingTagName, tagName)) { m_LayoutTags.erase(curr); break; } curr++; } m_LayoutTags.insert(make_pair(string(tagName), string(tagValue == nullptr ? "" : tagValue))); if (0 == strcmp("SECTION-DATA-COMPRESSION", tagName)) { if (Compression == nullptr) delete Compression; Compression = new char[strlen(tagValue) + 1]; strcpy_s(const_cast<char*>(Compression), strlen(tagValue) + 1, tagValue); if (strcmp(tagValue, "UNCOMPRESSED") != 0) m_UsesCompression = true; if (strcmp(tagValue, "LAGARITH16") == 0) m_UsesLagarith16Compression = true; } if (0 == strcmp("DATA-LAYOUT", tagName)) { IsFullImageRaw = 0 == strcmp(tagValue, "FULL-IMAGE-RAW"); Is12BitImagePacked = 0 == strcmp(tagValue, "12BIT-IMAGE-PACKED"); Is8BitColourImage = 0 == strcmp(tagValue, "8BIT-COLOR-IMAGE"); } } void Adv2ImageLayout::WriteHeader(FILE* pFile) { unsigned char buffChar; buffChar = 2; advfwrite(&buffChar, 1, 1, pFile); /* Version */ advfwrite(&Bpp, 1, 1, pFile); buffChar = (unsigned char)m_LayoutTags.size(); advfwrite(&buffChar, 1, 1, pFile); map<string, string>::iterator curr = m_LayoutTags.begin(); while (curr != m_LayoutTags.end()) { char* tagName = const_cast<char*>(curr->first.c_str()); WriteUTF8String(pFile, tagName); char* tagValue = const_cast<char*>(curr->second.c_str()); WriteUTF8String(pFile, tagValue); curr++; } } void Adv2ImageLayout::EnsureCompressors() { m_StateCompress = (qlz_state_compress *)malloc(sizeof(qlz_state_compress)); m_StateDecompress = (qlz_state_decompress *)malloc(sizeof(qlz_state_decompress)); // Lagarith compressor is intended for 16bit images only. In order to use it for a different BPP we // calculate 'adjusted' width of the corresponding 16bit image if passed bytes are grouped into int16 values. int widthOf16BitData = Width; if (Bpp == 8) widthOf16BitData /= 2; else if (Bpp == 12) widthOf16BitData = Width * 3 / 4; m_Lagarith16Compressor = new Compressor(widthOf16BitData, Height); } unsigned char* Adv2ImageLayout::GetDataBytes(unsigned short* currFramePixels, unsigned int *bytesCount, unsigned char dataPixelsBpp, enum GetByteOperation operation) { unsigned char* bytesToCompress = GetFullImageRawDataBytes(currFramePixels, bytesCount, dataPixelsBpp, operation); if (0 == strcmp(Compression, "QUICKLZ")) { unsigned int frameSize = 0; AdvProfiling_StartFrameCompression(); // compress and write result size_t len2 = qlz_compress(bytesToCompress, m_CompressedPixels, *bytesCount, m_StateCompress); AdvProfiling_EndFrameCompression(); *bytesCount = (unsigned int)len2; return (unsigned char*)(m_CompressedPixels); } if (0 == strcmp(Compression, "LAGARITH16")) { *bytesCount = m_Lagarith16Compressor->CompressData(currFramePixels, m_CompressedPixels); return (unsigned char*)(m_CompressedPixels); } else if (0 == strcmp(Compression, "UNCOMPRESSED")) { return bytesToCompress; } return nullptr; } unsigned char* Adv2ImageLayout::GetFullImageRawDataBytes(unsigned short* currFramePixels, unsigned int *bytesCount, unsigned char dataPixelsBpp, enum GetByteOperation operation) { int buffLen = 0; if (dataPixelsBpp == 16) { if (operation == GetByteOperation::ConvertTo12BitPacked) // 2 pixels saved in 3 bytes GetDataBytes12BppIndex16BppWords(currFramePixels, 0, bytesCount); else { buffLen = Width * Height * 2; memcpy(&m_PixelArrayBuffer[0], &currFramePixels[0], buffLen); } } else if (dataPixelsBpp == 8) { buffLen = Width * Height; memcpy(&m_PixelArrayBuffer[0], &currFramePixels[0], buffLen); } else if (dataPixelsBpp == 12) { // NOTE: Data will come in already packed bytes buffLen = Width * Height * 3 / 2; memcpy(&m_PixelArrayBuffer[0], &currFramePixels[0], buffLen); } *bytesCount = buffLen; return m_PixelArrayBuffer; } void Adv2ImageLayout::GetDataBytes12BppIndex12BppWords(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount, unsigned char dataPixelsBpp) { // Flags: 0 - no key frame used, 1 - key frame follows, 2 - diff corr data follows bool isKeyFrame = false; //mode == KeyFrameBytes; bool noKeyFrameUsed = true; //mode == Normal; bool isDiffCorrFrame = false; //mode == DiffCorrBytes; // Every 2 12-bit values can be encoded in 3 bytes // xxxxxxxx|xxxxyyyy|yyyyyyy //int arrayLength = 1 + 4 + 3 * (Width * Height) / 2 + 2 * ((Width * Height) % 2) + *bytesCount; //unsigned char *imageData = (unsigned char*)malloc(arrayLength); //int signsBytesCnt = *bytesCount; unsigned int bytesCounter = *bytesCount; m_PixelArrayBuffer[0] = noKeyFrameUsed ? (unsigned char)0 : (isKeyFrame ? (unsigned char)1 : (unsigned char)2); bytesCounter++; unsigned int* pPixelArrayWords = (unsigned int*)(&m_PixelArrayBuffer[0] + bytesCounter); unsigned int* pPixels = (unsigned int*)pixels; int counter = 0; int pixel8GroupCount = Height * Width / 8; for (int idx = 0; idx < pixel8GroupCount; ++idx) { unsigned int word1 = *pPixels; unsigned int word2 = *pPixels;pPixels++; unsigned int word3 = *pPixels;pPixels++; unsigned int word4 = *pPixels;pPixels++; // word1 word2 word3 word4 // | 00aa aaaa 00bb bbbb | 00cc cccc 00dd dddd | 00ee eeee 00ff ffff | 00gg gggg 00hh hhhh| // | aaaa aabb bbbb cccc | ccdd dddd eeee eeff | ffff gggg gghh hhhh | // encoded1 encoded2 encoded3 unsigned int encodedPixelWord1 = ((word1 << 4) && 0xFFF00000) + ((word1 << 8) && 0x000FFF00) + (word2 >> 20); unsigned int encodedPixelWord2 = ((word2 << 12) && 0xF0000000) + (word2 << 16) + ((word3 >> 12) && 0x0000FFF0)+ ((word3 >> 8) && 0x0000000F); unsigned int encodedPixelWord3 = (word4 << 24) + ((word4 >> 4) && 0x00FFF000) + (word4 && 0x00000FFF); *pPixelArrayWords = encodedPixelWord1;pPixelArrayWords++; *pPixelArrayWords = encodedPixelWord2;pPixelArrayWords++; *pPixelArrayWords = encodedPixelWord3;pPixelArrayWords++; bytesCounter += 12; }; *pPixelArrayWords = pixelsCRC32; pPixelArrayWords++; (*bytesCount) = bytesCounter + 4; //if (isDiffCorrFrame) // memcpy(&m_PixelArrayBuffer[1], &m_SignsBuffer[0], signsBytesCnt); } void Adv2ImageLayout::GetDataBytes12BppIndex16BppWords(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount) { // Flags: 0 - no key frame used, 1 - key frame follows, 2 - diff corr data follows bool isKeyFrame = false; //mode == KeyFrameBytes; bool noKeyFrameUsed = true; //mode == Normal; bool isDiffCorrFrame = false; //mode == DiffCorrBytes; // Every 2 12-bit values can be encoded in 3 bytes // xxxxxxxx|xxxxyyyy|yyyyyyy //int arrayLength = 1 + 4 + 3 * (Width * Height) / 2 + 2 * ((Width * Height) % 2) + *bytesCount; //unsigned char *imageData = (unsigned char*)malloc(arrayLength); //int signsBytesCnt = *bytesCount; unsigned int bytesCounter = *bytesCount; m_PixelArrayBuffer[0] = noKeyFrameUsed ? (unsigned char)0 : (isKeyFrame ? (unsigned char)1 : (unsigned char)2); bytesCounter++; unsigned int* pPixelArrayWords = (unsigned int*)(&m_PixelArrayBuffer[0] + bytesCounter); unsigned int* pPixels = (unsigned int*)pixels; int counter = 0; int pixel8GroupCount = Height * Width / 8; for (int idx = 0; idx < pixel8GroupCount; ++idx) { unsigned int word1 = *pPixels; unsigned int word2 = *pPixels;pPixels++; unsigned int word3 = *pPixels;pPixels++; unsigned int word4 = *pPixels;pPixels++; //(int)(pixels[x + y * Width] * 4095 / 65535) // word1 word2 word3 word4 // | 00aa aaaa 00bb bbbb | 00cc cccc 00dd dddd | 00ee eeee 00ff ffff | 00gg gggg 00hh hhhh| // | aaaa aabb bbbb cccc | ccdd dddd eeee eeff | ffff gggg gghh hhhh | // encoded1 encoded2 encoded3 unsigned int encodedPixelWord1 = ((word1 << 4) && 0xFFF00000) + ((word1 << 8) && 0x000FFF00) + (word2 >> 20); unsigned int encodedPixelWord2 = ((word2 << 12) && 0xF0000000) + (word2 << 16) + ((word3 >> 12) && 0x0000FFF0)+ ((word3 >> 8) && 0x0000000F); unsigned int encodedPixelWord3 = (word4 << 24) + ((word4 >> 4) && 0x00FFF000) + (word4 && 0x00000FFF); *pPixelArrayWords = encodedPixelWord1;pPixelArrayWords++; *pPixelArrayWords = encodedPixelWord2;pPixelArrayWords++; *pPixelArrayWords = encodedPixelWord3;pPixelArrayWords++; bytesCounter += 12; }; *pPixelArrayWords = pixelsCRC32; pPixelArrayWords++; (*bytesCount) = bytesCounter + 4; //if (isDiffCorrFrame) // memcpy(&m_PixelArrayBuffer[1], &m_SignsBuffer[0], signsBytesCnt); } void Adv2ImageLayout::GetDataBytes12BppIndexBytes(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount, unsigned char dataPixelsBpp) { // Flags: 0 - no key frame used, 1 - key frame follows, 2 - diff corr data follows bool isKeyFrame = false; //mode == KeyFrameBytes; bool noKeyFrameUsed = true; //mode == Normal; bool isDiffCorrFrame = false; //mode == DiffCorrBytes; // Every 2 12-bit values can be encoded in 3 bytes // xxxxxxxx|xxxxyyyy|yyyyyyy unsigned int bytesCounter = *bytesCount; //m_PixelArrayBuffer[0] = noKeyFrameUsed ? (unsigned char)0 : (isKeyFrame ? (unsigned char)1 : (unsigned char)2); //bytesCounter++; int counter = 0; for (unsigned int y = 0; y < Height; ++y) { for (unsigned int x = 0; x < Width; ++x) { unsigned short value = dataPixelsBpp == 12 ? (unsigned short)(pixels[x + y * Width] & 0xFFF) : (unsigned short)(pixels[x + y * Width] >> 4); counter++; switch (counter % 2) { case 1: m_PixelArrayBuffer[bytesCounter] = (unsigned char)(value >> 4); bytesCounter++; m_PixelArrayBuffer[bytesCounter] = (unsigned char)((value & 0x0F) << 4); break; case 0: m_PixelArrayBuffer[bytesCounter] += (unsigned char)(value >> 8); bytesCounter++; m_PixelArrayBuffer[bytesCounter] = (unsigned char)(value & 0xFF); bytesCounter++; break; } } } //m_PixelArrayBuffer[bytesCounter] = (unsigned char)(pixelsCRC32 & 0xFF); //m_PixelArrayBuffer[bytesCounter + 1] = (unsigned char)((pixelsCRC32 >> 8) & 0xFF); //m_PixelArrayBuffer[bytesCounter + 2] = (unsigned char)((pixelsCRC32 >> 16) & 0xFF); //m_PixelArrayBuffer[bytesCounter + 3] = (unsigned char)((pixelsCRC32 >> 24) & 0xFF); (*bytesCount) = bytesCounter; } void Adv2ImageLayout::GetDataBytes12Bpp(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount, unsigned char dataPixelsBpp) { GetDataBytes12BppIndexBytes(pixels, pixelsCRC32, bytesCount, dataPixelsBpp); } void Adv2ImageLayout::GetDataBytes16Bpp(unsigned short* pixels, unsigned int pixelsCRC32, unsigned int *bytesCount, unsigned char dataPixelsBpp) { /* // Flags: 0 - no key frame used, 1 - key frame follows, 2 - diff corr data follows bool isKeyFrame = false; //mode == KeyFrameBytes; bool noKeyFrameUsed = true; // mode == Normal; bool isDiffCorrFrame = false; //mode == DiffCorrBytes; //int arrayLength = 1 + 4 + 2 * Width * Height + *bytesCount; //unsigned char *imageData = (unsigned char*)malloc(arrayLength); int signsBytesCnt = *bytesCount; unsigned int bytesCounter = *bytesCount; m_PixelArrayBuffer[0] = noKeyFrameUsed ? (unsigned char)0 : (isKeyFrame ? (unsigned char)1 : (unsigned char)2); bytesCounter++; for (int y = 0; y < Height; ++y) { for (int x = 0; x < Width; ++x) { unsigned char lo = (unsigned char)(pixels[x + y * Width] & 0xFF); unsigned char hi = (unsigned char)(pixels[x + y * Width] >> 8); m_PixelArrayBuffer[bytesCounter] = hi; bytesCounter++; m_PixelArrayBuffer[bytesCounter] = lo; bytesCounter++; } } m_PixelArrayBuffer[bytesCounter] = (unsigned char)(pixelsCRC32 & 0xFF); m_PixelArrayBuffer[bytesCounter + 1] = (unsigned char)((pixelsCRC32 >> 8) & 0xFF); m_PixelArrayBuffer[bytesCounter + 2] = (unsigned char)((pixelsCRC32 >> 16) & 0xFF); m_PixelArrayBuffer[bytesCounter + 3] = (unsigned char)((pixelsCRC32 >> 24) & 0xFF); *bytesCount = bytesCounter + 4; if (isDiffCorrFrame) memcpy(&m_PixelArrayBuffer[1], &m_SignsBuffer[0], signsBytesCnt); */ } void Adv2ImageLayout::GetDataFromDataBytes(unsigned char* data, unsigned int* pixels, int sectionDataLength, int startOffset) { unsigned char* layoutData; if (!m_UsesCompression) { layoutData = data + startOffset; } else if (0 == strcmp(Compression, "QUICKLZ")) { size_t size = qlz_size_decompressed((char*)(data + startOffset)); // MaxFrameBufferSize qlz_decompress((char*)(data + startOffset), m_DecompressedPixels, m_StateDecompress); layoutData = (unsigned char*)m_DecompressedPixels; } else if (0 == strcmp(Compression, "LAGARITH16")) { int size = m_Lagarith16Compressor->DecompressData((char*)(data + startOffset), (unsigned short*)m_DecompressedPixels); layoutData = (unsigned char*)m_DecompressedPixels; } bool crcOkay; int readIndex = 0; if (Bpp == 12) { GetPixelsFrom12BitByteArray(layoutData, pixels, &readIndex, &crcOkay); } else if (Bpp == 16) { GetPixelsFrom16BitByteArrayRawLayout(layoutData, pixels, &readIndex, &crcOkay); } else if (Bpp == 8) { GetPixelsFrom8BitByteArrayRawLayout(layoutData, pixels, &readIndex, &crcOkay); } } void Adv2ImageLayout::GetPixelsFrom8BitByteArrayRawLayout(unsigned char* layoutData, unsigned int* pixelsOut, int* readIndex, bool* crcOkay) { if (Bpp == 8) { unsigned int* pPixelsOut = pixelsOut; for (int y = 0; y < Height; ++y) { for (int x = 0; x < Width; ++x) { unsigned char bt1 = *layoutData; layoutData++; *pPixelsOut = (unsigned short)bt1; pPixelsOut++; } } *readIndex += Height * Width; } if (m_ImageSection->UsesCRC) { unsigned int savedFrameCrc = (unsigned int)(*layoutData + (*(layoutData + 1) << 8) + (*(layoutData + 2) << 16) + (*(layoutData + 3) << 24)); *readIndex += 4; } else *crcOkay = true; } void Adv2ImageLayout::GetPixelsFrom16BitByteArrayRawLayout(unsigned char* layoutData, unsigned int* pixelsOut, int* readIndex, bool* crcOkay) { if (Bpp == 12 || Bpp == 14 || Bpp == 16) { unsigned int* pPixelsOut = pixelsOut; bool isLittleEndian = m_ImageSection->ByteOrder == LittleEndian; for (int y = 0; y < Height; ++y) { for (int x = 0; x < Width; ++x) { unsigned char bt1 = *layoutData; layoutData++; unsigned char bt2 = *layoutData; layoutData++; unsigned short val = isLittleEndian ? (unsigned short)(((unsigned short)bt2 << 8) + bt1) : (unsigned short)(((unsigned short)bt1 << 8) + bt2); *pPixelsOut = val; pPixelsOut++; } } *readIndex += Height * Width * 2; } if (m_ImageSection->UsesCRC) { unsigned int savedFrameCrc = (unsigned int)(*layoutData + (*(layoutData + 1) << 8) + (*(layoutData + 2) << 16) + (*(layoutData + 3) << 24)); *readIndex += 4; } else *crcOkay = true; } void Adv2ImageLayout::GetPixelsFrom12BitByteArray(unsigned char* layoutData, unsigned int* pixelsOut, int* readIndex, bool* crcOkay) { int counter = 0; for (int y = 0; y < Height; ++y) { for (int x = 0; x < Width; ++x) { counter++; // Every 2 12-bit values are be encoded in 3 bytes // xxxxxxxx|xxxxyyyy|yyyyyyy unsigned char bt1; unsigned char bt2; unsigned short val; switch (counter % 2) { case 1: bt1 = *layoutData; layoutData++; bt2 = *layoutData; val = (unsigned short)(((unsigned short)bt1 << 4) + ((bt2 >> 4) & 0x0F)); *pixelsOut = val; pixelsOut++; if (counter < 10 || counter > Height * Width - 10) printf("%d: %d", counter, val); break; case 0: bt1 = *layoutData; layoutData++; bt2 = *layoutData; layoutData++; val = (unsigned short)((((unsigned short)bt1 & 0x0F) << 8) + bt2); *pixelsOut = val; pixelsOut++; if (counter < 10 || counter > Height * Width - 10) printf("%d: %d", counter, val); break; } } } if (m_ImageSection->UsesCRC) { unsigned int savedFrameCrc = (unsigned int)(*layoutData + (*(layoutData + 1) << 8) + (*(layoutData + 2) << 16) + (*(layoutData + 3) << 24)); *readIndex += 4; } else *crcOkay = true; return; } }
/*========================================================================= Program: Visualization Toolkit Module: TestGroupLeafVertices.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkActor.h" #include "vtkActor2D.h" //#include "vtkDynamic2DLabelMapper.h" #include "vtkGlyph3D.h" #include "vtkGraphLayout.h" #include "vtkGraphToPolyData.h" #include "vtkGroupLeafVertices.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkSphereSource.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkTableToTreeFilter.h" #include "vtkTree.h" #include "vtkTreeLayoutStrategy.h" #include "vtkTreeMapViewer.h" #define VTK_CREATE(type,name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() int TestGroupLeafVertices(int argc, char* argv[]) { int imode = 0; // Interactive mode for(int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-I")) { imode = 1; continue; } cerr << argv[0] << " Options:\n " << " -h (prints this message)\n " << " -I (run interactively)\n "; return 0; } VTK_CREATE(vtkTable, table); VTK_CREATE(vtkStringArray, nameArray); nameArray->SetName("name"); VTK_CREATE(vtkStringArray, typeArray); typeArray->SetName("type"); VTK_CREATE(vtkStringArray, colorArray); colorArray->SetName("color"); nameArray->InsertNextValue("bobo"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("black"); nameArray->InsertNextValue("rex"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("brown"); nameArray->InsertNextValue("bill"); typeArray->InsertNextValue("cat"); colorArray->InsertNextValue("black"); nameArray->InsertNextValue("eli"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("black"); nameArray->InsertNextValue("spot"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("white"); nameArray->InsertNextValue("roger"); typeArray->InsertNextValue("cat"); colorArray->InsertNextValue("black"); nameArray->InsertNextValue("tweety"); typeArray->InsertNextValue("bird"); colorArray->InsertNextValue("white"); nameArray->InsertNextValue("mike"); typeArray->InsertNextValue("bird"); colorArray->InsertNextValue("brown"); nameArray->InsertNextValue("spike"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("brown"); table->AddColumn(nameArray); table->AddColumn(typeArray); table->AddColumn(colorArray); // // Create a tree from the table // VTK_CREATE(vtkTableToTreeFilter, tableToTree); tableToTree->SetInput(table); tableToTree->Update(); vtkTree* tree = tableToTree->GetOutput(); for (vtkIdType i = 0; i < tree->GetNumberOfVertices(); i++) { cerr << i << " has parent " << tree->GetParent(i) << endl; } VTK_CREATE(vtkGroupLeafVertices, group); group->SetInputConnection(tableToTree->GetOutputPort()); group->SetInputArrayToProcess(0, 0, 0, vtkDataSet::FIELD_ASSOCIATION_VERTICES, "type"); group->SetInputArrayToProcess(1, 0, 0, vtkDataSet::FIELD_ASSOCIATION_VERTICES, "name"); group->Update(); tree = group->GetOutput(); for (vtkIdType i = 0; i < tree->GetNumberOfVertices(); i++) { cerr << i << " has parent " << tree->GetParent(i) << endl; } VTK_CREATE(vtkGroupLeafVertices, group2); group2->SetInputConnection(group->GetOutputPort()); group2->SetInputArrayToProcess(0, 0, 0, vtkDataSet::FIELD_ASSOCIATION_VERTICES, "color"); group2->SetInputArrayToProcess(1, 0, 0, vtkDataSet::FIELD_ASSOCIATION_VERTICES, "name"); group2->Update(); tree = group2->GetOutput(); for (vtkIdType i = 0; i < tree->GetNumberOfVertices(); i++) { cerr << i << " has parent " << tree->GetParent(i) << endl; } // // Render the tree // VTK_CREATE(vtkTreeLayoutStrategy, strategy); strategy->SetRadial(true); strategy->SetAngle(360); VTK_CREATE(vtkGraphLayout, layout); layout->SetInputConnection(group2->GetOutputPort()); layout->SetLayoutStrategy(strategy); VTK_CREATE(vtkGraphToPolyData, graphToPoly); graphToPoly->SetInputConnection(layout->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, polyMapper); polyMapper->SetInputConnection(graphToPoly->GetOutputPort()); VTK_CREATE(vtkActor, polyActor); polyActor->SetMapper(polyMapper); polyActor->GetProperty()->SetColor(0.3, 0.3, 1.0); // // Make some labels // #if 0 VTK_CREATE(vtkDynamic2DLabelMapper, labelMapper); labelMapper->SetInputConnection(graphToPoly->GetOutputPort()); labelMapper->SetLabelFormat("%s"); labelMapper->SetLabelModeToLabelFieldData(); labelMapper->SetFieldDataName("name"); VTK_CREATE(vtkActor2D, labelActor); labelActor->SetMapper(labelMapper); #endif // // Make some glyphs // VTK_CREATE(vtkSphereSource, sphere); sphere->SetRadius(0.05); sphere->SetPhiResolution(6); sphere->SetThetaResolution(6); VTK_CREATE(vtkGlyph3D, glyph); glyph->SetInputConnection(0, graphToPoly->GetOutputPort()); glyph->SetInputConnection(1, sphere->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, glyphMap); glyphMap->SetInputConnection(glyph->GetOutputPort()); VTK_CREATE(vtkActor, glyphActor); glyphActor->SetMapper(glyphMap); glyphActor->GetProperty()->SetColor(0.3, 0.3, 1.0); // // Set up the main window // VTK_CREATE(vtkRenderer, ren); ren->AddActor(polyActor); //ren->AddActor(labelActor); ren->AddActor(glyphActor); VTK_CREATE(vtkRenderWindow, win); win->AddRenderer(ren); VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(win); if (imode) { iren->Initialize(); iren->Start(); } return 0; } COMP: fixed compiler error when VTK_USE_VIEWS is off /*========================================================================= Program: Visualization Toolkit Module: TestGroupLeafVertices.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkActor.h" #include "vtkActor2D.h" //#include "vtkDynamic2DLabelMapper.h" #include "vtkGlyph3D.h" #include "vtkGraphLayout.h" #include "vtkGraphToPolyData.h" #include "vtkGroupLeafVertices.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkSphereSource.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkTableToTreeFilter.h" #include "vtkTree.h" #include "vtkTreeLayoutStrategy.h" #define VTK_CREATE(type,name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() int TestGroupLeafVertices(int argc, char* argv[]) { int imode = 0; // Interactive mode for(int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-I")) { imode = 1; continue; } cerr << argv[0] << " Options:\n " << " -h (prints this message)\n " << " -I (run interactively)\n "; return 0; } VTK_CREATE(vtkTable, table); VTK_CREATE(vtkStringArray, nameArray); nameArray->SetName("name"); VTK_CREATE(vtkStringArray, typeArray); typeArray->SetName("type"); VTK_CREATE(vtkStringArray, colorArray); colorArray->SetName("color"); nameArray->InsertNextValue("bobo"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("black"); nameArray->InsertNextValue("rex"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("brown"); nameArray->InsertNextValue("bill"); typeArray->InsertNextValue("cat"); colorArray->InsertNextValue("black"); nameArray->InsertNextValue("eli"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("black"); nameArray->InsertNextValue("spot"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("white"); nameArray->InsertNextValue("roger"); typeArray->InsertNextValue("cat"); colorArray->InsertNextValue("black"); nameArray->InsertNextValue("tweety"); typeArray->InsertNextValue("bird"); colorArray->InsertNextValue("white"); nameArray->InsertNextValue("mike"); typeArray->InsertNextValue("bird"); colorArray->InsertNextValue("brown"); nameArray->InsertNextValue("spike"); typeArray->InsertNextValue("dog"); colorArray->InsertNextValue("brown"); table->AddColumn(nameArray); table->AddColumn(typeArray); table->AddColumn(colorArray); // // Create a tree from the table // VTK_CREATE(vtkTableToTreeFilter, tableToTree); tableToTree->SetInput(table); tableToTree->Update(); vtkTree* tree = tableToTree->GetOutput(); for (vtkIdType i = 0; i < tree->GetNumberOfVertices(); i++) { cerr << i << " has parent " << tree->GetParent(i) << endl; } VTK_CREATE(vtkGroupLeafVertices, group); group->SetInputConnection(tableToTree->GetOutputPort()); group->SetInputArrayToProcess(0, 0, 0, vtkDataSet::FIELD_ASSOCIATION_VERTICES, "type"); group->SetInputArrayToProcess(1, 0, 0, vtkDataSet::FIELD_ASSOCIATION_VERTICES, "name"); group->Update(); tree = group->GetOutput(); for (vtkIdType i = 0; i < tree->GetNumberOfVertices(); i++) { cerr << i << " has parent " << tree->GetParent(i) << endl; } VTK_CREATE(vtkGroupLeafVertices, group2); group2->SetInputConnection(group->GetOutputPort()); group2->SetInputArrayToProcess(0, 0, 0, vtkDataSet::FIELD_ASSOCIATION_VERTICES, "color"); group2->SetInputArrayToProcess(1, 0, 0, vtkDataSet::FIELD_ASSOCIATION_VERTICES, "name"); group2->Update(); tree = group2->GetOutput(); for (vtkIdType i = 0; i < tree->GetNumberOfVertices(); i++) { cerr << i << " has parent " << tree->GetParent(i) << endl; } // // Render the tree // VTK_CREATE(vtkTreeLayoutStrategy, strategy); strategy->SetRadial(true); strategy->SetAngle(360); VTK_CREATE(vtkGraphLayout, layout); layout->SetInputConnection(group2->GetOutputPort()); layout->SetLayoutStrategy(strategy); VTK_CREATE(vtkGraphToPolyData, graphToPoly); graphToPoly->SetInputConnection(layout->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, polyMapper); polyMapper->SetInputConnection(graphToPoly->GetOutputPort()); VTK_CREATE(vtkActor, polyActor); polyActor->SetMapper(polyMapper); polyActor->GetProperty()->SetColor(0.3, 0.3, 1.0); // // Make some labels // #if 0 VTK_CREATE(vtkDynamic2DLabelMapper, labelMapper); labelMapper->SetInputConnection(graphToPoly->GetOutputPort()); labelMapper->SetLabelFormat("%s"); labelMapper->SetLabelModeToLabelFieldData(); labelMapper->SetFieldDataName("name"); VTK_CREATE(vtkActor2D, labelActor); labelActor->SetMapper(labelMapper); #endif // // Make some glyphs // VTK_CREATE(vtkSphereSource, sphere); sphere->SetRadius(0.05); sphere->SetPhiResolution(6); sphere->SetThetaResolution(6); VTK_CREATE(vtkGlyph3D, glyph); glyph->SetInputConnection(0, graphToPoly->GetOutputPort()); glyph->SetInputConnection(1, sphere->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, glyphMap); glyphMap->SetInputConnection(glyph->GetOutputPort()); VTK_CREATE(vtkActor, glyphActor); glyphActor->SetMapper(glyphMap); glyphActor->GetProperty()->SetColor(0.3, 0.3, 1.0); // // Set up the main window // VTK_CREATE(vtkRenderer, ren); ren->AddActor(polyActor); //ren->AddActor(labelActor); ren->AddActor(glyphActor); VTK_CREATE(vtkRenderWindow, win); win->AddRenderer(ren); VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(win); if (imode) { iren->Initialize(); iren->Start(); } return 0; }
#include "condor_common.h" #include "condor_config.h" #include "condor_md.h" #include "classad_collection.h" #include "gahp-client.h" #include "Functor.h" #include "StatusReply.h" void printClassAds( unsigned count, const std::map< std::string, std::string > & instances, const std::string & annexID, ClassAd * command ) { // Compute the summary information for the annex ad. std::map< std::string, unsigned > statusCounts; std::map< std::string, std::vector< std::string > > statusInstanceList; for( auto i = instances.begin(); i != instances.end(); ++i ) { if( statusCounts.count( i->second ) == 0 ) { statusCounts[ i->second ] = 0; } statusCounts[ i->second ] += 1; statusInstanceList[ i->second ].push_back( i->first ); } // Print the annex ad. ClassAd annexAd; annexAd.Assign( "AnnexID", annexID ); annexAd.Assign( "TotalInstances", count ); // Add the attributes necessary to insert it into the collector. The // name must be unique, but the annex ID is only is only unique per- // credential. What we actually want to uniquify with is the root // account ID, but we don't have that. Instead, we'll hash the // public (access) key ID. annexAd.Assign( "MyType", "Annex" ); std::string publicKeyFile; param( publicKeyFile, "ANNEX_DEFAULT_ACCESS_KEY_FILE" ); command->LookupString( "PublicKeyFile", publicKeyFile ); Condor_MD_MAC mmc; if(! mmc.addMDFile( publicKeyFile.c_str() )) { fprintf( stderr, "Failed to hash the access (public) key file, aborting.\n" ); return; } unsigned char * md = mmc.computeMD(); MyString md5; for( int i = 0; i < MAC_SIZE; ++i ) { md5.formatstr_cat( "%02x", (int)(md[i]) ); } free( md ); std::string name; formatstr( name, "%s [%s]", annexID.c_str(), md5.c_str() ); annexAd.Assign( ATTR_NAME, name ); for( auto i = statusCounts.begin(); i != statusCounts.end(); ++i ) { std::string attr = i->first; if( attr == "in-pool" ) { attr = "InPool"; } bool firstInWord = true; for( unsigned i = 0; i < attr.size(); ++i ) { if(! isalpha( attr[i] )) { attr.erase( i, 1 ); --i; firstInWord = true; continue; } if( firstInWord ) { attr[i] = toupper( attr[i] ); firstInWord = false; } } // If these ever become evaluated ClassAds, we could stop tracking // these and instead just make the attribute value 'size(...)' annexAd.Assign( ("NumInstances" + attr).c_str(), i->second ); if( attr == "InPool" ) { continue; } std::string expr; std::vector< std::string > & instanceList = statusInstanceList[ i->first ]; formatstr( expr, "{ \"%s\"", instanceList[0].c_str() ); for( unsigned j = 1; j < instanceList.size(); ++j ) { formatstr( expr, "%s, \"%s\"", expr.c_str(), instanceList[j].c_str() ); } expr += " }"; annexAd.AssignExpr( (attr + "InstancesList").c_str(), expr.c_str() ); } std::string ncaFormat; classad::ClassAdUnParser caup; caup.Unparse( ncaFormat, & annexAd ); dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", ncaFormat.c_str() ); fPrintAd( stdout, annexAd ); } void printHumanReadableSummary( unsigned, std::map< std::string, std::string > & instances, std::map< std::string, std::string > & annexes ) { // Do some aggregation. std::set< std::string > statuses; std::map< std::string, unsigned > total; std::map< std::string, std::map< std::string, unsigned > > output; for( auto i = annexes.begin(); i != annexes.end(); ++i ) { const std::string & annexName = i->second; const std::string & instanceID = i->first; ASSERT( instances.count( instanceID ) > 0 ); const std::string & status = instances[ instanceID ]; statuses.insert( status ); if( output.count( annexName ) == 0 || output[ annexName ].count( status ) == 0 ) { output[ annexName ][ status ] = 0; } output[ annexName ][ instances[ instanceID ] ] += 1; if( total.count( annexName ) == 0 ) { total[ annexName ] = 0; } total[ annexName ] += 1; } // Print the [annex-]NAME TOTAL <status1> ... <statusN> table. unsigned longestStatus = 0; fprintf( stdout, "%-27.27s %5.5s", "NAME", "TOTAL" ); for( auto i = statuses.begin(); i != statuses.end(); ++i ) { fprintf( stdout, " %s", i->c_str() ); if( i->length() > longestStatus ) { longestStatus = i->length(); } } fprintf( stdout, "\n" ); std::string auditString; for( auto i = total.begin(); i != total.end(); ++i ) { unsigned annexTotal = i->second; const std::string & annexName = i->first; formatstr( auditString, "%s%s: %u total,", auditString.c_str(), annexName.c_str(), annexTotal ); fprintf( stdout, "%-27.27s %5u", annexName.c_str(), annexTotal ); for( auto j = statuses.begin(); j != statuses.end(); ++j ) { auto & as = output[ annexName ]; const std::string & status = * j; if( as.count( status ) == 0 ) { formatstr( auditString, "%s %u %s,", auditString.c_str(), 0, status.c_str() ); fprintf( stdout, " %*s", status.length(), "0" ); } else { formatstr( auditString, "%s %u %s,", auditString.c_str(), as[ status ], status.c_str() ); fprintf( stdout, " %*d", status.length(), as[ status ] ); } } auditString.erase( auditString.length() - 1 ); auditString += "; "; fprintf( stdout, "\n" ); } auditString.erase( auditString.length() - 2 ); dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", auditString.c_str() ); auditString.clear(); // Print the table separator. fprintf( stdout, "\n" ); // FIXME: Should this formatted as a table, or just as a series of lines? // Print the [annex-]NAME STATE INSTANCES... table. fprintf( stdout, "%-27.27s %-*s INSTANCES...\n", "NAME", longestStatus, "STATUS" ); for( auto i = output.begin(); i != output.end(); ++i ) { const std::string & annexName = i->first; auto & as = i->second; for( auto j = as.begin(); j != as.end(); ++j ) { const std::string & status = j->first; if( status == "in-pool" ) { continue; } formatstr( auditString, "%s%s %s:", auditString.c_str(), annexName.c_str(), status.c_str() ); fprintf( stdout, "%-27.27s %-*s", annexName.c_str(), longestStatus, status.c_str() ); for( auto k = instances.begin(); k != instances.end(); ++k ) { const std::string & instanceID = k->first; const std::string & instanceStatus = k->second; if( status == instanceStatus && annexName == annexes[ instanceID ] ) { formatstr( auditString, "%s %s", auditString.c_str(), instanceID.c_str() ); fprintf( stdout, " %s", instanceID.c_str() ); } } auditString += "; "; fprintf( stdout, "\n" ); } } auditString.erase( auditString.length() - 2 ); dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", auditString.c_str() ); } void printHumanReadable( unsigned count, std::map< std::string, std::string > & instances, const std::string & annexID, std::map< std::string, std::string > & annexes ) { if( annexID.empty() ) { printHumanReadableSummary( count, instances, annexes ); return; } std::string auditString; std::map< std::string, unsigned > statusCounts; for( auto i = instances.begin(); i != instances.end(); ++i ) { if( statusCounts.count( i->second ) == 0 ) { statusCounts[ i->second ] = 0; } statusCounts[ i->second ] += 1; } fprintf( stdout, "%-14.14s %5.5s\n", "STATE", "COUNT" ); for( auto i = statusCounts.begin(); i != statusCounts.end(); ++i ) { formatstr( auditString, "%s%s %u, ", auditString.c_str(), i->first.c_str(), i->second ); fprintf( stdout, "%-14.14s %5u\n", i->first.c_str(), i->second ); } formatstr( auditString, "%stotal %u", auditString.c_str(), count ); fprintf( stdout, "%-14.14s %5u\n", "TOTAL", count ); std::map< std::string, std::vector< std::string > > instanceIDsByStatus; for( auto i = instances.begin(); i != instances.end(); ++i ) { instanceIDsByStatus[ i->second ].push_back( i->first ); } if( statusCounts[ "in-pool" ] != count ) { formatstr( auditString, "%s; ", auditString.c_str() ); fprintf( stdout, "\n" ); fprintf( stdout, "Instances not in the pool, grouped by state:\n" ); for( auto i = instanceIDsByStatus.begin(); i != instanceIDsByStatus.end(); ++i ) { if( i->first == "in-pool" ) { continue; } formatstr( auditString, "%s%s ", auditString.c_str(), i->first.c_str() ); fprintf( stdout, "%s", i->first.c_str() ); unsigned column = i->first.length(); for( unsigned j = 0; j < i->second.size(); ++j ) { column += i->second[j].length() + 1; if( column >= 80 ) { fprintf( stdout, "\n" ); column = i->first.length(); fprintf( stdout, "%*.*s", column, column, "" ); column += i->second[j].length() + 1; } formatstr( auditString, "%s%s ", auditString.c_str(), i->second[j].c_str() ); fprintf( stdout, " %s", i->second[j].c_str() ); } formatstr( auditString, "%s; ", auditString.substr( 0, auditString.length() - 1 ).c_str() ); fprintf( stdout, "\n" ); } auditString.erase( auditString.length() - 2 ); } dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", auditString.c_str() ); } int StatusReply::operator() () { dprintf( D_FULLDEBUG, "StatusReply::operator()\n" ); if( reply ) { std::string resultString; reply->LookupString( ATTR_RESULT, resultString ); CAResult result = getCAResultNum( resultString.c_str() ); if( result == CA_SUCCESS ) { std::map< std::string, std::string > annexes; std::map< std::string, std::string > instances; std::string iName; unsigned count = 0; do { formatstr( iName, "Instance%d", count ); std::string instanceID; scratchpad->LookupString( (iName + ".instanceID").c_str(), instanceID ); if( instanceID.empty() ) { break; } ++count; // fprintf( stderr, "Found instance ID %s.\n", instanceID.c_str() ); std::string status; scratchpad->LookupString( (iName + ".status").c_str(), status ); ASSERT(! status.empty()); instances[ instanceID ] = status; std::string annexName; scratchpad->LookupString( (iName + ".annexName").c_str(), annexName ); // Spot instances don't have an annexName yet. // ASSERT(! annexName.empty() ); annexes[ instanceID ] = annexName; } while( true ); std::string annexID, annexName; scratchpad->LookupString( "AnnexID", annexID ); annexName = annexID.substr( 0, annexID.find( "_" ) ); if( count == 0 ) { std::string errorString; if( annexName.empty() ) { errorString = "Found no instances in any annex."; } else { errorString = "Found no machines in that annex."; } dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", errorString.c_str() ); fprintf( stdout, "%s\n", errorString.c_str() ); goto cleanup; } CondorQuery q( STARTD_AD ); std::string constraint; if( annexName.empty() ) { formatstr( constraint, "IsAnnex" ); } else { formatstr( constraint, "AnnexName == \"%s\"", annexName.c_str() ); } q.addANDConstraint( constraint.c_str() ); ClassAdList cal; CondorError errStack; CollectorList * collectors = CollectorList::create(); /* QueryResult qr = */ collectors->query( q, cal, & errStack ); delete collectors; cal.Rewind(); ClassAd * cad = NULL; while( (cad = cal.Next()) != NULL ) { std::string name, instanceID, aName; cad->LookupString( "Name", name ); cad->LookupString( "EC2InstanceID", instanceID ); cad->LookupString( "AnnexName", aName ); instances[ instanceID ] = "in-pool"; } if( wantClassAds ) { printClassAds( count, instances, annexID, command ); } else { printHumanReadable( count, instances, annexID, annexes ); } } else { std::string errorString; reply->LookupString( ATTR_ERROR_STRING, errorString ); if( errorString.empty() ) { fprintf( stderr, "Status check failed (%s) without an error string.\n", resultString.c_str() ); } else { fprintf( stderr, "%s\n", errorString.c_str() ); } } cleanup: delete reply; reply = NULL; } if( gahp ) { daemonCore->Cancel_Timer( gahp->getNotificationTimerId() ); delete gahp; gahp = NULL; } if( scratchpad ) { delete scratchpad; scratchpad = NULL; } return TRUE; } int StatusReply::rollback() { dprintf( D_FULLDEBUG, "StatusReply::rollback() -- calling operator().\n" ); return (* this)(); } (#6321) Implement 'condor_annex -status -classad', including audit logging. #include "condor_common.h" #include "condor_config.h" #include "condor_md.h" #include "classad_collection.h" #include "gahp-client.h" #include "Functor.h" #include "StatusReply.h" void printClassAds( const std::map< std::string, std::string > & instances, const std::string & annexID, ClassAd * command, std::map< std::string, std::string > & annexes ); void printClassAdsSummary( const std::map< std::string, std::string > & instances, ClassAd * command, std::map< std::string, std::string > & annexes ) { std::map< std::string, std::map< std::string, std::string > > instanceListsByAnnex; for( auto i = instances.begin(); i != instances.end(); ++i ) { const std::string & status = i->second; const std::string & instanceID = i->first; const std::string & annexName = annexes[ instanceID ]; instanceListsByAnnex[ annexName ][ instanceID ] = status; } std::map< std::string, std::string > dummy; for( auto i = instanceListsByAnnex.begin(); i != instanceListsByAnnex.end(); ++i ) { const std::string & annexName = i->first; std::map< std::string, std::string > & instanceList = i->second; printClassAds( instanceList, annexName, command, dummy ); fprintf( stdout, "\n" ); } } void printClassAds( const std::map< std::string, std::string > & instances, const std::string & annexID, ClassAd * command, std::map< std::string, std::string > & annexes ) { if( annexID.empty() ) { printClassAdsSummary( instances, command, annexes ); return; } // Compute the summary information for the annex ad. std::map< std::string, unsigned > statusCounts; std::map< std::string, std::vector< std::string > > statusInstanceList; for( auto i = instances.begin(); i != instances.end(); ++i ) { if( statusCounts.count( i->second ) == 0 ) { statusCounts[ i->second ] = 0; } statusCounts[ i->second ] += 1; statusInstanceList[ i->second ].push_back( i->first ); } // Print the annex ad. ClassAd annexAd; annexAd.Assign( "AnnexID", annexID ); annexAd.Assign( "TotalInstances", instances.size() ); // Add the attributes necessary to insert it into the collector. The // name must be unique, but the annex ID is only is only unique per- // credential. What we actually want to uniquify with is the root // account ID, but we don't have that. Instead, we'll hash the // public (access) key ID. annexAd.Assign( "MyType", "Annex" ); std::string publicKeyFile; param( publicKeyFile, "ANNEX_DEFAULT_ACCESS_KEY_FILE" ); command->LookupString( "PublicKeyFile", publicKeyFile ); Condor_MD_MAC mmc; if(! mmc.addMDFile( publicKeyFile.c_str() )) { fprintf( stderr, "Failed to hash the access (public) key file, aborting.\n" ); return; } unsigned char * md = mmc.computeMD(); MyString md5; for( int i = 0; i < MAC_SIZE; ++i ) { md5.formatstr_cat( "%02x", (int)(md[i]) ); } free( md ); std::string name; formatstr( name, "%s [%s]", annexID.c_str(), md5.c_str() ); annexAd.Assign( ATTR_NAME, name ); for( auto i = statusCounts.begin(); i != statusCounts.end(); ++i ) { std::string attr = i->first; if( attr == "in-pool" ) { attr = "InPool"; } bool firstInWord = true; for( unsigned i = 0; i < attr.size(); ++i ) { if(! isalpha( attr[i] )) { attr.erase( i, 1 ); --i; firstInWord = true; continue; } if( firstInWord ) { attr[i] = toupper( attr[i] ); firstInWord = false; } } // If these ever become evaluated ClassAds, we could stop tracking // these and instead just make the attribute value 'size(...)' annexAd.Assign( ("NumInstances" + attr).c_str(), i->second ); if( attr == "InPool" ) { continue; } std::string expr; std::vector< std::string > & instanceList = statusInstanceList[ i->first ]; formatstr( expr, "{ \"%s\"", instanceList[0].c_str() ); for( unsigned j = 1; j < instanceList.size(); ++j ) { formatstr( expr, "%s, \"%s\"", expr.c_str(), instanceList[j].c_str() ); } expr += " }"; annexAd.AssignExpr( (attr + "InstancesList").c_str(), expr.c_str() ); } std::string ncaFormat; classad::ClassAdUnParser caup; caup.Unparse( ncaFormat, & annexAd ); dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", ncaFormat.c_str() ); fPrintAd( stdout, annexAd ); } void printHumanReadableSummary( std::map< std::string, std::string > & instances, std::map< std::string, std::string > & annexes ) { // Do some aggregation. std::set< std::string > statuses; std::map< std::string, unsigned > total; std::map< std::string, std::map< std::string, unsigned > > output; for( auto i = annexes.begin(); i != annexes.end(); ++i ) { const std::string & annexName = i->second; const std::string & instanceID = i->first; ASSERT( instances.count( instanceID ) > 0 ); const std::string & status = instances[ instanceID ]; statuses.insert( status ); if( output.count( annexName ) == 0 || output[ annexName ].count( status ) == 0 ) { output[ annexName ][ status ] = 0; } output[ annexName ][ instances[ instanceID ] ] += 1; if( total.count( annexName ) == 0 ) { total[ annexName ] = 0; } total[ annexName ] += 1; } // Print the [annex-]NAME TOTAL <status1> ... <statusN> table. unsigned longestStatus = 0; fprintf( stdout, "%-27.27s %5.5s", "NAME", "TOTAL" ); for( auto i = statuses.begin(); i != statuses.end(); ++i ) { fprintf( stdout, " %s", i->c_str() ); if( i->length() > longestStatus ) { longestStatus = i->length(); } } fprintf( stdout, "\n" ); std::string auditString; for( auto i = total.begin(); i != total.end(); ++i ) { unsigned annexTotal = i->second; const std::string & annexName = i->first; formatstr( auditString, "%s%s: %u total,", auditString.c_str(), annexName.c_str(), annexTotal ); fprintf( stdout, "%-27.27s %5u", annexName.c_str(), annexTotal ); for( auto j = statuses.begin(); j != statuses.end(); ++j ) { auto & as = output[ annexName ]; const std::string & status = * j; if( as.count( status ) == 0 ) { formatstr( auditString, "%s %u %s,", auditString.c_str(), 0, status.c_str() ); fprintf( stdout, " %*s", status.length(), "0" ); } else { formatstr( auditString, "%s %u %s,", auditString.c_str(), as[ status ], status.c_str() ); fprintf( stdout, " %*d", status.length(), as[ status ] ); } } auditString.erase( auditString.length() - 1 ); auditString += "; "; fprintf( stdout, "\n" ); } auditString.erase( auditString.length() - 2 ); dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", auditString.c_str() ); auditString.clear(); // Print the table separator. fprintf( stdout, "\n" ); // FIXME: Should this formatted as a table, or just as a series of lines? // Print the [annex-]NAME STATE INSTANCES... table. fprintf( stdout, "%-27.27s %-*s INSTANCES...\n", "NAME", longestStatus, "STATUS" ); for( auto i = output.begin(); i != output.end(); ++i ) { const std::string & annexName = i->first; auto & as = i->second; for( auto j = as.begin(); j != as.end(); ++j ) { const std::string & status = j->first; if( status == "in-pool" ) { continue; } formatstr( auditString, "%s%s %s:", auditString.c_str(), annexName.c_str(), status.c_str() ); fprintf( stdout, "%-27.27s %-*s", annexName.c_str(), longestStatus, status.c_str() ); for( auto k = instances.begin(); k != instances.end(); ++k ) { const std::string & instanceID = k->first; const std::string & instanceStatus = k->second; if( status == instanceStatus && annexName == annexes[ instanceID ] ) { formatstr( auditString, "%s %s", auditString.c_str(), instanceID.c_str() ); fprintf( stdout, " %s", instanceID.c_str() ); } } auditString += "; "; fprintf( stdout, "\n" ); } } auditString.erase( auditString.length() - 2 ); dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", auditString.c_str() ); } void printHumanReadable( std::map< std::string, std::string > & instances, const std::string & annexID, std::map< std::string, std::string > & annexes ) { if( annexID.empty() ) { printHumanReadableSummary( instances, annexes ); return; } std::string auditString; std::map< std::string, unsigned > statusCounts; for( auto i = instances.begin(); i != instances.end(); ++i ) { if( statusCounts.count( i->second ) == 0 ) { statusCounts[ i->second ] = 0; } statusCounts[ i->second ] += 1; } fprintf( stdout, "%-14.14s %5.5s\n", "STATE", "COUNT" ); for( auto i = statusCounts.begin(); i != statusCounts.end(); ++i ) { formatstr( auditString, "%s%s %u, ", auditString.c_str(), i->first.c_str(), i->second ); fprintf( stdout, "%-14.14s %5u\n", i->first.c_str(), i->second ); } formatstr( auditString, "%stotal %u", auditString.c_str(), instances.size() ); fprintf( stdout, "%-14.14s %5u\n", "TOTAL", instances.size() ); std::map< std::string, std::vector< std::string > > instanceIDsByStatus; for( auto i = instances.begin(); i != instances.end(); ++i ) { instanceIDsByStatus[ i->second ].push_back( i->first ); } if( statusCounts[ "in-pool" ] != instances.size() ) { formatstr( auditString, "%s; ", auditString.c_str() ); fprintf( stdout, "\n" ); fprintf( stdout, "Instances not in the pool, grouped by state:\n" ); for( auto i = instanceIDsByStatus.begin(); i != instanceIDsByStatus.end(); ++i ) { if( i->first == "in-pool" ) { continue; } formatstr( auditString, "%s%s ", auditString.c_str(), i->first.c_str() ); fprintf( stdout, "%s", i->first.c_str() ); unsigned column = i->first.length(); for( unsigned j = 0; j < i->second.size(); ++j ) { column += i->second[j].length() + 1; if( column >= 80 ) { fprintf( stdout, "\n" ); column = i->first.length(); fprintf( stdout, "%*.*s", column, column, "" ); column += i->second[j].length() + 1; } formatstr( auditString, "%s%s ", auditString.c_str(), i->second[j].c_str() ); fprintf( stdout, " %s", i->second[j].c_str() ); } formatstr( auditString, "%s; ", auditString.substr( 0, auditString.length() - 1 ).c_str() ); fprintf( stdout, "\n" ); } auditString.erase( auditString.length() - 2 ); } dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", auditString.c_str() ); } int StatusReply::operator() () { dprintf( D_FULLDEBUG, "StatusReply::operator()\n" ); if( reply ) { std::string resultString; reply->LookupString( ATTR_RESULT, resultString ); CAResult result = getCAResultNum( resultString.c_str() ); if( result == CA_SUCCESS ) { std::map< std::string, std::string > annexes; std::map< std::string, std::string > instances; std::string iName; unsigned count = 0; do { formatstr( iName, "Instance%d", count ); std::string instanceID; scratchpad->LookupString( (iName + ".instanceID").c_str(), instanceID ); if( instanceID.empty() ) { break; } ++count; // fprintf( stderr, "Found instance ID %s.\n", instanceID.c_str() ); std::string status; scratchpad->LookupString( (iName + ".status").c_str(), status ); ASSERT(! status.empty()); instances[ instanceID ] = status; std::string annexName; scratchpad->LookupString( (iName + ".annexName").c_str(), annexName ); // Spot instances don't have an annexName yet. // ASSERT(! annexName.empty() ); annexes[ instanceID ] = annexName; } while( true ); std::string annexID, annexName; scratchpad->LookupString( "AnnexID", annexID ); annexName = annexID.substr( 0, annexID.find( "_" ) ); if( count == 0 ) { std::string errorString; if( annexName.empty() ) { errorString = "Found no instances in any annex."; } else { errorString = "Found no machines in that annex."; } dprintf( D_AUDIT | D_IDENT | D_PID, getuid(), "%s\n", errorString.c_str() ); fprintf( stdout, "%s\n", errorString.c_str() ); goto cleanup; } CondorQuery q( STARTD_AD ); std::string constraint; if( annexName.empty() ) { formatstr( constraint, "IsAnnex" ); } else { formatstr( constraint, "AnnexName == \"%s\"", annexName.c_str() ); } q.addANDConstraint( constraint.c_str() ); ClassAdList cal; CondorError errStack; CollectorList * collectors = CollectorList::create(); /* QueryResult qr = */ collectors->query( q, cal, & errStack ); delete collectors; cal.Rewind(); ClassAd * cad = NULL; while( (cad = cal.Next()) != NULL ) { std::string name, instanceID, aName; cad->LookupString( "Name", name ); cad->LookupString( "EC2InstanceID", instanceID ); cad->LookupString( "AnnexName", aName ); instances[ instanceID ] = "in-pool"; } if( wantClassAds ) { printClassAds( instances, annexID, command, annexes ); } else { printHumanReadable( instances, annexID, annexes ); } } else { std::string errorString; reply->LookupString( ATTR_ERROR_STRING, errorString ); if( errorString.empty() ) { fprintf( stderr, "Status check failed (%s) without an error string.\n", resultString.c_str() ); } else { fprintf( stderr, "%s\n", errorString.c_str() ); } } cleanup: delete reply; reply = NULL; } if( gahp ) { daemonCore->Cancel_Timer( gahp->getNotificationTimerId() ); delete gahp; gahp = NULL; } if( scratchpad ) { delete scratchpad; scratchpad = NULL; } return TRUE; } int StatusReply::rollback() { dprintf( D_FULLDEBUG, "StatusReply::rollback() -- calling operator().\n" ); return (* this)(); }
#include "mpdas.h" CCache* Cache = 0; void CCache::SaveCache() { std::string path = getenv("HOME"); path.append("/.mpdascache"); remove(path.c_str()); std::ofstream ofs(path.c_str()); if(!_entries.size()) { remove(path.c_str()); return; } for(unsigned int i = 0; i < _entries.size(); i++) { centry_t* entry = _entries[i]; if(entry->album) ofs << true << "\n"; ofs << entry->artist << "\n"; ofs << entry->title << "\n"; ofs << entry->time << "\n"; ofs << entry->starttime; if(entry->album) ofs << "\n" << entry->album; if(i+1 == _entries.size()) ofs.flush(); else ofs << std::endl; } ofs.close(); } void CCache::LoadCache() { int length; std::string path = getenv("HOME"); path.append("/.mpdascache"); std::ifstream ifs(path.c_str(), std::ios::in|std::ios::binary); ifs.seekg (0, std::ios::end); length = ifs.tellg(); ifs.seekg (0, std::ios::beg); while(ifs.good()) { if(length == ifs.tellg()) break; std::string artist, album, title; bool gotalbum = false; int time; time_t starttime; ifs >> gotalbum; ifs.ignore(1); ifs >> artist; ifs >> title; ifs >> time; ifs.ignore(1); ifs >> starttime; ifs.ignore(1); if(gotalbum) getline(ifs, album); AddToCache(time, artist, title, album, starttime, true); } ifs.close(); remove(path.c_str()); } void CCache::WorkCache() { if(_failtime && time(NULL) - _failtime < 300) { return; } _failtime = 0; while(_entries.size()) { if(AudioScrobbler->Scrobble(_entries.front())) { curl_free((void*)_entries.front()->artist); curl_free((void*)_entries.front()->title); if(_entries.front()->album) curl_free((void*)_entries.front()->album); delete _entries.front(); _entries.erase(_entries.begin()); } else { eprintf("%s", "Error scrobbling. Trying again in 5 minutes."); _failtime = time(NULL); break; } sleep(1); } SaveCache(); } void CCache::AddToCache(int time, std::string artist, std::string title, std::string album, time_t starttime, bool escaped = false) { centry_t* entry = new centry_t; bzero(entry, sizeof(centry_t)); entry->time = time; if(!escaped) { entry->artist = (char*)curl_escape(artist.c_str(), 0); entry->title = (char*)curl_escape(title.c_str(), 0); if(album.size()) entry->album = (char*)curl_escape(album.c_str(), 0); } else { entry->artist = new char[artist.size()+1]; strcpy(entry->artist, artist.c_str()); entry->title = new char[title.size()+1]; strcpy(entry->title, title.c_str()); if(album.size()) { entry->album = new char[album.size()+1]; strcpy(entry->album, album.c_str()); } } entry->starttime = starttime; _entries.push_back(entry); SaveCache(); } Re-implement re-handshaking after 3 scrobble errors #include "mpdas.h" CCache* Cache = 0; void CCache::SaveCache() { std::string path = getenv("HOME"); path.append("/.mpdascache"); remove(path.c_str()); std::ofstream ofs(path.c_str()); if(!_entries.size()) { remove(path.c_str()); return; } for(unsigned int i = 0; i < _entries.size(); i++) { centry_t* entry = _entries[i]; if(entry->album) ofs << true << "\n"; ofs << entry->artist << "\n"; ofs << entry->title << "\n"; ofs << entry->time << "\n"; ofs << entry->starttime; if(entry->album) ofs << "\n" << entry->album; if(i+1 == _entries.size()) ofs.flush(); else ofs << std::endl; } ofs.close(); } void CCache::LoadCache() { int length; std::string path = getenv("HOME"); path.append("/.mpdascache"); std::ifstream ifs(path.c_str(), std::ios::in|std::ios::binary); ifs.seekg (0, std::ios::end); length = ifs.tellg(); ifs.seekg (0, std::ios::beg); while(ifs.good()) { if(length == ifs.tellg()) break; std::string artist, album, title; bool gotalbum = false; int time; time_t starttime; ifs >> gotalbum; ifs.ignore(1); ifs >> artist; ifs >> title; ifs >> time; ifs.ignore(1); ifs >> starttime; ifs.ignore(1); if(gotalbum) getline(ifs, album); AddToCache(time, artist, title, album, starttime, true); } ifs.close(); remove(path.c_str()); } void CCache::WorkCache() { if(_failtime && time(NULL) - _failtime < 300) { return; } _failtime = 0; while(_entries.size()) { if(AudioScrobbler->Scrobble(_entries.front())) { curl_free((void*)_entries.front()->artist); curl_free((void*)_entries.front()->title); if(_entries.front()->album) curl_free((void*)_entries.front()->album); delete _entries.front(); _entries.erase(_entries.begin()); } else { eprintf("%s", "Error scrobbling. Trying again in 5 minutes."); _failtime = time(NULL); AudioScrobbler->Failure(); break; } sleep(1); } SaveCache(); } void CCache::AddToCache(int time, std::string artist, std::string title, std::string album, time_t starttime, bool escaped = false) { centry_t* entry = new centry_t; bzero(entry, sizeof(centry_t)); entry->time = time; if(!escaped) { entry->artist = (char*)curl_escape(artist.c_str(), 0); entry->title = (char*)curl_escape(title.c_str(), 0); if(album.size()) entry->album = (char*)curl_escape(album.c_str(), 0); } else { entry->artist = new char[artist.size()+1]; strcpy(entry->artist, artist.c_str()); entry->title = new char[title.size()+1]; strcpy(entry->title, title.c_str()); if(album.size()) { entry->album = new char[album.size()+1]; strcpy(entry->album, album.c_str()); } } entry->starttime = starttime; _entries.push_back(entry); SaveCache(); }
/* Copyright 2016 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "realm/realm_config.h" #include "lowlevel_dma.h" #include "accessor.h" #include "realm/threads.h" #include <errno.h> // included for file memory data transfer #include <unistd.h> #ifdef REALM_USE_KERNEL_AIO #include <linux/aio_abi.h> #include <sys/syscall.h> #else #include <aio.h> #endif #include <queue> #define CHECK_PTHREAD(cmd) do { \ int ret = (cmd); \ if(ret != 0) { \ fprintf(stderr, "PTHREAD: %s = %d (%s)\n", #cmd, ret, strerror(ret)); \ exit(1); \ } \ } while(0) using namespace LegionRuntime::Accessor; #include "atomics.h" #include "realm/timers.h" #include "realm/serialize.h" using namespace Realm::Serialization; namespace LegionRuntime { namespace LowLevel { typedef Realm::GASNetMemory GASNetMemory; typedef Realm::DiskMemory DiskMemory; typedef Realm::FileMemory FileMemory; typedef Realm::Thread Thread; typedef Realm::ThreadLaunchParameters ThreadLaunchParameters; typedef Realm::CoreReservation CoreReservation; typedef Realm::CoreReservationParameters CoreReservationParameters; Logger::Category log_dma("dma"); Logger::Category log_aio("aio"); #ifdef EVENT_GRAPH_TRACE extern Logger::Category log_event_graph; extern Event find_enclosing_termination_event(void); #endif typedef std::pair<Memory, Memory> MemPair; typedef std::pair<RegionInstance, RegionInstance> InstPair; typedef std::map<InstPair, OASVec> OASByInst; typedef std::map<MemPair, OASByInst *> OASByMem; class DmaRequest; class DmaRequestQueue { public: DmaRequestQueue(Realm::CoreReservationSet& crs); void enqueue_request(DmaRequest *r); DmaRequest *dequeue_request(bool sleep = true); void shutdown_queue(void); void start_workers(int count); void worker_thread_loop(void); protected: GASNetHSL queue_mutex; GASNetCondVar queue_condvar; std::map<int, std::list<DmaRequest *> *> queues; int queue_sleepers; bool shutdown_flag; CoreReservation core_rsrv; std::vector<Thread *> worker_threads; }; //////////////////////////////////////////////////////////////////////// // // class DmaRequest // DmaRequest::DmaRequest(int _priority, Event _after_copy) : Operation(_after_copy, Realm::ProfilingRequestSet()), state(STATE_INIT), priority(_priority) { } DmaRequest::DmaRequest(int _priority, Event _after_copy, const Realm::ProfilingRequestSet &reqs) : Realm::Operation(_after_copy, reqs), state(STATE_INIT), priority(_priority) { } DmaRequest::~DmaRequest(void) { } void DmaRequest::print(std::ostream& os) const { os << "DmaRequest"; } //////////////////////////////////////////////////////////////////////// // // class DmaRequest::Waiter // DmaRequest::Waiter::Waiter(void) { } DmaRequest::Waiter::~Waiter(void) { } // dma requests come in two flavors: // 1) CopyRequests, which are per memory pair, and // 2) ReduceRequests, which have to be handled monolithically class CopyRequest : public DmaRequest { public: CopyRequest(const void *data, size_t datalen, Event _before_copy, Event _after_copy, int _priority); CopyRequest(const Domain& _domain, OASByInst *_oas_by_inst, Event _before_copy, Event _after_copy, int _priority, const Realm::ProfilingRequestSet &reqs); protected: // deletion performed when reference count goes to zero virtual ~CopyRequest(void); public: size_t compute_size(void) const; void serialize(void *buffer); virtual bool check_readiness(bool just_check, DmaRequestQueue *rq); void perform_dma_mask(MemPairCopier *mpc); template <unsigned DIM> void perform_dma_rect(MemPairCopier *mpc); virtual void perform_dma(void); virtual bool handler_safe(void) { return(false); } Domain domain; OASByInst *oas_by_inst; Event before_copy; Waiter waiter; // if we need to wait on events }; class ReduceRequest : public DmaRequest { public: ReduceRequest(const void *data, size_t datalen, ReductionOpID _redop_id, bool _red_fold, Event _before_copy, Event _after_copy, int _priority); ReduceRequest(const Domain& _domain, const std::vector<Domain::CopySrcDstField>& _srcs, const Domain::CopySrcDstField& _dst, bool _inst_lock_needed, ReductionOpID _redop_id, bool _red_fold, Event _before_copy, Event _after_copy, int _priority, const Realm::ProfilingRequestSet &reqs); protected: // deletion performed when reference count goes to zero virtual ~ReduceRequest(void); public: size_t compute_size(void); void serialize(void *buffer); virtual bool check_readiness(bool just_check, DmaRequestQueue *rq); void perform_dma_mask(MemPairCopier *mpc); template <unsigned DIM> void perform_dma_rect(MemPairCopier *mpc); virtual void perform_dma(void); virtual bool handler_safe(void) { return(false); } Domain domain; std::vector<Domain::CopySrcDstField> srcs; Domain::CopySrcDstField dst; bool inst_lock_needed; Event inst_lock_event; ReductionOpID redop_id; bool red_fold; Event before_copy; Waiter waiter; // if we need to wait on events }; class FillRequest : public DmaRequest { public: FillRequest(const void *data, size_t msglen, RegionInstance inst, unsigned offset, unsigned size, Event _before_fill, Event _after_fill, int priority); FillRequest(const Domain &_domain, const Domain::CopySrcDstField &_dst, const void *fill_value, size_t fill_size, Event _before_fill, Event _after_fill, int priority, const Realm::ProfilingRequestSet &reqs); protected: // deletion performed when reference count goes to zero virtual ~FillRequest(void); public: size_t compute_size(void); void serialize(void *buffer); virtual bool check_readiness(bool just_check, DmaRequestQueue *rq); virtual void perform_dma(void); virtual bool handler_safe(void) { return(false); } template<int DIM> void perform_dma_rect(MemoryImpl *mem_impl); size_t optimize_fill_buffer(RegionInstanceImpl *impl, int &fill_elmts); Domain domain; Domain::CopySrcDstField dst; void *fill_buffer; size_t fill_size; Event before_fill; Waiter waiter; }; DmaRequestQueue::DmaRequestQueue(Realm::CoreReservationSet& crs) : queue_condvar(queue_mutex) , core_rsrv("DMA request queue", crs, CoreReservationParameters()) { queue_sleepers = 0; shutdown_flag = false; } void DmaRequestQueue::shutdown_queue(void) { queue_mutex.lock(); assert(queues.empty()); // set the shutdown flag and wake up any sleepers shutdown_flag = true; queue_condvar.broadcast(); queue_mutex.unlock(); // reap all the threads for(std::vector<Thread *>::iterator it = worker_threads.begin(); it != worker_threads.end(); it++) { (*it)->join(); delete (*it); } worker_threads.clear(); } void DmaRequestQueue::enqueue_request(DmaRequest *r) { // Record that it is ready - check for cancellation though bool ok_to_run = r->mark_ready(); if(!ok_to_run) { r->mark_finished(false /*!successful*/); return; } queue_mutex.lock(); // there's a queue per priority level // priorities are negated so that the highest logical priority comes first int p = -r->priority; std::map<int, std::list<DmaRequest *> *>::iterator it = queues.find(p); if(it == queues.end()) { // nothing at this priority level - make a new list std::list<DmaRequest *> *l = new std::list<DmaRequest *>; l->push_back(r); queues[p] = l; } else { // push ourselves onto the back of the existing queue it->second->push_back(r); } // if anybody was sleeping, wake them up if(queue_sleepers > 0) { queue_sleepers = 0; queue_condvar.broadcast(); } queue_mutex.unlock(); } DmaRequest *DmaRequestQueue::dequeue_request(bool sleep /*= true*/) { queue_mutex.lock(); // quick check - are there any requests at all? while(queues.empty()) { if(!sleep || shutdown_flag) { queue_mutex.unlock(); return 0; } // sleep until there are, or until shutdown queue_sleepers++; queue_condvar.wait(); } // grab the first request from the highest-priority queue there is // priorities are negated so that the highest logical priority comes first std::map<int, std::list<DmaRequest *> *>::iterator it = queues.begin(); assert(!it->second->empty()); DmaRequest *r = it->second->front(); it->second->pop_front(); // if queue is empty, delete from list if(it->second->empty()) { delete it->second; queues.erase(it); } queue_mutex.unlock(); return r; } CopyRequest::CopyRequest(const void *data, size_t datalen, Event _before_copy, Event _after_copy, int _priority) : DmaRequest(_priority, _after_copy), oas_by_inst(0), before_copy(_before_copy) { const IDType *idata = (const IDType *)data; idata = domain.deserialize(idata); oas_by_inst = new OASByInst; size_t num_pairs = *idata++; for (unsigned idx = 0; idx < num_pairs; idx++) { RegionInstance src_inst = ID((IDType)*idata++).convert<RegionInstance>(); RegionInstance dst_inst = ID((IDType)*idata++).convert<RegionInstance>(); InstPair ip(src_inst, dst_inst); // If either one of the instances is in GPU memory increase priority if (priority == 0) { MemoryImpl::MemoryKind src_kind = get_runtime()->get_memory_impl(get_runtime()->get_instance_impl(src_inst)->memory)->kind; if (src_kind == MemoryImpl::MKIND_GPUFB) priority = 1; else { MemoryImpl::MemoryKind dst_kind = get_runtime()->get_memory_impl(get_runtime()->get_instance_impl(dst_inst)->memory)->kind; if (dst_kind == MemoryImpl::MKIND_GPUFB) priority = 1; } } OASVec& oasvec = (*oas_by_inst)[ip]; unsigned count = *idata++; for(unsigned i = 0; i < count; i++) { OffsetsAndSize oas; oas.src_offset = *idata++; oas.dst_offset = *idata++; oas.size = *idata++; oas.serdez_id = *idata++; oasvec.push_back(oas); } } // Unpack any profiling requests // TODO: unbreak once the serialization stuff is repaired //const void *result = requests.deserialize(idata); //Realm::Operation::reconstruct_measurements(); // better have consumed exactly the right amount of data //assert((((unsigned long)result) - ((unsigned long)data)) == datalen); size_t request_size = *reinterpret_cast<const size_t*>(idata); idata += sizeof(size_t) / sizeof(IDType); FixedBufferDeserializer deserializer(idata, request_size); deserializer >> requests; Realm::Operation::reconstruct_measurements(); log_dma.info("dma request %p deserialized - " IDFMT "[%zd]->" IDFMT "[%zd]:%d (+%zd) (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, oas_by_inst->begin()->first.first.id, oas_by_inst->begin()->second[0].src_offset, oas_by_inst->begin()->first.second.id, oas_by_inst->begin()->second[0].dst_offset, oas_by_inst->begin()->second[0].size, oas_by_inst->begin()->second.size() - 1, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); } CopyRequest::CopyRequest(const Domain& _domain, OASByInst *_oas_by_inst, Event _before_copy, Event _after_copy, int _priority, const Realm::ProfilingRequestSet &reqs) : DmaRequest(_priority, _after_copy, reqs), domain(_domain), oas_by_inst(_oas_by_inst), before_copy(_before_copy) { log_dma.info() << "dma request " << (void *)this << " created - is=" << domain << " before=" << before_copy << " after=" << get_finish_event(); for(OASByInst::const_iterator it = oas_by_inst->begin(); it != oas_by_inst->end(); it++) for(OASVec::const_iterator it2 = it->second.begin(); it2 != it->second.end(); it2++) log_dma.info() << "dma request " << (void *)this << " field: " << it->first.first << "[" << it2->src_offset << "]->" << it->first.second << "[" << it2->dst_offset << "] size=" << it2->size; } CopyRequest::~CopyRequest(void) { delete oas_by_inst; } size_t CopyRequest::compute_size(void) const { size_t result = domain.compute_size(); result += sizeof(IDType); // number of requests; for(OASByInst::iterator it2 = oas_by_inst->begin(); it2 != oas_by_inst->end(); it2++) { OASVec& oasvec = it2->second; result += (3 + oasvec.size() * 4) * sizeof(IDType); } // TODO: unbreak once the serialization stuff is repaired //result += requests.compute_size(); ByteCountSerializer counter; counter << requests; result += sizeof(size_t) + counter.bytes_used(); return result; } void CopyRequest::serialize(void *buffer) { // domain info goes first IDType *msgptr = domain.serialize((IDType *)buffer); *msgptr++ = oas_by_inst->size(); // now OAS vectors for(OASByInst::iterator it2 = oas_by_inst->begin(); it2 != oas_by_inst->end(); it2++) { RegionInstance src_inst = it2->first.first; RegionInstance dst_inst = it2->first.second; OASVec& oasvec = it2->second; *msgptr++ = src_inst.id; *msgptr++ = dst_inst.id; *msgptr++ = oasvec.size(); for(OASVec::iterator it3 = oasvec.begin(); it3 != oasvec.end(); it3++) { *msgptr++ = it3->src_offset; *msgptr++ = it3->dst_offset; *msgptr++ = it3->size; *msgptr++ = it3->serdez_id; } } // TODO: unbreak once the serialization stuff is repaired //requests.serialize(msgptr); // We sent this message remotely, so we need to clear the profiling // so it doesn't get sent accidentally ByteCountSerializer counter; counter << requests; *reinterpret_cast<size_t*>(msgptr) = counter.bytes_used(); msgptr += sizeof(size_t) / sizeof(IDType); FixedBufferSerializer serializer(msgptr, counter.bytes_used()); serializer << requests; clear_profiling(); } void DmaRequest::Waiter::sleep_on_event(Event e, Reservation l /*= Reservation::NO_RESERVATION*/) { current_lock = l; EventImpl::add_waiter(e, this); } bool DmaRequest::Waiter::event_triggered(Event e, bool poisoned) { if(poisoned) { Realm::log_poison.info() << "cancelling poisoned dma operation - op=" << req << " after=" << req->get_finish_event(); // cancel the dma operation - this has to work bool did_cancel = req->attempt_cancellation(Realm::Faults::ERROR_POISONED_PRECONDITION, &e, sizeof(e)); assert(did_cancel); return false; } log_dma.info("request %p triggered in state %d (lock = " IDFMT ")", req, req->state, current_lock.id); if(current_lock.exists()) { current_lock.release(); current_lock = Reservation::NO_RESERVATION; } // this'll enqueue the DMA if it can, or wait on another event if it // can't req->check_readiness(false, queue); // don't delete us! return false; } void DmaRequest::Waiter::print(std::ostream& os) const { os << "dma request " << req << ": after " << req->get_finish_event(); } bool CopyRequest::check_readiness(bool just_check, DmaRequestQueue *rq) { if(state == STATE_INIT) state = STATE_METADATA_FETCH; // remember which queue we're going to be assigned to if we sleep waiter.req = this; waiter.queue = rq; // make sure our node has all the meta data it needs, but don't take more than one lock // at a time if(state == STATE_METADATA_FETCH) { // index space first if(domain.get_dim() == 0) { IndexSpaceImpl *is_impl = get_runtime()->get_index_space_impl(domain.get_index_space()); if(!is_impl->locked_data.valid) { log_dma.info("dma request %p - no index space metadata yet", this); if(just_check) return false; Event e = is_impl->lock.acquire(1, false); if(e.has_triggered()) { log_dma.info("request %p - index space metadata invalid - instant trigger", this); is_impl->lock.release(); } else { log_dma.info("request %p - index space metadata invalid - sleeping on lock " IDFMT "", this, is_impl->lock.me.id); waiter.sleep_on_event(e, is_impl->lock.me); return false; } } // we need more than just the metadata - we also need the valid mask { Event e = is_impl->request_valid_mask(); if(!e.has_triggered()) { log_dma.info("request %p - valid mask needed for index space " IDFMT " - sleeping on event " IDFMT "/%d", this, domain.get_index_space().id, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // now go through all instance pairs for(OASByInst::iterator it = oas_by_inst->begin(); it != oas_by_inst->end(); it++) { RegionInstanceImpl *src_impl = get_runtime()->get_instance_impl(it->first.first); RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(it->first.second); { Event e = src_impl->request_metadata(); if(!e.has_triggered()) { if(just_check) { log_dma.info("dma request %p - no src instance (" IDFMT ") metadata yet", this, src_impl->me.id); return false; } log_dma.info("request %p - src instance metadata invalid - sleeping on event " IDFMT "/%d", this, e.id, e.gen); waiter.sleep_on_event(e); return false; } } { Event e = dst_impl->request_metadata(); if(!e.has_triggered()) { if(just_check) { log_dma.info("dma request %p - no dst instance (" IDFMT ") metadata yet", this, dst_impl->me.id); return false; } log_dma.info("request %p - dst instance metadata invalid - sleeping on event " IDFMT "/%d", this, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // if we got all the way through, we've got all the metadata we need state = STATE_BEFORE_EVENT; } // make sure our functional precondition has occurred if(state == STATE_BEFORE_EVENT) { // has the before event triggered? if not, wait on it if(before_copy.has_triggered()) { log_dma.info("request %p - before event triggered", this); state = STATE_READY; } else { log_dma.info("request %p - before event not triggered", this); if(just_check) return false; log_dma.info("request %p - sleeping on before event", this); waiter.sleep_on_event(before_copy); return false; } } if(state == STATE_READY) { log_dma.info("request %p ready", this); if(just_check) return true; state = STATE_QUEUED; assert(rq != 0); log_dma.info("request %p enqueued", this); // once we're enqueued, we may be deleted at any time, so no more // references rq->enqueue_request(this); return true; } if(state == STATE_QUEUED) return true; assert(0); return false; } namespace RangeExecutors { class Memcpy { public: Memcpy(void *_dst_base, const void *_src_base, size_t _elmt_size) : dst_base((char *)_dst_base), src_base((const char *)_src_base), elmt_size(_elmt_size) {} template <class T> Memcpy(T *_dst_base, const T *_src_base) : dst_base((char *)_dst_base), src_base((const char *)_src_base), elmt_size(sizeof(T)) {} void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; memcpy(dst_base + byte_offset, src_base + byte_offset, byte_count); } protected: char *dst_base; const char *src_base; size_t elmt_size; }; class GasnetPut { public: GasnetPut(MemoryImpl *_tgt_mem, off_t _tgt_offset, const void *_src_ptr, size_t _elmt_size) : tgt_mem(_tgt_mem), tgt_offset(_tgt_offset), src_ptr((const char *)_src_ptr), elmt_size(_elmt_size) {} virtual ~GasnetPut(void) { } void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; tgt_mem->put_bytes(tgt_offset + byte_offset, src_ptr + byte_offset, byte_count); } protected: MemoryImpl *tgt_mem; off_t tgt_offset; const char *src_ptr; size_t elmt_size; }; class GasnetPutBatched { public: GasnetPutBatched(MemoryImpl *_tgt_mem, off_t _tgt_offset, const void *_src_ptr, size_t _elmt_size) : tgt_mem((GASNetMemory *)_tgt_mem), tgt_offset(_tgt_offset), src_ptr((const char *)_src_ptr), elmt_size(_elmt_size) {} void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; offsets.push_back(tgt_offset + byte_offset); srcs.push_back(src_ptr + byte_offset); sizes.push_back(byte_count); } void finish(void) { if(offsets.size() > 0) { DetailedTimer::ScopedPush sp(TIME_SYSTEM); tgt_mem->put_batch(offsets.size(), &offsets[0], &srcs[0], &sizes[0]); } } protected: GASNetMemory *tgt_mem; off_t tgt_offset; const char *src_ptr; size_t elmt_size; std::vector<off_t> offsets; std::vector<const void *> srcs; std::vector<size_t> sizes; }; class GasnetPutReduce : public GasnetPut { public: GasnetPutReduce(MemoryImpl *_tgt_mem, off_t _tgt_offset, const ReductionOpUntyped *_redop, bool _redfold, const void *_src_ptr, size_t _elmt_size) : GasnetPut(_tgt_mem, _tgt_offset, _src_ptr, _elmt_size), redop(_redop), redfold(_redfold) {} virtual ~GasnetPutReduce(void) { } void do_span(int offset, int count) { assert(redfold == false); off_t tgt_byte_offset = offset * redop->sizeof_lhs; off_t src_byte_offset = offset * elmt_size; assert(elmt_size == redop->sizeof_rhs); char buffer[1024]; assert(redop->sizeof_lhs <= 1024); for(int i = 0; i < count; i++) { tgt_mem->get_bytes(tgt_offset + tgt_byte_offset, buffer, redop->sizeof_lhs); redop->apply(buffer, src_ptr + src_byte_offset, 1, true); tgt_mem->put_bytes(tgt_offset + tgt_byte_offset, buffer, redop->sizeof_lhs); } } protected: const ReductionOpUntyped *redop; bool redfold; }; class GasnetPutRedList : public GasnetPut { public: GasnetPutRedList(MemoryImpl *_tgt_mem, off_t _tgt_offset, ReductionOpID _redopid, const ReductionOpUntyped *_redop, const void *_src_ptr, size_t _elmt_size) : GasnetPut(_tgt_mem, _tgt_offset, _src_ptr, _elmt_size), redopid(_redopid), redop(_redop) {} virtual ~GasnetPutRedList(void) { } void do_span(int offset, int count) { if(count == 0) return; assert(offset == 0); // too lazy to do pointer math on _src_ptr unsigned *ptrs = new unsigned[count]; redop->get_list_pointers(ptrs, src_ptr, count); // now figure out how many reductions go to each node unsigned *nodecounts = new unsigned[gasnet_nodes()]; for(unsigned i = 0; i < gasnet_nodes(); i++) nodecounts[i] = 0; for(int i = 0; i < count; i++) { off_t elem_offset = tgt_offset + ptrs[i] * redop->sizeof_lhs; int home_node = tgt_mem->get_home_node(elem_offset, redop->sizeof_lhs); assert(home_node >= 0); ptrs[i] = home_node; nodecounts[home_node]++; } size_t max_entries_per_msg = (1 << 20) / redop->sizeof_list_entry; char *entry_buffer = new char[max_entries_per_msg * redop->sizeof_list_entry]; for(unsigned i = 0; i < gasnet_nodes(); i++) { unsigned pos = 0; for(int j = 0; j < count; j++) { //printf("S: [%d] = %d\n", j, ptrs[j]); if(ptrs[j] != i) continue; memcpy(entry_buffer + (pos * redop->sizeof_list_entry), ((const char *)src_ptr) + (j * redop->sizeof_list_entry), redop->sizeof_list_entry); pos++; if(pos == max_entries_per_msg) { if(i == gasnet_mynode()) { tgt_mem->apply_reduction_list(tgt_offset, redop, pos, entry_buffer); } else { do_remote_apply_red_list(i, tgt_mem->me, tgt_offset, redopid, entry_buffer, pos * redop->sizeof_list_entry, 0); } pos = 0; } } if(pos > 0) { if(i == gasnet_mynode()) { tgt_mem->apply_reduction_list(tgt_offset, redop, pos, entry_buffer); } else { do_remote_apply_red_list(i, tgt_mem->me, tgt_offset, redopid, entry_buffer, pos * redop->sizeof_list_entry, 0); } } } delete[] entry_buffer; delete[] ptrs; delete[] nodecounts; } protected: ReductionOpID redopid; const ReductionOpUntyped *redop; }; class GasnetGet { public: GasnetGet(void *_tgt_ptr, MemoryImpl *_src_mem, off_t _src_offset, size_t _elmt_size) : tgt_ptr((char *)_tgt_ptr), src_mem(_src_mem), src_offset(_src_offset), elmt_size(_elmt_size) {} void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; DetailedTimer::ScopedPush sp(TIME_SYSTEM); src_mem->get_bytes(src_offset + byte_offset, tgt_ptr + byte_offset, byte_count); } protected: char *tgt_ptr; MemoryImpl *src_mem; off_t src_offset; size_t elmt_size; }; class GasnetGetBatched { public: GasnetGetBatched(void *_tgt_ptr, MemoryImpl *_src_mem, off_t _src_offset, size_t _elmt_size) : tgt_ptr((char *)_tgt_ptr), src_mem((GASNetMemory *)_src_mem), src_offset(_src_offset), elmt_size(_elmt_size) {} void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; offsets.push_back(src_offset + byte_offset); dsts.push_back(tgt_ptr + byte_offset); sizes.push_back(byte_count); } void finish(void) { if(offsets.size() > 0) { DetailedTimer::ScopedPush sp(TIME_SYSTEM); src_mem->get_batch(offsets.size(), &offsets[0], &dsts[0], &sizes[0]); } } protected: char *tgt_ptr; GASNetMemory *src_mem; off_t src_offset; size_t elmt_size; std::vector<off_t> offsets; std::vector<void *> dsts; std::vector<size_t> sizes; }; class GasnetGetAndPut { public: GasnetGetAndPut(MemoryImpl *_tgt_mem, off_t _tgt_offset, MemoryImpl *_src_mem, off_t _src_offset, size_t _elmt_size) : tgt_mem(_tgt_mem), tgt_offset(_tgt_offset), src_mem(_src_mem), src_offset(_src_offset), elmt_size(_elmt_size) {} static const size_t CHUNK_SIZE = 16384; void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; while(byte_count > CHUNK_SIZE) { src_mem->get_bytes(src_offset + byte_offset, chunk, CHUNK_SIZE); tgt_mem->put_bytes(tgt_offset + byte_offset, chunk, CHUNK_SIZE); byte_offset += CHUNK_SIZE; byte_count -= CHUNK_SIZE; } if(byte_count > 0) { src_mem->get_bytes(src_offset + byte_offset, chunk, byte_count); tgt_mem->put_bytes(tgt_offset + byte_offset, chunk, byte_count); } } protected: MemoryImpl *tgt_mem; off_t tgt_offset; MemoryImpl *src_mem; off_t src_offset; size_t elmt_size; char chunk[CHUNK_SIZE]; }; #ifdef DEAD_DMA_CODE class RemoteWrite { public: RemoteWrite(Memory _tgt_mem, off_t _tgt_offset, const void *_src_ptr, size_t _elmt_size, Event _event) : tgt_mem(_tgt_mem), tgt_offset(_tgt_offset), src_ptr((const char *)_src_ptr), elmt_size(_elmt_size), event(_event), span_count(0) {} void do_span(int offset, int count) { // if this isn't the first span, push the previous one out before // we overwrite it if(span_count > 0) really_do_span(false); span_count++; prev_offset = offset; prev_count = count; } Event finish(void) { log_dma.debug("remote write done with %d spans", span_count); // if we got any spans, the last one is still waiting to go out if(span_count > 0) { really_do_span(true); return Event::NO_EVENT; // recipient will trigger the event } return event; } protected: void really_do_span(bool last) { off_t byte_offset = prev_offset * elmt_size; size_t byte_count = prev_count * elmt_size; // if we don't have an event for our completion, we need one now if(!event.exists()) event = GenEventImpl::create_genevent()->current_event(); DetailedTimer::ScopedPush sp(TIME_SYSTEM); do_remote_write(tgt_mem, tgt_offset + byte_offset, src_ptr + byte_offset, byte_count, 0, last ? event : Event::NO_EVENT); } Memory tgt_mem; off_t tgt_offset; const char *src_ptr; size_t elmt_size; Event event; int span_count; int prev_offset, prev_count; }; #endif }; // namespace RangeExecutors // helper function to figure out which field we're in void find_field_start(const std::vector<size_t>& field_sizes, off_t byte_offset, size_t size, off_t& field_start, int& field_size) { off_t start = 0; for(std::vector<size_t>::const_iterator it = field_sizes.begin(); it != field_sizes.end(); it++) { assert((*it) > 0); if(byte_offset < (off_t)(*it)) { assert((byte_offset + size) <= (*it)); field_start = start; field_size = (*it); return; } start += (*it); byte_offset -= (*it); } assert(0); } class RemoteWriteInstPairCopier : public InstPairCopier { public: RemoteWriteInstPairCopier(RegionInstance src_inst, RegionInstance dst_inst, OASVec &_oas_vec) : src_acc(src_inst.get_accessor()), dst_acc(dst_inst.get_accessor()), oas_vec(_oas_vec) {} virtual ~RemoteWriteInstPairCopier(void) { } virtual void copy_field(int src_index, int dst_index, int elem_count, unsigned offset_index) { unsigned src_offset = oas_vec[offset_index].src_offset; unsigned dst_offset = oas_vec[offset_index].dst_offset; unsigned bytes = oas_vec[offset_index].size; char buffer[1024]; for(int i = 0; i < elem_count; i++) { src_acc.read_untyped(ptr_t(src_index + i), buffer, bytes, src_offset); if(0 && i == 0) { printf("remote write: (%d:%d->%d:%d) %d bytes:", src_index + i, src_offset, dst_index + i, dst_offset, bytes); for(unsigned j = 0; j < bytes; j++) printf(" %02x", (unsigned char)(buffer[j])); printf("\n"); } dst_acc.write_untyped(ptr_t(dst_index + i), buffer, bytes, dst_offset); } } virtual void flush(void) {} protected: RegionAccessor<AccessorType::Generic> src_acc; RegionAccessor<AccessorType::Generic> dst_acc; OASVec &oas_vec; }; //////////////////////////////////////////////////////////////////////// // // class MemPairCopier // MemPairCopier::MemPairCopier(void) : total_reqs(0), total_bytes(0) { } MemPairCopier::~MemPairCopier(void) { } // default behavior of flush is just to report bytes (maybe) void MemPairCopier::flush(DmaRequest *req) { #ifdef EVENT_GRAPH_TRACE log_event_graph.debug("Copy Size: (" IDFMT ",%d) %ld", after_copy.id, after_copy.gen, total_bytes); report_bytes(after_copy); #endif } void MemPairCopier::record_bytes(size_t bytes) { total_reqs++; total_bytes += bytes; } //////////////////////////////////////////////////////////////////////// // // class MemPairCopierFactory // MemPairCopierFactory::MemPairCopierFactory(const std::string& _name) : name(_name) { } MemPairCopierFactory::~MemPairCopierFactory(void) { } const std::string& MemPairCopierFactory::get_name(void) const { return name; } class BufferedMemPairCopier : public MemPairCopier { public: BufferedMemPairCopier(Memory _src_mem, Memory _dst_mem, size_t _buffer_size = 32768) : buffer_size(_buffer_size) { src_mem = get_runtime()->get_memory_impl(_src_mem); dst_mem = get_runtime()->get_memory_impl(_dst_mem); buffer = new char[buffer_size]; } virtual ~BufferedMemPairCopier(void) { delete[] buffer; } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<BufferedMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("buffered copy of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); while(bytes > buffer_size) { src_mem->get_bytes(src_offset, buffer, buffer_size); dst_mem->put_bytes(dst_offset, buffer, buffer_size); src_offset += buffer_size; dst_offset += buffer_size; bytes -= buffer_size; record_bytes(buffer_size); } if(bytes > 0) { src_mem->get_bytes(src_offset, buffer, bytes); dst_mem->put_bytes(dst_offset, buffer, bytes); record_bytes(bytes); } } // default behavior of 2D copy is to unroll to 1D copies void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: size_t buffer_size; MemoryImpl *src_mem, *dst_mem; char *buffer; }; class MemcpyMemPairCopier : public MemPairCopier { public: MemcpyMemPairCopier(Memory _src_mem, Memory _dst_mem) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_impl->get_direct_ptr(0, src_impl->size)); assert(src_base); MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); assert(dst_base); } virtual ~MemcpyMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<MemcpyMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("memcpy of %zd bytes\n", bytes); memcpy(dst_base + dst_offset, src_base + src_offset, bytes); record_bytes(bytes); } // default behavior of 2D copy is to unroll to 1D copies void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: const char *src_base; char *dst_base; }; class LocalReductionMemPairCopier : public MemPairCopier { public: LocalReductionMemPairCopier(Memory _src_mem, Memory _dst_mem, ReductionOpID redop_id, bool _fold) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_impl->get_direct_ptr(0, src_impl->size)); assert(src_base); MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); assert(dst_base); redop = get_runtime()->reduce_op_table[redop_id]; fold = _fold; } virtual ~LocalReductionMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<LocalReductionMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("reduction of %zd bytes\n", bytes); assert((bytes % redop->sizeof_rhs) == 0); if(fold) redop->fold(dst_base + dst_offset, src_base + src_offset, bytes / redop->sizeof_rhs, false /*non-exclusive*/); else redop->apply(dst_base + dst_offset, src_base + src_offset, bytes / redop->sizeof_rhs, false /*non-exclusive*/); } // default behavior of 2D copy is to unroll to 1D copies void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { // two cases here: // 1) if bytes == sizeof_rhs, we can use the apply/fold_strided calls if(bytes == redop->sizeof_rhs) { if(fold) redop->fold_strided(dst_base + dst_offset, src_base + src_offset, src_stride, dst_stride, lines, false /*non-exclusive*/); else redop->apply_strided(dst_base + dst_offset, src_base + src_offset, src_stride, dst_stride, lines, false /*non-exclusive*/); return; } // 2) with multiple elements per line, have to do a apply/fold call per line while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: const char *src_base; char *dst_base; const ReductionOpUntyped *redop; bool fold; }; class BufferedReductionMemPairCopier : public MemPairCopier { public: BufferedReductionMemPairCopier(Memory _src_mem, Memory _dst_mem, ReductionOpID redop_id, bool _fold, size_t _buffer_size = 1024) // in elements : buffer_size(_buffer_size) { src_mem = get_runtime()->get_memory_impl(_src_mem); dst_mem = get_runtime()->get_memory_impl(_dst_mem); redop = get_runtime()->reduce_op_table[redop_id]; fold = _fold; src_buffer = new char[buffer_size * redop->sizeof_rhs]; dst_buffer = new char[buffer_size * (fold ? redop->sizeof_rhs : redop->sizeof_lhs)]; } virtual ~BufferedReductionMemPairCopier(void) { delete[] src_buffer; delete[] dst_buffer; } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<BufferedReductionMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("buffered copy of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); size_t dst_size = fold ? redop->sizeof_rhs : redop->sizeof_lhs; assert((bytes % redop->sizeof_rhs) == 0); size_t elems = bytes / redop->sizeof_rhs; while(elems > 0) { // figure out how many elements we can do at a time size_t count = (elems > buffer_size) ? buffer_size : elems; // fetch source and dest data into buffers src_mem->get_bytes(src_offset, src_buffer, count * redop->sizeof_rhs); dst_mem->get_bytes(dst_offset, dst_buffer, count * dst_size); // apply reduction to local buffers if(fold) redop->fold(dst_buffer, src_buffer, count, true /*exclusive*/); else redop->apply(dst_buffer, src_buffer, count, true /*exclusive*/); dst_mem->put_bytes(dst_offset, dst_buffer, count * dst_size); src_offset += count * redop->sizeof_rhs; dst_offset += count * dst_size; elems -= count; } } // default behavior of 2D copy is to unroll to 1D copies void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: size_t buffer_size; MemoryImpl *src_mem, *dst_mem; char *src_buffer; char *dst_buffer; const ReductionOpUntyped *redop; bool fold; }; #if 0 // a MemPairCopier that keeps a list of events for component copies and doesn't trigger // the completion event until they're all done class DelayedMemPairCopierX : public MemPairCopier { public: DelayedMemPairCopierX(void) {} virtual ~DelayedMemPairCopierX(void) {} virtual void flush(Event after_copy) { // create a merged event for all the copies and used that to perform a delayed trigger // of the after_copy event (if it exists) if(after_copy.exists()) { if(events.size() > 0) { Event merged = GenEventImpl::merge_events(events); // deferred trigger based on this merged event get_runtime()->get_genevent_impl(after_copy)->trigger(after_copy.gen, gasnet_mynode(), merged); } else { // no actual copies occurred, so manually trigger event ourselves get_runtime()->get_genevent_impl(after_copy)->trigger(after_copy.gen, gasnet_mynode()); } } else { if(events.size() > 0) { // we don't have an event we can use to signal completion, so wait on the events ourself for(std::set<Event>::const_iterator it = events.begin(); it != events.end(); it++) (*it).wait(); } else { // nothing happened and we don't need to tell anyone - life is simple } } #ifdef EVENT_GRAPH_TRACE report_bytes(after_copy); #endif } protected: std::set<Event> events; }; #endif static unsigned rdma_sequence_no = 1; class RemoteWriteMemPairCopier : public MemPairCopier { public: RemoteWriteMemPairCopier(Memory _src_mem, Memory _dst_mem) { src_mem = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_mem->get_direct_ptr(0, src_mem->size)); assert(src_base); dst_mem = get_runtime()->get_memory_impl(_dst_mem); #ifdef TIME_REMOTE_WRITES span_time = 0; gather_time = 0; #endif sequence_id = __sync_fetch_and_add(&rdma_sequence_no, 1); num_writes = 0; } virtual ~RemoteWriteMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<RemoteWriteMemPairCopier>(this, src_inst, dst_inst, oas_vec); } struct PendingGather { off_t dst_start; off_t dst_size; SpanList src_spans; }; // this is no longer limited by LMB size, so try for large blocks when // possible static const size_t TARGET_XFER_SIZE = 4 << 20; void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("remote write of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #ifdef TIME_REMOTE_WRITES unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif record_bytes(bytes); if(bytes >= TARGET_XFER_SIZE) { // large enough that we can transfer it by itself #ifdef DEBUG_REMOTE_WRITES printf("remote write of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #endif num_writes += do_remote_write(dst_mem->me, dst_offset, src_base + src_offset, bytes, sequence_id, false /* no copy */); } else { // see if this can be added to an existing gather PendingGather *g; std::map<off_t, PendingGather *>::iterator it = gathers.find(dst_offset); if(it != gathers.end()) { g = it->second; gathers.erase(it); // remove from the existing location - we'll re-add it (probably) with the updated offset } else { // nope, start a new one g = new PendingGather; g->dst_start = dst_offset; g->dst_size = 0; } // sanity checks assert((g->dst_start + g->dst_size) == dst_offset); // now see if this particular span is disjoint or can be tacked on to the end of the last one if(g->src_spans.size() > 0) { SpanListEntry& last_span = g->src_spans.back(); if(((char *)(last_span.first) + last_span.second) == (src_base + src_offset)) { // append last_span.second += bytes; } else { g->src_spans.push_back(std::make_pair(src_base + src_offset, bytes)); } } else { // first span g->src_spans.push_back(std::make_pair(src_base + src_offset, bytes)); } g->dst_size += bytes; // is this span big enough to push now? if((size_t)g->dst_size >= TARGET_XFER_SIZE) { // yes, copy it copy_gather(g); delete g; } else { // no, put it back in the pending list, keyed by the next dst_offset that'll match it gathers.insert(std::make_pair(g->dst_start + g->dst_size, g)); } } #ifdef TIME_REMOTE_WRITES unsigned long long stop = TimeStamp::get_current_time_in_micros(); span_time += (stop - start); #endif } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { // case 1: although described as 2D, both src and dst coalesce if(((size_t)src_stride == bytes) && ((size_t)dst_stride == bytes)) { copy_span(src_offset, dst_offset, bytes * lines); return; } // case 2: if dst coalesces, we'll let the RDMA code do the gather for us - // this won't merge with any other copies though if((size_t)dst_stride == bytes) { #ifdef NEW2D_DEBUG printf("GATHER copy\n"); #endif num_writes += do_remote_write(dst_mem->me, dst_offset, src_base + src_offset, bytes, src_stride, lines, sequence_id, false /* no copy */); record_bytes(bytes * lines); return; } // default is to unroll the lines here, and let the PendingGather code try to // put things back in bigger pieces while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } void copy_gather(const PendingGather *g) { #ifdef TIME_REMOTE_WRITES unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif // special case: if there's only one source span, it's not actually // a gather (so we don't need to make a copy) if(g->src_spans.size() == 1) { const SpanListEntry& span = *(g->src_spans.begin()); #ifdef DEBUG_REMOTE_WRITES printf("remote write of %zd bytes (singleton " IDFMT ":%zd -> " IDFMT ":%zd)\n", span.second, src_mem->me.id, (char *)span.first - src_base, dst_mem->me.id, g->dst_start); printf(" datb[%p]: %08x %08x %08x %08x %08x %08x %08x %08x\n", span.first, ((unsigned *)(span.first))[0], ((unsigned *)(span.first))[1], ((unsigned *)(span.first))[2], ((unsigned *)(span.first))[3], ((unsigned *)(span.first))[4], ((unsigned *)(span.first))[5], ((unsigned *)(span.first))[6], ((unsigned *)(span.first))[7]); #endif // TODO: handle case where single write can include event trigger in message //num_writes += do_remote_write(dst_mem->me, g->dst_start, span.first, span.second, trigger, false /* no copy */); num_writes += do_remote_write(dst_mem->me, g->dst_start, span.first, span.second, sequence_id, false /* no copy */); return; } // general case: do_remote_write knows how to take a span list now, so let it // handle the actual gathering #ifdef DEBUG_REMOTE_WRITES printf("remote write of %zd bytes (gather -> " IDFMT ":%zd), trigger=" IDFMT "/%d\n", g->dst_size, dst_mem->me.id, g->dst_start, trigger.id, trigger.gen); #endif // TODO: handle case where single write can include event trigger in message num_writes += do_remote_write(dst_mem->me, g->dst_start, g->src_spans, g->dst_size, sequence_id, false /* no copy - data won't change til copy event triggers */); #ifdef TIME_REMOTE_WRITES unsigned long long stop = TimeStamp::get_current_time_in_micros(); gather_time += (stop - start); #endif } virtual void flush(DmaRequest *req) { #ifdef TIME_REMOTE_WRITES size_t total_gathers = gathers.size(); size_t total_spans = 0; for (std::map<off_t,PendingGather*>::const_iterator it = gathers.begin(); it != gathers.end(); it++) { total_spans += it->second->src_spans.size(); } unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif // do we have any pending gathers to push out? while(!gathers.empty()) { std::map<off_t, PendingGather *>::iterator it = gathers.begin(); PendingGather *g = it->second; gathers.erase(it); copy_gather(g); delete g; } // if we did any remote writes, we need a fence, and the DMA request // needs to know about it if(total_reqs > 0) { Realm::RemoteWriteFence *fence = new Realm::RemoteWriteFence(req); req->add_async_work_item(fence); do_remote_fence(dst_mem->me, sequence_id, num_writes, fence); } #ifdef TIME_REMOTE_WRITES unsigned long long stop = TimeStamp::get_current_time_in_micros(); gather_time += (stop - start); printf("Remote Write: span time: %lld gather time %lld " "total gathers %ld total spans %d\n", span_time, gather_time, total_gathers, total_spans); #endif MemPairCopier::flush(req); } protected: MemoryImpl *src_mem, *dst_mem; const char *src_base; std::map<off_t, PendingGather *> gathers; #ifdef TIME_REMOTE_WRITES unsigned long long span_time; unsigned long long gather_time; #endif unsigned sequence_id, num_writes; }; class RemoteReduceMemPairCopier : public MemPairCopier { public: RemoteReduceMemPairCopier(Memory _src_mem, Memory _dst_mem, ReductionOpID _redop_id, bool _fold) { src_mem = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_mem->get_direct_ptr(0, src_mem->size)); assert(src_base); dst_mem = get_runtime()->get_memory_impl(_dst_mem); redop_id = _redop_id; redop = get_runtime()->reduce_op_table[redop_id]; fold = _fold; sequence_id = __sync_fetch_and_add(&rdma_sequence_no, 1); num_writes = 0; } virtual ~RemoteReduceMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<RemoteReduceMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("remote write of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #ifdef TIME_REMOTE_WRITES unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif #ifdef DEBUG_REMOTE_WRITES printf("remote reduce of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #endif num_writes += do_remote_reduce(dst_mem->me, dst_offset, redop_id, fold, src_base + src_offset, bytes / redop->sizeof_rhs, redop->sizeof_rhs, redop->sizeof_lhs, sequence_id, false /* no copy */); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { // TODO: figure out 2D coalescing for reduction case (sizes may not match) //if((src_stride == bytes) && (dst_stride == bytes)) { // copy_span(src_offset, dst_offset, bytes * lines); // return; //} // default is to unroll the lines here while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } virtual void flush(DmaRequest *req) { // if we did any remote writes, we need a fence, and the DMA request // needs to know about it if(total_reqs > 0) { Realm::RemoteWriteFence *fence = new Realm::RemoteWriteFence(req); req->add_async_work_item(fence); do_remote_fence(dst_mem->me, sequence_id, num_writes, fence); } MemPairCopier::flush(req); } protected: MemoryImpl *src_mem, *dst_mem; const char *src_base; unsigned sequence_id, num_writes; ReductionOpID redop_id; const ReductionOpUntyped *redop; bool fold; }; class RemoteSerdezMemPairCopier : public MemPairCopier { public: RemoteSerdezMemPairCopier(Memory _src_mem, Memory _dst_mem, CustomSerdezID _serdez_id) { src_mem = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_mem->get_direct_ptr(0, src_mem->size)); assert(src_base); dst_mem = get_runtime()->get_memory_impl(_dst_mem); serdez_id = _serdez_id; serdez_op = get_runtime()->custom_serdez_table[serdez_id]; sequence_id = __sync_fetch_and_add(&rdma_sequence_no, 1); num_writes = 0; } virtual ~RemoteSerdezMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<RemoteSerdezMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("remote write of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #ifdef TIME_REMOTE_WRITES unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif #ifdef DEBUG_REMOTE_WRITES printf("remote serdez of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #endif num_writes += do_remote_serdez(dst_mem->me, dst_offset, serdez_id, src_base + src_offset, bytes / serdez_op->sizeof_field_type, sequence_id); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { // TODO: figure out 2D coalescing for reduction case (sizes may not match) //if((src_stride == bytes) && (dst_stride == bytes)) { // copy_span(src_offset, dst_offset, bytes * lines); // return; //} // default is to unroll the lines here while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } virtual void flush(DmaRequest *req) { // if we did any remote writes, we need a fence, and the DMA request // needs to know about it if(total_reqs > 0) { Realm::RemoteWriteFence *fence = new Realm::RemoteWriteFence(req); req->add_async_work_item(fence); do_remote_fence(dst_mem->me, sequence_id, num_writes, fence); } MemPairCopier::flush(req); } protected: MemoryImpl *src_mem, *dst_mem; const char *src_base; unsigned sequence_id, num_writes; CustomSerdezID serdez_id; const CustomSerdezUntyped *serdez_op; }; class AsyncFileIOContext { public: AsyncFileIOContext(int _max_depth); ~AsyncFileIOContext(void); void enqueue_write(int fd, size_t offset, size_t bytes, const void *buffer); void enqueue_read(int fd, size_t offset, size_t bytes, void *buffer); void enqueue_fence(DmaRequest *req); bool empty(void); void make_progress(void); class AIOOperation { public: virtual ~AIOOperation(void) {} virtual void launch(void) = 0; virtual bool check_completion(void) = 0; bool completed; }; int max_depth; std::deque<AIOOperation *> launched_operations, pending_operations; GASNetHSL mutex; #ifdef REALM_USE_KERNEL_AIO aio_context_t aio_ctx; #endif }; static AsyncFileIOContext *aio_context = 0; #ifdef REALM_USE_KERNEL_AIO inline int io_setup(unsigned nr, aio_context_t *ctxp) { return syscall(__NR_io_setup, nr, ctxp); } inline int io_destroy(aio_context_t ctx) { return syscall(__NR_io_destroy, ctx); } inline int io_submit(aio_context_t ctx, long nr, struct iocb **iocbpp) { return syscall(__NR_io_submit, ctx, nr, iocbpp); } inline int io_getevents(aio_context_t ctx, long min_nr, long max_nr, struct io_event *events, struct timespec *timeout) { return syscall(__NR_io_getevents, ctx, min_nr, max_nr, events, timeout); } class KernelAIOWrite : public AsyncFileIOContext::AIOOperation { public: KernelAIOWrite(aio_context_t aio_ctx, int fd, size_t offset, size_t bytes, const void *buffer); virtual void launch(void); virtual bool check_completion(void); public: aio_context_t ctx; struct iocb cb; }; KernelAIOWrite::KernelAIOWrite(aio_context_t aio_ctx, int fd, size_t offset, size_t bytes, const void *buffer) { completed = false; ctx = aio_ctx; memset(&cb, 0, sizeof(cb)); cb.aio_data = (uint64_t)this; cb.aio_fildes = fd; cb.aio_lio_opcode = IOCB_CMD_PWRITE; cb.aio_buf = (uint64_t)buffer; cb.aio_offset = offset; cb.aio_nbytes = bytes; } void KernelAIOWrite::launch(void) { struct iocb *cbs[1]; cbs[0] = &cb; log_aio.debug("write issued: op=%p cb=%p", this, &cb); int ret = io_submit(ctx, 1, cbs); assert(ret == 1); } bool KernelAIOWrite::check_completion(void) { return completed; } class KernelAIORead : public AsyncFileIOContext::AIOOperation { public: KernelAIORead(aio_context_t aio_ctx, int fd, size_t offset, size_t bytes, void *buffer); virtual void launch(void); virtual bool check_completion(void); public: aio_context_t ctx; struct iocb cb; }; KernelAIORead::KernelAIORead(aio_context_t aio_ctx, int fd, size_t offset, size_t bytes, void *buffer) { completed = false; ctx = aio_ctx; memset(&cb, 0, sizeof(cb)); cb.aio_data = (uint64_t)this; cb.aio_fildes = fd; cb.aio_lio_opcode = IOCB_CMD_PREAD; cb.aio_buf = (uint64_t)buffer; cb.aio_offset = offset; cb.aio_nbytes = bytes; } void KernelAIORead::launch(void) { struct iocb *cbs[1]; cbs[0] = &cb; log_aio.debug("read issued: op=%p cb=%p", this, &cb); int ret = io_submit(ctx, 1, cbs); assert(ret == 1); } bool KernelAIORead::check_completion(void) { return completed; } #else class PosixAIOWrite : public AsyncFileIOContext::AIOOperation { public: PosixAIOWrite(int fd, size_t offset, size_t bytes, const void *buffer); virtual void launch(void); virtual bool check_completion(void); public: struct aiocb cb; }; PosixAIOWrite::PosixAIOWrite(int fd, size_t offset, size_t bytes, const void *buffer) { completed = false; memset(&cb, 0, sizeof(cb)); cb.aio_fildes = fd; cb.aio_buf = (void *)buffer; cb.aio_offset = offset; cb.aio_nbytes = bytes; } void PosixAIOWrite::launch(void) { log_aio.debug("write issued: op=%p cb=%p", this, &cb); #ifndef NDEBUG int ret = #endif aio_write(&cb); assert(ret == 0); } bool PosixAIOWrite::check_completion(void) { int ret = aio_error(&cb); if(ret == EINPROGRESS) return false; log_aio.debug("write returned: op=%p cb=%p ret=%d", this, &cb, ret); assert(ret == 0); return true; } class PosixAIORead : public AsyncFileIOContext::AIOOperation { public: PosixAIORead(int fd, size_t offset, size_t bytes, void *buffer); virtual void launch(void); virtual bool check_completion(void); public: struct aiocb cb; }; PosixAIORead::PosixAIORead(int fd, size_t offset, size_t bytes, void *buffer) { completed = false; memset(&cb, 0, sizeof(cb)); cb.aio_fildes = fd; cb.aio_buf = buffer; cb.aio_offset = offset; cb.aio_nbytes = bytes; } void PosixAIORead::launch(void) { log_aio.debug("read issued: op=%p cb=%p", this, &cb); #ifndef NDEBUG int ret = #endif aio_read(&cb); assert(ret == 0); } bool PosixAIORead::check_completion(void) { int ret = aio_error(&cb); if(ret == EINPROGRESS) return false; log_aio.debug("read returned: op=%p cb=%p ret=%d", this, &cb, ret); assert(ret == 0); return true; } #endif class AIOFence : public Realm::Operation::AsyncWorkItem { public: AIOFence(Realm::Operation *_op) : Realm::Operation::AsyncWorkItem(_op) {} virtual void request_cancellation(void) {} virtual void print(std::ostream& os) const { os << "AIOFence"; } }; class AIOFenceOp : public AsyncFileIOContext::AIOOperation { public: AIOFenceOp(DmaRequest *_req); virtual void launch(void); virtual bool check_completion(void); public: DmaRequest *req; AIOFence *f; }; AIOFenceOp::AIOFenceOp(DmaRequest *_req) { completed = false; req = _req; f = new AIOFence(req); req->add_async_work_item(f); } void AIOFenceOp::launch(void) { log_aio.debug("fence launched: op=%p req=%p", this, req); completed = true; } bool AIOFenceOp::check_completion(void) { assert(completed); log_aio.debug("fence completed: op=%p req=%p", this, req); f->mark_finished(true /*successful*/); return true; } AsyncFileIOContext::AsyncFileIOContext(int _max_depth) : max_depth(_max_depth) { #ifdef REALM_USE_KERNEL_AIO aio_ctx = 0; int ret = io_setup(max_depth, &aio_ctx); assert(ret == 0); #endif } AsyncFileIOContext::~AsyncFileIOContext(void) { assert(pending_operations.empty()); assert(launched_operations.empty()); #ifdef REALM_USE_KERNEL_AIO int ret = io_destroy(aio_ctx); assert(ret == 0); #endif } void AsyncFileIOContext::enqueue_write(int fd, size_t offset, size_t bytes, const void *buffer) { #ifdef REALM_USE_KERNEL_AIO KernelAIOWrite *op = new KernelAIOWrite(aio_ctx, fd, offset, bytes, buffer); #else PosixAIOWrite *op = new PosixAIOWrite(fd, offset, bytes, buffer); #endif { AutoHSLLock al(mutex); if(launched_operations.size() < (size_t)max_depth) { op->launch(); launched_operations.push_back(op); } else { pending_operations.push_back(op); } } } void AsyncFileIOContext::enqueue_read(int fd, size_t offset, size_t bytes, void *buffer) { #ifdef REALM_USE_KERNEL_AIO KernelAIORead *op = new KernelAIORead(aio_ctx, fd, offset, bytes, buffer); #else PosixAIORead *op = new PosixAIORead(fd, offset, bytes, buffer); #endif { AutoHSLLock al(mutex); if(launched_operations.size() < (size_t)max_depth) { op->launch(); launched_operations.push_back(op); } else { pending_operations.push_back(op); } } } void AsyncFileIOContext::enqueue_fence(DmaRequest *req) { AIOFenceOp *op = new AIOFenceOp(req); { AutoHSLLock al(mutex); if(launched_operations.size() < (size_t)max_depth) { op->launch(); launched_operations.push_back(op); } else { pending_operations.push_back(op); } } } bool AsyncFileIOContext::empty(void) { AutoHSLLock al(mutex); return launched_operations.empty(); } void AsyncFileIOContext::make_progress(void) { AutoHSLLock al(mutex); // first, reap as many events as we can - oldest first #ifdef REALM_USE_KERNEL_AIO while(true) { struct io_event events[8]; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 0; // no delay int ret = io_getevents(aio_ctx, 1, 8, events, &ts); if(ret == 0) break; log_aio.debug("io_getevents returned %d events", ret); for(int i = 0; i < ret; i++) { AIOOperation *op = (AIOOperation *)(events[i].data); log_aio.debug("io_getevents: event[%d] = %p", i, op); op->completed = true; } } #endif // now actually mark events completed in oldest-first order while(!launched_operations.empty()) { AIOOperation *op = launched_operations.front(); if(!op->check_completion()) break; log_aio.debug("aio op completed: op=%p", op); delete op; launched_operations.pop_front(); } // finally, if there are any pending ops, and room for them, launch them while((launched_operations.size() < (size_t)max_depth) && !pending_operations.empty()) { AIOOperation *op = pending_operations.front(); pending_operations.pop_front(); op->launch(); launched_operations.push_back(op); } } // MemPairCopier from disk memory to cpu memory class DisktoCPUMemPairCopier : public MemPairCopier { public: DisktoCPUMemPairCopier(int _fd, Memory _dst_mem) { MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); assert(dst_base); fd = _fd; } virtual ~DisktoCPUMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &osa_vec) { return new SpanBasedInstPairCopier<DisktoCPUMemPairCopier>(this, src_inst, dst_inst, osa_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { aio_context->enqueue_read(fd, src_offset, bytes, dst_base + dst_offset); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } void flush(DmaRequest *req) { aio_context->enqueue_fence(req); MemPairCopier::flush(req); } protected: char *dst_base; int fd; // file descriptor }; // MemPairCopier from disk memory to cpu memory class DiskfromCPUMemPairCopier : public MemPairCopier { public: DiskfromCPUMemPairCopier(Memory _src_mem, int _fd) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (char *)(src_impl->get_direct_ptr(0, src_impl->size)); assert(src_base); fd = _fd; } virtual ~DiskfromCPUMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &osa_vec) { return new SpanBasedInstPairCopier<DiskfromCPUMemPairCopier>(this, src_inst, dst_inst, osa_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { aio_context->enqueue_write(fd, dst_offset, bytes, src_base + src_offset); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } void flush(DmaRequest *req) { aio_context->enqueue_fence(req); MemPairCopier::flush(req); } protected: char *src_base; int fd; // file descriptor }; class FilefromCPUMemPairCopier : public MemPairCopier { public: class FileWriteCopier : public InstPairCopier { public: enum {max_nr = 1}; FileWriteCopier(int _fd, char* _base, RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec, FilefromCPUMemPairCopier *_mpc) { fd = _fd; inst_copier = new SpanBasedInstPairCopier<FileWriteCopier>(this, src_inst, dst_inst, oas_vec); src_base = _base; mpc = _mpc; } ~FileWriteCopier(void) { delete inst_copier; } virtual void copy_field(int src_index, int dst_index, int elem_count, unsigned offset_index) { inst_copier->copy_field(src_index, dst_index, elem_count, offset_index); } virtual void copy_all_fields(int src_index, int dst_index, int elem_count) { inst_copier->copy_all_fields(src_index, dst_index, elem_count); } virtual void copy_all_fields(int src_index, int dst_index, int count_per_line, int src_stride, int dst_stride, int lines) { inst_copier->copy_all_fields(src_index, dst_index, count_per_line, src_stride, dst_stride, lines); } virtual void flush(void) { inst_copier->flush(); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { aio_context->enqueue_write(fd, dst_offset, bytes, src_base + src_offset); mpc->record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: int fd; char *src_base; InstPairCopier* inst_copier; FilefromCPUMemPairCopier *mpc; }; FilefromCPUMemPairCopier(Memory _src_mem, Memory _dst_mem) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (char *)(src_impl->get_direct_ptr(0, src_impl->size)); dst_mem = (FileMemory*) get_runtime()->get_memory_impl(_dst_mem); } virtual ~FilefromCPUMemPairCopier(void) {} virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { ID id(dst_inst); unsigned index = id.index_l(); int fd = dst_mem->get_file_des(index); return new FileWriteCopier(fd, src_base, src_inst, dst_inst, oas_vec, this); } void flush(DmaRequest *req) { aio_context->enqueue_fence(req); MemPairCopier::flush(req); } protected: char *src_base; FileMemory *dst_mem; }; class FiletoCPUMemPairCopier : public MemPairCopier { public: class FileReadCopier : public InstPairCopier { public: enum {max_nr = 1}; FileReadCopier(int _fd, char* _base, RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec, FiletoCPUMemPairCopier *_mpc) { fd = _fd; inst_copier = new SpanBasedInstPairCopier<FileReadCopier>(this, src_inst, dst_inst, oas_vec); dst_base = _base; mpc = _mpc; } ~FileReadCopier(void) { delete inst_copier; } virtual void copy_field(int src_index, int dst_index, int elem_count, unsigned offset_index) { inst_copier->copy_field(src_index, dst_index, elem_count, offset_index); } virtual void copy_all_fields(int src_index, int dst_index, int elem_count) { inst_copier->copy_all_fields(src_index, dst_index, elem_count); } virtual void copy_all_fields(int src_index, int dst_index, int count_per_line, int src_stride, int dst_stride, int lines) { inst_copier->copy_all_fields(src_index, dst_index, count_per_line, src_stride, dst_stride, lines); } virtual void flush(void) { inst_copier->flush(); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { aio_context->enqueue_read(fd, src_offset, bytes, dst_base + dst_offset); mpc->record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: int fd; char *dst_base; InstPairCopier* inst_copier; FiletoCPUMemPairCopier *mpc; }; FiletoCPUMemPairCopier(Memory _src_mem, Memory _dst_mem) { MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); src_mem = (FileMemory*) get_runtime()->get_memory_impl(_src_mem); } virtual ~FiletoCPUMemPairCopier(void) {} virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { ID id(src_inst); unsigned index = id.index_l(); int fd = src_mem->get_file_des(index); return new FileReadCopier(fd, dst_base, src_inst, dst_inst, oas_vec, this); } void flush(DmaRequest *req) { aio_context->enqueue_fence(req); MemPairCopier::flush(req); } protected: char *dst_base; FileMemory *src_mem; }; // most of the smarts from MemPairCopier::create_copier are now captured in the various factories class MemcpyMemPairCopierFactory : public MemPairCopierFactory { public: MemcpyMemPairCopierFactory(void) : MemPairCopierFactory("memcpy") {} virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // non-reduction copies between anything SYSMEM and/or ZC // (TODO: really should be anything with a direct CPU pointer, but GPUFBMemory // returns non-null for that right now...) if(redop_id != 0) return false; MemoryImpl *src_impl = get_runtime()->get_memory_impl(src_mem); MemoryImpl::MemoryKind src_kind = src_impl->kind; if((src_kind != MemoryImpl::MKIND_SYSMEM) && (src_kind != MemoryImpl::MKIND_ZEROCOPY)) return false; MemoryImpl *dst_impl = get_runtime()->get_memory_impl(dst_mem); MemoryImpl::MemoryKind dst_kind = dst_impl->kind; if((dst_kind != MemoryImpl::MKIND_SYSMEM) && (dst_kind != MemoryImpl::MKIND_ZEROCOPY)) return false; return true; } virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { return new MemcpyMemPairCopier(src_mem, dst_mem); } }; void create_builtin_dma_channels(Realm::RuntimeImpl *r) { r->add_dma_channel(new MemcpyMemPairCopierFactory); } MemPairCopier *MemPairCopier::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id /*= 0*/, CustomSerdezID serdez_id /*= 0*/, bool fold /*= false*/) { // try to use new DMA channels first const std::vector<MemPairCopierFactory *>& channels = get_runtime()->get_dma_channels(); for(std::vector<MemPairCopierFactory *>::const_iterator it = channels.begin(); it != channels.end(); it++) { if((*it)->can_perform_copy(src_mem, dst_mem, redop_id, fold)) { // impls and kinds are just for logging now MemoryImpl *src_impl = get_runtime()->get_memory_impl(src_mem); MemoryImpl *dst_impl = get_runtime()->get_memory_impl(dst_mem); MemoryImpl::MemoryKind src_kind = src_impl->kind; MemoryImpl::MemoryKind dst_kind = dst_impl->kind; log_dma.info("copier: " IDFMT "(%d) -> " IDFMT "(%d) = %s", src_mem.id, src_kind, dst_mem.id, dst_kind, (*it)->get_name().c_str()); return (*it)->create_copier(src_mem, dst_mem, redop_id, fold); } } // old style - various options in here are being turned into assert(0)'s as they are // replaced by DMA channel-provided copiers MemoryImpl *src_impl = get_runtime()->get_memory_impl(src_mem); MemoryImpl *dst_impl = get_runtime()->get_memory_impl(dst_mem); MemoryImpl::MemoryKind src_kind = src_impl->kind; MemoryImpl::MemoryKind dst_kind = dst_impl->kind; log_dma.info("copier: " IDFMT "(%d) -> " IDFMT "(%d)", src_mem.id, src_kind, dst_mem.id, dst_kind); if(redop_id == 0) { if (serdez_id != 0) { // handle serdez cases, for now we only support remote serdez case if((dst_kind == MemoryImpl::MKIND_REMOTE) || (dst_kind == MemoryImpl::MKIND_RDMA)) { assert(src_kind != MemoryImpl::MKIND_REMOTE); return new RemoteSerdezMemPairCopier(src_mem, dst_mem, serdez_id); } log_dma.warning("Unsupported serdez transfer case (" IDFMT " -> " IDFMT ")", src_mem.id, dst_mem.id); assert(0); } // can we perform simple memcpy's? if(((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY)) && ((dst_kind == MemoryImpl::MKIND_SYSMEM) || (dst_kind == MemoryImpl::MKIND_ZEROCOPY))) { assert(0); //return new MemcpyMemPairCopier(src_mem, dst_mem); } // can we perform transfer between disk and cpu memory if (((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY)) && (dst_kind == MemoryImpl::MKIND_DISK)) { // printf("Create DiskfromCPUMemPairCopier\n"); int fd = ((DiskMemory *)dst_impl)->fd; return new DiskfromCPUMemPairCopier(src_mem, fd); } if ((src_kind == MemoryImpl::MKIND_DISK) && ((dst_kind == MemoryImpl::MKIND_SYSMEM) || (dst_kind == MemoryImpl::MKIND_ZEROCOPY))) { // printf("Create DisktoCPUMemPairCopier\n"); int fd = ((DiskMemory *)src_impl)->fd; return new DisktoCPUMemPairCopier(fd, dst_mem); } // can we perform transfer between cpu and file memory if (((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY)) && (dst_kind == MemoryImpl::MKIND_FILE)) { //printf("Create FilefromCPUMemPairCopier\n"); return new FilefromCPUMemPairCopier(src_mem, dst_mem); } if ((src_kind == MemoryImpl::MKIND_FILE) && ((dst_kind == MemoryImpl::MKIND_SYSMEM) || (dst_kind == MemoryImpl::MKIND_ZEROCOPY))) { //printf("Create FiletoCPUMemPairCopier\n"); return new FiletoCPUMemPairCopier(src_mem, dst_mem); } // GPU FB-related copies should be handled by module-provided dma channels now if((src_kind == MemoryImpl::MKIND_GPUFB) || (dst_kind == MemoryImpl::MKIND_GPUFB)) { assert(0); } // try as many things as we can think of if((dst_kind == MemoryImpl::MKIND_REMOTE) || (dst_kind == MemoryImpl::MKIND_RDMA)) { assert(src_kind != MemoryImpl::MKIND_REMOTE); return new RemoteWriteMemPairCopier(src_mem, dst_mem); } // fallback return new BufferedMemPairCopier(src_mem, dst_mem); } else { // reduction case // can we perform simple memcpy's? if(((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY)) && ((dst_kind == MemoryImpl::MKIND_SYSMEM) || (dst_kind == MemoryImpl::MKIND_ZEROCOPY))) { return new LocalReductionMemPairCopier(src_mem, dst_mem, redop_id, fold); } // reductions to a remote memory get shipped over there to be applied if((dst_kind == MemoryImpl::MKIND_REMOTE) || (dst_kind == MemoryImpl::MKIND_RDMA)) { assert(src_kind != MemoryImpl::MKIND_REMOTE); return new RemoteReduceMemPairCopier(src_mem, dst_mem, redop_id, fold); } // fallback is pretty damn slow log_dma.warning("using a buffering copier for reductions (" IDFMT " -> " IDFMT ")", src_mem.id, dst_mem.id); return new BufferedReductionMemPairCopier(src_mem, dst_mem, redop_id, fold); } } template <unsigned DIM> static unsigned compress_strides(const Rect<DIM> &r, const Point<1> in1[DIM], const Point<1> in2[DIM], Point<DIM>& extents, Point<1> out1[DIM], Point<1> out2[DIM]) { // sort the dimensions by the first set of strides for maximum gathering goodness unsigned stride_order[DIM]; for(unsigned i = 0; i < DIM; i++) stride_order[i] = i; // yay, bubble sort! for(unsigned i = 0; i < DIM; i++) for(unsigned j = 0; j < i; j++) if(in1[stride_order[j]] > in1[stride_order[j+1]]) { int t = stride_order[j]; stride_order[j] = stride_order[j+1]; stride_order[j+1] = t; } int curdim = -1; int exp1 = 0, exp2 = 0; // now go through dimensions, collapsing each if it matches the expected stride for // both sets (can't collapse for first) for(unsigned i = 0; i < DIM; i++) { unsigned d = stride_order[i]; unsigned e = r.dim_size(d); if(i && (exp1 == in1[d][0]) && (exp2 == in2[d][0])) { // collapse and grow extent extents.x[curdim] *= e; exp1 *= e; exp2 *= e; } else { // no match - create a new dimension curdim++; extents.x[curdim] = e; exp1 = in1[d][0] * e; exp2 = in2[d][0] * e; out1[curdim] = in1[d]; out2[curdim] = in2[d]; } } return curdim+1; } void CopyRequest::perform_dma_mask(MemPairCopier *mpc) { IndexSpaceImpl *ispace = get_runtime()->get_index_space_impl(domain.get_index_space()); assert(ispace->valid_mask_complete); // this is the SOA-friendly loop nesting for(OASByInst::iterator it = oas_by_inst->begin(); it != oas_by_inst->end(); it++) { RegionInstance src_inst = it->first.first; RegionInstance dst_inst = it->first.second; OASVec& oasvec = it->second; InstPairCopier *ipc = mpc->inst_pair(src_inst, dst_inst, oasvec); // index space instances use 1D linearizations for translation Arrays::Mapping<1, 1> *src_linearization = get_runtime()->get_instance_impl(src_inst)->metadata.linearization.get_mapping<1>(); Arrays::Mapping<1, 1> *dst_linearization = get_runtime()->get_instance_impl(dst_inst)->metadata.linearization.get_mapping<1>(); // does the destination instance space's index space match what we're copying? if so, // it's ok to copy extra elements (to decrease sparsity) because they're unused in // the destination assert(get_runtime()->get_instance_impl(dst_inst)->metadata.is_valid()); int rlen_target; if(ispace->me == get_runtime()->get_instance_impl(dst_inst)->metadata.is) { rlen_target = 32768 / 4; // aim for ~32KB transfers at least } else { rlen_target = 1; } ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, rlen; while(e->get_next(rstart, rlen)) { // do we want to copy extra elements to fill in some holes? while(rlen < rlen_target) { // see where the next valid elements are int rstart2, rlen2; // if none, stop if(!e->peek_next(rstart2, rlen2)) break; // or if they don't even start until outside the window, stop if(rstart2 > (rstart + rlen_target)) break; // ok, include the next valid element(s) and any invalid ones in between //printf("bloating from %d to %d\n", rlen, rstart2 + rlen2 - rstart); rlen = rstart2 + rlen2 - rstart; // and actually take the next range from the enumerator e->get_next(rstart2, rlen2); } int sstart = src_linearization->image(rstart); int dstart = dst_linearization->image(rstart); #ifdef DEBUG_LOW_LEVEL assert(src_linearization->image_is_dense(Rect<1>(rstart, rstart + rlen - 1))); assert(dst_linearization->image_is_dense(Rect<1>(rstart, rstart + rlen - 1))); #endif //printf("X: %d+%d %d %d\n", rstart, rlen, sstart, dstart); for (unsigned idx = 0; idx < oasvec.size(); idx++) ipc->copy_field(sstart, dstart, rlen, idx); } delete e; delete ipc; } } template <unsigned DIM> void CopyRequest::perform_dma_rect(MemPairCopier *mpc) { Arrays::Rect<DIM> orig_rect = domain.get_rect<DIM>(); // this is the SOA-friendly loop nesting for(OASByInst::iterator it = oas_by_inst->begin(); it != oas_by_inst->end(); it++) { RegionInstance src_inst = it->first.first; RegionInstance dst_inst = it->first.second; OASVec& oasvec = it->second; InstPairCopier *ipc = mpc->inst_pair(src_inst, dst_inst, oasvec); RegionInstanceImpl *src_impl = get_runtime()->get_instance_impl(src_inst); RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst_inst); assert(src_impl->metadata.is_valid()); assert(dst_impl->metadata.is_valid()); Arrays::Mapping<DIM, 1> *src_linearization = src_impl->metadata.linearization.get_mapping<DIM>(); Arrays::Mapping<DIM, 1> *dst_linearization = dst_impl->metadata.linearization.get_mapping<DIM>(); // see what linear subrects we can get - again, iterate over destination first for gathering for(typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lso(orig_rect, *dst_linearization); lso; lso++) { for(typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lsi(lso.subrect, *src_linearization); lsi; lsi++) { // see if we can compress the strides for a more efficient copy Point<1> src_cstrides[DIM], dst_cstrides[DIM]; Point<DIM> extents; int cdim = compress_strides(lsi.subrect, lso.strides, lsi.strides, extents, dst_cstrides, src_cstrides); #ifdef NEW2D_DEBUG printf("ORIG: (%d,%d,%d)->(%d,%d,%d)\n", orig_rect.lo[0], orig_rect.lo[1], orig_rect.lo[2], orig_rect.hi[0], orig_rect.hi[1], orig_rect.hi[2]); printf("DST: (%d,%d,%d)->(%d,%d,%d) %d+(%d,%d,%d)\n", lso.subrect.lo[0], lso.subrect.lo[1], lso.subrect.lo[2], lso.subrect.hi[0], lso.subrect.hi[1], lso.subrect.hi[2], lso.image_lo[0], lso.strides[0][0], lso.strides[1][0], lso.strides[2][0]); printf("SRC: (%d,%d,%d)->(%d,%d,%d) %d+(%d,%d,%d)\n", lsi.subrect.lo[0], lsi.subrect.lo[1], lsi.subrect.lo[2], lsi.subrect.hi[0], lsi.subrect.hi[1], lsi.subrect.hi[2], lsi.image_lo[0], lsi.strides[0][0], lsi.strides[1][0], lsi.strides[2][0]); printf("CMP: %d (%d,%d,%d) +(%d,%d,%d) +(%d,%d,%d)\n", cdim, extents[0], extents[1], extents[2], dst_cstrides[0][0], dst_cstrides[1][0], dst_cstrides[2][0], src_cstrides[0][0], src_cstrides[1][0], src_cstrides[2][0]); #endif if((cdim == 1) && (dst_cstrides[0][0] == 1) && (src_cstrides[0][0] == 1)) { // all the dimension(s) collapse to a 1-D extent in both source and dest, so one big copy ipc->copy_all_fields(lsi.image_lo[0], lso.image_lo[0], extents[0]); continue; } if((cdim == 2) && (dst_cstrides[0][0] == 1) && (src_cstrides[0][0] == 1)) { // source and/or destination need a 2-D description ipc->copy_all_fields(lsi.image_lo[0], lso.image_lo[0], extents[0], src_cstrides[1][0], dst_cstrides[1][0], extents[1]); continue; } // fall through - just identify dense (sub)subrects and copy them // iterate by output rectangle first - this gives us a chance to gather data when linearizations // don't match up for(Arrays::GenericDenseSubrectIterator<Arrays::Mapping<DIM, 1> > dso(lsi.subrect, *dst_linearization); dso; dso++) { // dense subrect in dst might not be dense in src for(Arrays::GenericDenseSubrectIterator<Arrays::Mapping<DIM, 1> > dsi(dso.subrect, *src_linearization); dsi; dsi++) { Rect<1> irect = dsi.image; // rectangle in output must be recalculated Rect<DIM> subrect_check; Rect<1> orect = dst_linearization->image_dense_subrect(dsi.subrect, subrect_check); assert(dsi.subrect == subrect_check); //for(OASVec::iterator it2 = oasvec.begin(); it2 != oasvec.end(); it2++) for (unsigned idx = 0; idx < oasvec.size(); idx++) ipc->copy_field(irect.lo, orect.lo, irect.hi[0] - irect.lo[0] + 1, idx); //it2->src_offset, it2->dst_offset, it2->size); } } } } // Dammit Sean stop leaking things! delete ipc; } } void CopyRequest::perform_dma(void) { log_dma.info("request %p executing", this); DetailedTimer::ScopedPush sp(TIME_COPY); // create a copier for the memory used by all of these instance pairs Memory src_mem = get_runtime()->get_instance_impl(oas_by_inst->begin()->first.first)->memory; Memory dst_mem = get_runtime()->get_instance_impl(oas_by_inst->begin()->first.second)->memory; CustomSerdezID serdez_id = oas_by_inst->begin()->second.begin()->serdez_id; // for now we launches an individual copy request for every serdez copy assert(serdez_id == 0 || (oas_by_inst->size() == 1 && oas_by_inst->begin()->second.size() == 1)); MemPairCopier *mpc = MemPairCopier::create_copier(src_mem, dst_mem, 0, serdez_id); log_dma.info("mpc created"); switch(domain.get_dim()) { case 0: { // iterate over valid ranges of an index space perform_dma_mask(mpc); break; } // rectangle cases case 1: perform_dma_rect<1>(mpc); break; case 2: perform_dma_rect<2>(mpc); break; case 3: perform_dma_rect<3>(mpc); break; default: assert(0); }; log_dma.info("dma request %p finished - " IDFMT "[%zd]->" IDFMT "[%zd]:%d (+%zd) (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, oas_by_inst->begin()->first.first.id, oas_by_inst->begin()->second[0].src_offset, oas_by_inst->begin()->first.second.id, oas_by_inst->begin()->second[0].dst_offset, oas_by_inst->begin()->second[0].size, oas_by_inst->begin()->second.size() - 1, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); mpc->flush(this); if(measurements.wants_measurement<Realm::ProfilingMeasurements::OperationMemoryUsage>()) { const InstPair &pair = oas_by_inst->begin()->first; Realm::ProfilingMeasurements::OperationMemoryUsage usage; usage.source = pair.first.get_location(); usage.target = pair.second.get_location(); usage.size = mpc->get_total_bytes(); measurements.add_measurement(usage); } // if(after_copy.exists()) // after_copy.impl()->trigger(after_copy.gen, gasnet_mynode()); delete mpc; #ifdef EVEN_MORE_DEAD_DMA_CODE RegionInstanceImpl *src_impl = src.impl(); RegionInstanceImpl *tgt_impl = target.impl(); // we should have already arranged to have access to this data, so // assert if we don't StaticAccess<RegionInstanceImpl> src_data(src_impl, true); StaticAccess<RegionInstanceImpl> tgt_data(tgt_impl, true); // code path for copies to/from reduction-only instances not done yet // are we doing a reduction? const ReductionOpUntyped *redop = ((src_data->redopid >= 0) ? get_runtime()->reduce_op_table[src_data->redopid] : 0); bool red_fold = (tgt_data->redopid >= 0); // if destination is a reduction, source must be also and must match assert(tgt_data->redopid == src_data->redopid); // for now, a reduction list instance can only be copied back to a // non-reduction instance bool red_list = (src_data->redopid >= 0) && (src_data->red_list_size >= 0); if(red_list) assert(tgt_data->redopid < 0); MemoryImpl *src_mem = src_impl->memory.impl(); MemoryImpl *tgt_mem = tgt_impl->memory.impl(); // get valid masks from region to limit copy to correct data IndexSpaceImpl *is_impl = is.impl(); //RegionMetaDataUntyped::Impl *src_reg = src_data->region.impl(); //RegionMetaDataUntyped::Impl *tgt_reg = tgt_data->region.impl(); log_dma.info("copy: " IDFMT "->" IDFMT " (" IDFMT "/%p)", src.id, target.id, is.id, is_impl->valid_mask); // if we're missing the valid mask at this point, we've screwed up if(!is_impl->valid_mask_complete) { assert(is_impl->valid_mask_complete); } log_dma.debug("performing copy " IDFMT " (%d) -> " IDFMT " (%d) - %zd bytes (%zd)", src.id, src_mem->kind, target.id, tgt_mem->kind, bytes_to_copy, elmt_size); switch(src_mem->kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { const void *src_ptr = src_mem->get_direct_ptr(src_data->alloc_offset, bytes_to_copy); assert(src_ptr != 0); switch(tgt_mem->kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { void *tgt_ptr = tgt_mem->get_direct_ptr(tgt_data->alloc_offset, bytes_to_copy); assert(tgt_ptr != 0); assert(!redop); RangeExecutors::Memcpy rexec(tgt_ptr, src_ptr, elmt_size); ElementMask::forall_ranges(rexec, *is_impl->valid_mask); } break; case MemoryImpl::MKIND_GLOBAL: { if(redop) { if(red_list) { RangeExecutors::GasnetPutRedList rexec(tgt_mem, tgt_data->alloc_offset, src_data->redopid, redop, src_ptr, redop->sizeof_list_entry); size_t count; src_mem->get_bytes(src_data->count_offset, &count, sizeof(size_t)); if(count > 0) { rexec.do_span(0, count); count = 0; src_mem->put_bytes(src_data->count_offset, &count, sizeof(size_t)); } } else { RangeExecutors::GasnetPutReduce rexec(tgt_mem, tgt_data->alloc_offset, redop, red_fold, src_ptr, elmt_size); ElementMask::forall_ranges(rexec, *is_impl->valid_mask); } } else { #define USE_BATCHED_GASNET_XFERS #ifdef USE_BATCHED_GASNET_XFERS RangeExecutors::GasnetPutBatched rexec(tgt_mem, tgt_data->alloc_offset, src_ptr, elmt_size); #else RangeExecutors::GasnetPut rexec(tgt_mem, tgt_data->alloc_offset, src_ptr, elmt_size); #endif ElementMask::forall_ranges(rexec, *is_impl->valid_mask); #ifdef USE_BATCHED_GASNET_XFERS rexec.finish(); #endif } } break; case MemoryImpl::MKIND_GPUFB: { // all GPU operations are deferred, so we need an event if // we don't already have one created assert(!redop); if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)tgt_mem)->gpu->copy_to_fb(tgt_data->alloc_offset, src_ptr, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; case MemoryImpl::MKIND_REMOTE: { // use active messages to push data to other node RangeExecutors::RemoteWrite rexec(tgt_impl->memory, tgt_data->alloc_offset, src_ptr, elmt_size, after_copy); ElementMask::forall_ranges(rexec, *is_impl->valid_mask); // if no copies actually occur, we'll get the event back // from the range executor and we have to trigger it ourselves Event finish_event = rexec.finish(); if(finish_event.exists()) { log_dma.info("triggering event " IDFMT "/%d after empty remote copy", finish_event.id, finish_event.gen); assert(finish_event == after_copy); get_runtime()->get_singleevent_impl(finish_event)->trigger(finish_event.gen, gasnet_mynode()); } return; } default: assert(0); } } break; case MemoryImpl::MKIND_GLOBAL: { switch(tgt_mem->kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { void *tgt_ptr = tgt_mem->get_direct_ptr(tgt_data->alloc_offset, bytes_to_copy); assert(tgt_ptr != 0); assert(!redop); #ifdef USE_BATCHED_GASNET_XFERS RangeExecutors::GasnetGetBatched rexec(tgt_ptr, src_mem, src_data->alloc_offset, elmt_size); #else RangeExecutors::GasnetGet rexec(tgt_ptr, src_mem, src_data->alloc_offset, elmt_size); #endif ElementMask::forall_ranges(rexec, *is_impl->valid_mask); #ifdef USE_BATCHED_GASNET_XFERS rexec.finish(); #endif } break; case MemoryImpl::MKIND_GLOBAL: { assert(!redop); RangeExecutors::GasnetGetAndPut rexec(tgt_mem, tgt_data->alloc_offset, src_mem, src_data->alloc_offset, elmt_size); ElementMask::forall_ranges(rexec, *is_impl->valid_mask); } break; case MemoryImpl::MKIND_GPUFB: { assert(!redop); // all GPU operations are deferred, so we need an event if // we don't already have one created if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)tgt_mem)->gpu->copy_to_fb_generic(tgt_data->alloc_offset, src_mem, src_data->alloc_offset, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; default: assert(0); } } break; case MemoryImpl::MKIND_GPUFB: { switch(tgt_mem->kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { void *tgt_ptr = tgt_mem->get_direct_ptr(tgt_data->alloc_offset, bytes_to_copy); assert(tgt_ptr != 0); assert(!redop); // all GPU operations are deferred, so we need an event if // we don't already have one created if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)src_mem)->gpu->copy_from_fb(tgt_ptr, src_data->alloc_offset, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; case MemoryImpl::MKIND_GLOBAL: { assert(!redop); // all GPU operations are deferred, so we need an event if // we don't already have one created if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)src_mem)->gpu->copy_from_fb_generic(tgt_mem, tgt_data->alloc_offset, src_data->alloc_offset, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; case MemoryImpl::MKIND_GPUFB: { // only support copies within the same FB for now assert(src_mem == tgt_mem); assert(!redop); // all GPU operations are deferred, so we need an event if // we don't already have one created if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)src_mem)->gpu->copy_within_fb(tgt_data->alloc_offset, src_data->alloc_offset, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; default: assert(0); } } break; default: assert(0); } log_dma.debug("finished copy " IDFMT " (%d) -> " IDFMT " (%d) - %zd bytes (%zd), event=" IDFMT "/%d", src.id, src_mem->kind, target.id, tgt_mem->kind, bytes_to_copy, elmt_size, after_copy.id, after_copy.gen); #endif } ReduceRequest::ReduceRequest(const void *data, size_t datalen, ReductionOpID _redop_id, bool _red_fold, Event _before_copy, Event _after_copy, int _priority) : DmaRequest(_priority, _after_copy), inst_lock_event(Event::NO_EVENT), redop_id(_redop_id), red_fold(_red_fold), before_copy(_before_copy) { const IDType *idata = (const IDType *)data; idata = domain.deserialize(idata); priority = 0; // get sources int n_srcs = *idata++; for(int i = 0; i < n_srcs; i++) { Domain::CopySrcDstField f; f.inst.id = *idata++; f.offset = *idata++; f.size = *idata++; srcs.push_back(f); } // single dst field dst.inst.id = *idata++; dst.offset = *idata++; dst.size = *idata++; inst_lock_needed = *idata++; // Unpack any requests that we have // TODO: unbreak once the serialization stuff is repaired //const void *result = requests.deserialize(idata); //Realm::Operation::reconstruct_measurements(); // better have consumed exactly the right amount of data //assert((((unsigned long long)result) - ((unsigned long long)data)) == datalen); size_t request_size = *reinterpret_cast<const size_t*>(idata); idata += sizeof(size_t) / sizeof(IDType); FixedBufferDeserializer deserializer(idata, request_size); deserializer >> requests; Realm::Operation::reconstruct_measurements(); log_dma.info("dma request %p deserialized - " IDFMT "[%d]->" IDFMT "[%d]:%d (+%zd) %s %d (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, srcs[0].inst.id, srcs[0].offset, dst.inst.id, dst.offset, dst.size, srcs.size() - 1, (red_fold ? "fold" : "apply"), redop_id, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); } ReduceRequest::ReduceRequest(const Domain& _domain, const std::vector<Domain::CopySrcDstField>& _srcs, const Domain::CopySrcDstField& _dst, bool _inst_lock_needed, ReductionOpID _redop_id, bool _red_fold, Event _before_copy, Event _after_copy, int _priority, const Realm::ProfilingRequestSet &reqs) : DmaRequest(_priority, _after_copy, reqs), domain(_domain), dst(_dst), inst_lock_needed(_inst_lock_needed), inst_lock_event(Event::NO_EVENT), redop_id(_redop_id), red_fold(_red_fold), before_copy(_before_copy) { srcs.insert(srcs.end(), _srcs.begin(), _srcs.end()); log_dma.info("dma request %p created - " IDFMT "[%d]->" IDFMT "[%d]:%d (+%zd) %s %d (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, srcs[0].inst.id, srcs[0].offset, dst.inst.id, dst.offset, dst.size, srcs.size() - 1, (red_fold ? "fold" : "apply"), redop_id, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); } ReduceRequest::~ReduceRequest(void) { } size_t ReduceRequest::compute_size(void) { size_t result = domain.compute_size(); result += (4 + 3 * srcs.size()) * sizeof(IDType); result += sizeof(IDType); // for inst_lock_needed // TODO: unbreak once the serialization stuff is repaired //result += requests.compute_size(); ByteCountSerializer counter; counter << requests; result += sizeof(size_t) + counter.bytes_used(); return result; } void ReduceRequest::serialize(void *buffer) { // domain info goes first IDType *msgptr = domain.serialize((IDType *)buffer); // now source fields *msgptr++ = srcs.size(); for(std::vector<Domain::CopySrcDstField>::const_iterator it = srcs.begin(); it != srcs.end(); it++) { *msgptr++ = it->inst.id; *msgptr++ = it->offset; *msgptr++ = it->size; } // and the dest field *msgptr++ = dst.inst.id; *msgptr++ = dst.offset; *msgptr++ = dst.size; *msgptr++ = inst_lock_needed; // TODO: unbreak once the serialization stuff is repaired //requests.serialize(msgptr); // We sent this request remotely so we need to clear it's profiling ByteCountSerializer counter; counter << requests; *reinterpret_cast<size_t*>(msgptr) = counter.bytes_used(); msgptr += sizeof(size_t) / sizeof(IDType); FixedBufferSerializer serializer(msgptr, counter.bytes_used()); serializer << requests; clear_profiling(); } bool ReduceRequest::check_readiness(bool just_check, DmaRequestQueue *rq) { if(state == STATE_INIT) state = STATE_METADATA_FETCH; // remember which queue we're going to be assigned to if we sleep waiter.req = this; waiter.queue = rq; // make sure our node has all the meta data it needs, but don't take more than one lock // at a time if(state == STATE_METADATA_FETCH) { // index space first if(domain.get_dim() == 0) { IndexSpaceImpl *is_impl = get_runtime()->get_index_space_impl(domain.get_index_space()); if(!is_impl->locked_data.valid) { log_dma.info("dma request %p - no index space metadata yet", this); if(just_check) return false; Event e = is_impl->lock.acquire(1, false); if(e.has_triggered()) { log_dma.info("request %p - index space metadata invalid - instant trigger", this); is_impl->lock.release(); } else { log_dma.info("request %p - index space metadata invalid - sleeping on lock " IDFMT "", this, is_impl->lock.me.id); waiter.sleep_on_event(e, is_impl->lock.me); return false; } } // we need more than just the metadata - we also need the valid mask { Event e = is_impl->request_valid_mask(); if(!e.has_triggered()) { log_dma.info("request %p - valid mask needed for index space " IDFMT " - sleeping on event " IDFMT "/%d", this, domain.get_index_space().id, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // now go through all source instance pairs for(std::vector<Domain::CopySrcDstField>::iterator it = srcs.begin(); it != srcs.end(); it++) { RegionInstanceImpl *src_impl = get_runtime()->get_instance_impl(it->inst); { Event e = src_impl->request_metadata(); if(!e.has_triggered()) { if(just_check) { log_dma.info("dma request %p - no src instance (" IDFMT ") metadata yet", this, src_impl->me.id); return false; } log_dma.info("request %p - src instance metadata invalid - sleeping on event " IDFMT "/%d", this, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } { RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst.inst); { Event e = dst_impl->request_metadata(); if(!e.has_triggered()) { if(just_check) { log_dma.info("dma request %p - no dst instance (" IDFMT ") metadata yet", this, dst_impl->me.id); return false; } log_dma.info("request %p - dst instance metadata invalid - sleeping on event " IDFMT "/%d", this, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // if we got all the way through, we've got all the metadata we need state = STATE_BEFORE_EVENT; } // make sure our functional precondition has occurred if(state == STATE_BEFORE_EVENT) { // has the before event triggered? if not, wait on it if(before_copy.has_triggered()) { log_dma.info("request %p - before event triggered", this); if(inst_lock_needed) { // request an exclusive lock on the instance to protect reductions inst_lock_event = get_runtime()->get_instance_impl(dst.inst)->lock.acquire(0, true /*excl*/); state = STATE_INST_LOCK; log_dma.info("request %p - instance lock acquire event " IDFMT "/%d", this, inst_lock_event.id, inst_lock_event.gen); } else { // go straight to ready state = STATE_READY; } } else { log_dma.info("request %p - before event not triggered", this); if(just_check) return false; log_dma.info("request %p - sleeping on before event", this); waiter.sleep_on_event(before_copy); return false; } } if(state == STATE_INST_LOCK) { if(inst_lock_event.has_triggered()) { log_dma.info("request %p - instance lock acquired", this); state = STATE_READY; } else { log_dma.info("request %p - instance lock - sleeping on event " IDFMT "/%d", this, inst_lock_event.id, inst_lock_event.gen); waiter.sleep_on_event(inst_lock_event); return false; } } if(state == STATE_READY) { log_dma.info("request %p ready", this); if(just_check) return true; state = STATE_QUEUED; assert(rq != 0); log_dma.info("request %p enqueued", this); // once we're enqueued, we may be deleted at any time, so no more // references rq->enqueue_request(this); return true; } if(state == STATE_QUEUED) return true; assert(0); } template <unsigned DIM> void ReduceRequest::perform_dma_rect(MemPairCopier *mpc) { Arrays::Rect<DIM> orig_rect = domain.get_rect<DIM>(); const ReductionOpUntyped *redop = get_runtime()->reduce_op_table[redop_id]; // single source field for now assert(srcs.size() == 1); // manufacture an OASVec for the copier OASVec oasvec(1); oasvec[0].src_offset = srcs[0].offset; oasvec[0].dst_offset = dst.offset; oasvec[0].size = redop->sizeof_rhs; RegionInstance src_inst = srcs[0].inst; RegionInstance dst_inst = dst.inst; InstPairCopier *ipc = mpc->inst_pair(src_inst, dst_inst, oasvec); RegionInstanceImpl *src_impl = get_runtime()->get_instance_impl(src_inst); RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst_inst); assert(src_impl->metadata.is_valid()); assert(dst_impl->metadata.is_valid()); Arrays::Mapping<DIM, 1> *src_linearization = src_impl->metadata.linearization.get_mapping<DIM>(); Arrays::Mapping<DIM, 1> *dst_linearization = dst_impl->metadata.linearization.get_mapping<DIM>(); // see what linear subrects we can get - again, iterate over destination first for gathering for(typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lso(orig_rect, *dst_linearization); lso; lso++) { for(typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lsi(lso.subrect, *src_linearization); lsi; lsi++) { // see if we can compress the strides for a more efficient copy Point<1> src_cstrides[DIM], dst_cstrides[DIM]; Point<DIM> extents; int cdim = compress_strides(lsi.subrect, lso.strides, lsi.strides, extents, dst_cstrides, src_cstrides); #ifdef NEW2D_DEBUG printf("ORIG: (%d,%d,%d)->(%d,%d,%d)\n", orig_rect.lo[0], orig_rect.lo[1], orig_rect.lo[2], orig_rect.hi[0], orig_rect.hi[1], orig_rect.hi[2]); printf("DST: (%d,%d,%d)->(%d,%d,%d) %d+(%d,%d,%d)\n", lso.subrect.lo[0], lso.subrect.lo[1], lso.subrect.lo[2], lso.subrect.hi[0], lso.subrect.hi[1], lso.subrect.hi[2], lso.image_lo[0], lso.strides[0][0], lso.strides[1][0], lso.strides[2][0]); printf("SRC: (%d,%d,%d)->(%d,%d,%d) %d+(%d,%d,%d)\n", lsi.subrect.lo[0], lsi.subrect.lo[1], lsi.subrect.lo[2], lsi.subrect.hi[0], lsi.subrect.hi[1], lsi.subrect.hi[2], lsi.image_lo[0], lsi.strides[0][0], lsi.strides[1][0], lsi.strides[2][0]); printf("CMP: %d (%d,%d,%d) +(%d,%d,%d) +(%d,%d,%d)\n", cdim, extents[0], extents[1], extents[2], dst_cstrides[0][0], dst_cstrides[1][0], dst_cstrides[2][0], src_cstrides[0][0], src_cstrides[1][0], src_cstrides[2][0]); #endif if((cdim == 1) && (dst_cstrides[0][0] == 1) && (src_cstrides[0][0] == 1)) { // all the dimension(s) collapse to a 1-D extent in both source and dest, so one big copy ipc->copy_all_fields(lsi.image_lo[0], lso.image_lo[0], extents[0]); continue; } if((cdim == 2) && (dst_cstrides[0][0] == 1) && (src_cstrides[0][0] == 1)) { // source and/or destination need a 2-D description ipc->copy_all_fields(lsi.image_lo[0], lso.image_lo[0], extents[0], src_cstrides[1][0], dst_cstrides[1][0], extents[1]); continue; } // fall through - just identify dense (sub)subrects and copy them // iterate by output rectangle first - this gives us a chance to gather data when linearizations // don't match up for(Arrays::GenericDenseSubrectIterator<Arrays::Mapping<DIM, 1> > dso(lsi.subrect, *dst_linearization); dso; dso++) { // dense subrect in dst might not be dense in src for(Arrays::GenericDenseSubrectIterator<Arrays::Mapping<DIM, 1> > dsi(dso.subrect, *src_linearization); dsi; dsi++) { Rect<1> irect = dsi.image; // rectangle in output must be recalculated Rect<DIM> subrect_check; Rect<1> orect = dst_linearization->image_dense_subrect(dsi.subrect, subrect_check); assert(dsi.subrect == subrect_check); //for(OASVec::iterator it2 = oasvec.begin(); it2 != oasvec.end(); it2++) for (unsigned idx = 0; idx < oasvec.size(); idx++) ipc->copy_field(irect.lo, orect.lo, irect.hi[0] - irect.lo[0] + 1, idx); //it2->src_offset, it2->dst_offset, it2->size); } } } } delete ipc; } void ReduceRequest::perform_dma(void) { log_dma.info("request %p executing", this); DetailedTimer::ScopedPush sp(TIME_COPY); // code assumes a single source field for now assert(srcs.size() == 1); Memory src_mem = get_runtime()->get_instance_impl(srcs[0].inst)->memory; Memory dst_mem = get_runtime()->get_instance_impl(dst.inst)->memory; MemoryImpl::MemoryKind src_kind = get_runtime()->get_memory_impl(src_mem)->kind; MemoryImpl::MemoryKind dst_kind = get_runtime()->get_memory_impl(dst_mem)->kind; const ReductionOpUntyped *redop = get_runtime()->reduce_op_table[redop_id]; //printf("kinds: " IDFMT "=%d " IDFMT "=%d\n", src_mem.id, src_mem.impl()->kind, dst_mem.id, dst_mem.impl()->kind); // we have the same jumble of memory type and layout permutations here - again we'll // solve a few of them point-wise and then try to unify later size_t total_bytes = 0; if(domain.get_dim() == 0) { // index space IndexSpaceImpl *ispace = get_runtime()->get_index_space_impl(domain.get_index_space()); assert(ispace->valid_mask_complete); if((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY) || (src_kind == MemoryImpl::MKIND_RDMA)) { void *src_base = 0; size_t src_stride = 0; #ifndef NDEBUG bool src_ok = #endif get_runtime()->get_instance_impl(srcs[0].inst)->get_strided_parameters(src_base, src_stride, srcs[0].offset); assert(src_ok); switch(dst_kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { void *dst_base = 0; size_t dst_stride = 0; #ifndef NDEBUG bool dst_ok = #endif get_runtime()->get_instance_impl(dst.inst)->get_strided_parameters(dst_base, dst_stride, dst.offset); assert(dst_ok); // if source and dest are ok, we can just walk the index space's spans ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, rlen; while(e->get_next(rstart, rlen)) { if(red_fold) redop->fold_strided(((char *)dst_base) + (rstart * dst_stride), ((const char *)src_base) + (rstart * src_stride), dst_stride, src_stride, rlen, false /*not exclusive*/); else redop->apply_strided(((char *)dst_base) + (rstart * dst_stride), ((const char *)src_base) + (rstart * src_stride), dst_stride, src_stride, rlen, false /*not exclusive*/); } delete e; break; } case MemoryImpl::MKIND_REMOTE: case MemoryImpl::MKIND_RDMA: { // we need to figure out how to calculate offsets in the destination memory RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst.inst); assert(dst_impl->metadata.is_valid()); off_t dst_field_start=0; int dst_field_size=0; find_field_start(dst_impl->metadata.field_sizes, dst.offset, dst.size, dst_field_start, dst_field_size); assert(dst.size == (size_t)dst_field_size); // index space instances use 1D linearizations for translation Arrays::Mapping<1, 1> *dst_linearization = dst_impl->metadata.linearization.get_mapping<1>(); ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, rlen; // get an RDMA sequence number so we can have the far side trigger the event once all reductions have been // applied unsigned sequence_id = __sync_fetch_and_add(&rdma_sequence_no, 1); unsigned rdma_count = 0; // for a reduction from a fold instance, it's always ok to copy unused elements, since they'll have an // identity value stored for them int rlen_target = 32768 / dst_field_size; while(e->get_next(rstart, rlen)) { // do we want to copy extra elements to fill in some holes? while(rlen < rlen_target) { // see where the next valid elements are int rstart2, rlen2; // if none, stop if(!e->peek_next(rstart2, rlen2)) break; // or if they don't even start until outside the window, stop if(rstart2 > (rstart + rlen_target)) break; // ok, include the next valid element(s) and any invalid ones in between //printf("bloating from %d to %d\n", rlen, rstart2 + rlen2 - rstart); rlen = rstart2 + rlen2 - rstart; // and actually take the next range from the enumerator e->get_next(rstart2, rlen2); } // translate the index space point to the dst instance's linearization int dstart = dst_linearization->image(rstart); // now do an offset calculation for the destination off_t dst_offset; off_t dst_stride; if(dst_impl->metadata.block_size > 1) { // straddling a block boundary is complicated assert((dstart / dst_impl->metadata.block_size) == ((dstart + rlen - 1) / dst_impl->metadata.block_size)); dst_offset = calc_mem_loc(dst_impl->metadata.alloc_offset, dst_field_start, dst_field_size, dst_impl->metadata.elmt_size, dst_impl->metadata.block_size, dstart); dst_stride = dst_field_size; } else { // easy case dst_offset = dst_impl->metadata.alloc_offset + (dstart * dst_impl->metadata.elmt_size) + dst_field_start; dst_stride = dst_impl->metadata.elmt_size; } rdma_count += do_remote_reduce(dst_mem, dst_offset, redop_id, red_fold, ((const char *)src_base) + (rstart * src_stride), rlen, src_stride, dst_stride, sequence_id); } // if we did any actual reductions, send a fence, otherwise trigger here if(rdma_count > 0) { Realm::RemoteWriteFence *fence = new Realm::RemoteWriteFence(this); this->add_async_work_item(fence); do_remote_fence(dst_mem, sequence_id, rdma_count, fence); } delete e; break; } case MemoryImpl::MKIND_GLOBAL: { // make sure we've requested a lock on the dst instance assert(inst_lock_needed); // we need to figure out how to calculate offsets in the destination memory RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst.inst); assert(dst_impl->metadata.is_valid()); off_t dst_field_start=0; int dst_field_size=0; find_field_start(dst_impl->metadata.field_sizes, dst.offset, dst.size, dst_field_start, dst_field_size); assert(dst.size == (size_t)dst_field_size); // index space instances use 1D linearizations for translation Arrays::Mapping<1, 1> *dst_linearization = dst_impl->metadata.linearization.get_mapping<1>(); // if source and dest are ok, we can just walk the index space's spans ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, rlen; while(e->get_next(rstart, rlen)) { // translate the index space point to the dst instance's linearization int dstart = dst_linearization->image(rstart); // now do an offset calculation for the destination off_t dst_offset; off_t dst_stride; if(dst_impl->metadata.block_size > 1) { // straddling a block boundary is complicated assert((dstart / dst_impl->metadata.block_size) == ((dstart + rlen - 1) / dst_impl->metadata.block_size)); dst_offset = calc_mem_loc(dst_impl->metadata.alloc_offset, dst_field_start, dst_field_size, dst_impl->metadata.elmt_size, dst_impl->metadata.block_size, dstart); dst_stride = dst_field_size; } else { // easy case dst_offset = dst_impl->metadata.alloc_offset + (dstart * dst_impl->metadata.elmt_size) + dst_field_start; dst_stride = dst_impl->metadata.elmt_size; } // get a temporary buffer in local memory // this may have extra data if stride > field_size, but that's // ok - we'll write back whatever we read void *buffer = malloc(dst_stride * rlen); get_runtime()->get_memory_impl(dst_mem)->get_bytes(dst_offset, buffer, dst_stride * rlen); if(red_fold) redop->fold_strided(buffer, ((const char *)src_base) + (rstart * src_stride), dst_stride, src_stride, rlen, true /*exclusive*/); else redop->apply_strided(buffer, ((const char *)src_base) + (rstart * src_stride), dst_stride, src_stride, rlen, true /*exclusive*/); get_runtime()->get_memory_impl(dst_mem)->put_bytes(dst_offset, buffer, dst_stride * rlen); // release the temp buffer free(buffer); } // also release the instance lock dst_impl->lock.release(); delete e; break; } default: assert(0); } } // TODO: we don't track the size of reduction on unstructred index spaces total_bytes = 0; } else { MemPairCopier *mpc = MemPairCopier::create_copier(src_mem, dst_mem, redop_id, red_fold); switch(domain.get_dim()) { case 1: perform_dma_rect<1>(mpc); break; case 2: perform_dma_rect<2>(mpc); break; case 3: perform_dma_rect<3>(mpc); break; default: assert(0); } mpc->flush(this); total_bytes = mpc->get_total_bytes(); // if an instance lock was taken, release it after copy completes if(inst_lock_needed) get_runtime()->get_instance_impl(dst.inst)->lock.me.release(get_finish_event()); delete mpc; } log_dma.info("dma request %p finished - " IDFMT "[%d]->" IDFMT "[%d]:%d (+%zd) %s %d (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, srcs[0].inst.id, srcs[0].offset, dst.inst.id, dst.offset, dst.size, srcs.size() - 1, (red_fold ? "fold" : "apply"), redop_id, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); if(measurements.wants_measurement<Realm::ProfilingMeasurements::OperationMemoryUsage>()) { Realm::ProfilingMeasurements::OperationMemoryUsage usage; // Not precise, but close enough for now usage.source = srcs[0].inst.get_location(); usage.target = dst.inst.get_location(); usage.size = total_bytes; measurements.add_measurement(usage); } } FillRequest::FillRequest(const void *data, size_t datalen, RegionInstance inst, unsigned offset, unsigned size, Event _before_fill, Event _after_fill, int _priority) : DmaRequest(_priority, _after_fill), before_fill(_before_fill) { dst.inst = inst; dst.offset = offset; dst.size = size; const IDType *idata = (const IDType *)data; idata = domain.deserialize(idata); size_t elmts = *idata++; fill_size = dst.size; fill_buffer = malloc(fill_size); memcpy(fill_buffer, idata, fill_size); idata += elmts; // TODO: unbreak once the serialization stuff is repaired //const void *result = requests.deserialize(idata); //Realm::Operation::reconstruct_measurements(); // better have consumed exactly the right amount of data //assert((((unsigned long)result) - ((unsigned long)data)) == datalen); } FillRequest::FillRequest(const Domain &d, const Domain::CopySrcDstField &_dst, const void *_fill_value, size_t _fill_size, Event _before_fill, Event _after_fill, int _priority, const Realm::ProfilingRequestSet &reqs) : DmaRequest(_priority, _after_fill, reqs), domain(d), dst(_dst), before_fill(_before_fill) { fill_size = _fill_size; fill_buffer = malloc(fill_size); memcpy(fill_buffer, _fill_value, fill_size); } FillRequest::~FillRequest(void) { // clean up our mess free(fill_buffer); } size_t FillRequest::compute_size(void) { size_t result = domain.compute_size(); size_t elmts = (fill_size + sizeof(IDType) - 1)/sizeof(IDType); result += ((elmts+1) * sizeof(IDType)); // +1 for fill size in bytes // TODO: unbreak once the serialization stuff is repaired //result += requests.compute_size(); return result; } void FillRequest::serialize(void *buffer) { IDType *msgptr = domain.serialize((IDType *)buffer); assert(dst.size == fill_size); size_t elmts = (fill_size + sizeof(IDType) - 1)/sizeof(IDType); *msgptr++ = elmts; memcpy(msgptr, fill_buffer, fill_size); msgptr += elmts; // TODO: unbreak once the serialization stuff is repaired //requests.serialize(msgptr); // We sent this message remotely, so we need to clear the profiling // so it doesn't get sent accidentally clear_profiling(); } bool FillRequest::check_readiness(bool just_check, DmaRequestQueue *rq) { if(state == STATE_INIT) state = STATE_METADATA_FETCH; // remember which queue we're going to be assigned to if we sleep waiter.req = this; waiter.queue = rq; // make sure our node has all the meta data it needs, but don't take more than one lock // at a time if(state == STATE_METADATA_FETCH) { // index space first if(domain.get_dim() == 0) { IndexSpaceImpl *is_impl = get_runtime()->get_index_space_impl(domain.get_index_space()); if(!is_impl->locked_data.valid) { log_dma.info("dma request %p - no index space metadata yet", this); if(just_check) return false; Event e = is_impl->lock.acquire(1, false); if(e.has_triggered()) { log_dma.info("request %p - index space metadata invalid - instant trigger", this); is_impl->lock.release(); } else { log_dma.info("request %p - index space metadata invalid - sleeping on lock " IDFMT "", this, is_impl->lock.me.id); waiter.sleep_on_event(e, is_impl->lock.me); return false; } } // we need more than just the metadata - we also need the valid mask { Event e = is_impl->request_valid_mask(); if(!e.has_triggered()) { log_dma.info("request %p - valid mask needed for index space " IDFMT " - sleeping on event " IDFMT "/%d", this, domain.get_index_space().id, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // No need to check the instance, we are on its local node state = STATE_BEFORE_EVENT; } // make sure our functional precondition has occurred if(state == STATE_BEFORE_EVENT) { // has the before event triggered? if not, wait on it if(before_fill.has_triggered()) { log_dma.info("request %p - before event triggered", this); state = STATE_READY; } else { log_dma.info("request %p - before event not triggered", this); if(just_check) return false; log_dma.info("request %p - sleeping on before event", this); waiter.sleep_on_event(before_fill); return false; } } if(state == STATE_READY) { log_dma.info("request %p ready", this); if(just_check) return true; state = STATE_QUEUED; assert(rq != 0); log_dma.info("request %p enqueued", this); // once we're enqueued, we may be deleted at any time, so no more // references rq->enqueue_request(this); return true; } if(state == STATE_QUEUED) return true; assert(0); return false; } void FillRequest::perform_dma(void) { // First switch on the memory type MemoryImpl *mem_impl = get_runtime()->get_memory_impl(dst.inst.get_location()); MemoryImpl::MemoryKind mem_kind = mem_impl->kind; // TODO: optimize transfers for framebuffer to use a memset kernel if ((mem_kind == MemoryImpl::MKIND_SYSMEM) || (mem_kind == MemoryImpl::MKIND_ZEROCOPY) || (mem_kind == MemoryImpl::MKIND_RDMA) || (mem_kind == MemoryImpl::MKIND_GPUFB) || (mem_kind == MemoryImpl::MKIND_ZEROCOPY)) { switch (domain.get_dim()) { case 0: { // Iterate over all the points and get the IndexSpaceImpl *ispace = get_runtime()->get_index_space_impl(domain.get_index_space()); assert(ispace->valid_mask_complete); RegionInstanceImpl *inst_impl = get_runtime()->get_instance_impl(dst.inst); off_t field_start=0; int field_size=0; find_field_start(inst_impl->metadata.field_sizes, dst.offset, dst.size, field_start, field_size); assert(field_size <= int(fill_size)); int fill_elmts = 1; // Optimize our buffer for the target instance size_t fill_elmts_size = optimize_fill_buffer(inst_impl, fill_elmts); Arrays::Mapping<1, 1> *dst_linearization = inst_impl->metadata.linearization.get_mapping<1>(); ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, elem_count; while(e->get_next(rstart, elem_count)) { int dst_index = dst_linearization->image(rstart); int done = 0; while (done < elem_count) { int dst_in_this_block = inst_impl->metadata.block_size - ((dst_index + done) % inst_impl->metadata.block_size); int todo = min(elem_count, dst_in_this_block); off_t dst_start = calc_mem_loc(inst_impl->metadata.alloc_offset, field_start, field_size, inst_impl->metadata.elmt_size, inst_impl->metadata.block_size, dst_index + done); // Record how many we've done done += todo; // Now do as many bulk transfers as we can while (todo >= fill_elmts) { mem_impl->put_bytes(dst_start, fill_buffer, fill_elmts_size); dst_start += fill_elmts_size; todo -= fill_elmts; } // Handle any remainder elemts if (todo > 0) { mem_impl->put_bytes(dst_start, fill_buffer, todo*fill_size); } } } delete e; break; } case 1: { perform_dma_rect<1>(mem_impl); break; } case 2: { perform_dma_rect<2>(mem_impl); break; } case 3: { perform_dma_rect<3>(mem_impl); break; } default: assert(false); } } else { // TODO: Implement GASNet and Disk assert(false); } if(measurements.wants_measurement<Realm::ProfilingMeasurements::OperationMemoryUsage>()) { Realm::ProfilingMeasurements::OperationMemoryUsage usage; usage.source = Memory::NO_MEMORY; usage.target = dst.inst.get_location(); measurements.add_measurement(usage); } } template<int DIM> void FillRequest::perform_dma_rect(MemoryImpl *mem_impl) { RegionInstanceImpl *inst_impl = get_runtime()->get_instance_impl(dst.inst); off_t field_start=0; int field_size=0; find_field_start(inst_impl->metadata.field_sizes, dst.offset, dst.size, field_start, field_size); assert(field_size <= (int)fill_size); typename Arrays::Mapping<DIM, 1> *dst_linearization = inst_impl->metadata.linearization.get_mapping<DIM>(); typename Arrays::Rect<DIM> rect = domain.get_rect<DIM>(); int fill_elmts = 1; // Optimize our buffer for the target instance size_t fill_elmts_size = optimize_fill_buffer(inst_impl, fill_elmts); for (typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lso(rect, *dst_linearization); lso; lso++) { int dst_index = lso.image_lo[0]; int elem_count = lso.subrect.volume(); int done = 0; while (done < elem_count) { int dst_in_this_block = inst_impl->metadata.block_size - ((dst_index + done) % inst_impl->metadata.block_size); int todo = min(elem_count, dst_in_this_block); off_t dst_start = calc_mem_loc(inst_impl->metadata.alloc_offset, field_start, field_size, inst_impl->metadata.elmt_size, inst_impl->metadata.block_size, dst_index + done); // Record how many we've done done += todo; // Now do as many bulk transfers as we can while (todo >= fill_elmts) { mem_impl->put_bytes(dst_start, fill_buffer, fill_elmts_size); dst_start += fill_elmts_size; todo -= fill_elmts; } // Handle any remainder elemts if (todo > 0) { mem_impl->put_bytes(dst_start, fill_buffer, todo*fill_size); } } } } size_t FillRequest::optimize_fill_buffer(RegionInstanceImpl *inst_impl, int &fill_elmts) { const size_t max_size = 1024; // Only do this optimization for "small" fields // which are less than half a page if (fill_size <= max_size) { // If we have a single-field instance or we have a set // of contiguous elmts then make a bulk buffer to use if ((inst_impl->metadata.elmt_size == fill_size) || (inst_impl->metadata.block_size > 1)) { fill_elmts = min(inst_impl->metadata.block_size,2*max_size/fill_size); size_t fill_elmts_size = fill_elmts * fill_size; char *next_buffer = (char*)malloc(fill_elmts_size); char *next_ptr = next_buffer; for (int idx = 0; idx < fill_elmts; idx++) { memcpy(next_ptr, fill_buffer, fill_size); next_ptr += fill_size; } // Free the old buffer and replace it free(fill_buffer); fill_buffer = next_buffer; return fill_elmts_size; } } return fill_size; } #if 0 class CopyCompletionProfiler : public EventWaiter, public Realm::Operation::AsyncWorkItem { public: CopyCompletionProfiler(DmaRequest* _req) : Realm::Operation::AsyncWorkItem(_req), req(_req) { } virtual ~CopyCompletionProfiler(void) { } virtual bool event_triggered(Event e) { mark_finished(); return false; } virtual void print_info(FILE *f) { fprintf(f, "copy completion profiler - " IDFMT "/%d\n", req->get_finish_event().id, req->get_finish_event().gen); } virtual void request_cancellation(void) { // ignored for now } protected: DmaRequest* req; }; #endif // for now we use a single queue for all (local) dmas static DmaRequestQueue *dma_queue = 0; void DmaRequestQueue::worker_thread_loop(void) { log_dma.info("dma worker thread created"); while(!shutdown_flag) { aio_context->make_progress(); bool aio_idle = aio_context->empty(); // get a request, sleeping as necessary DmaRequest *r = dequeue_request(aio_idle); if(r) { bool ok_to_run = r->mark_started(); if(ok_to_run) { // this will automatically add any necessary AsyncWorkItem's r->perform_dma(); r->mark_finished(true /*successful*/); } else r->mark_finished(false /*!successful*/); } } log_dma.info("dma worker thread terminating"); } void DmaRequestQueue::start_workers(int count) { ThreadLaunchParameters tlp; for(int i = 0; i < count; i++) { Thread *t = Thread::create_kernel_thread<DmaRequestQueue, &DmaRequestQueue::worker_thread_loop>(this, tlp, core_rsrv, 0 /* default scheduler*/); worker_threads.push_back(t); } } void start_dma_worker_threads(int count, Realm::CoreReservationSet& crs) { aio_context = new AsyncFileIOContext(256); dma_queue = new DmaRequestQueue(crs); dma_queue->start_workers(count); } void stop_dma_worker_threads(void) { dma_queue->shutdown_queue(); delete dma_queue; dma_queue = 0; delete aio_context; aio_context = 0; } }; }; namespace Realm { using namespace LegionRuntime::LowLevel; Event Domain::fill(const std::vector<CopySrcDstField> &dsts, const void *fill_value, size_t fill_value_size, Event wait_on /*= Event::NO_EVENT*/) const { Realm::ProfilingRequestSet reqs; return Domain::fill(dsts, reqs, fill_value, fill_value_size, wait_on); } Event Domain::fill(const std::vector<CopySrcDstField> &dsts, const Realm::ProfilingRequestSet &requests, const void *fill_value, size_t fill_value_size, Event wait_on /*= Event::NO_EVENT*/) const { std::set<Event> finish_events; for (std::vector<CopySrcDstField>::const_iterator it = dsts.begin(); it != dsts.end(); it++) { Event ev = GenEventImpl::create_genevent()->current_event(); FillRequest *r = new FillRequest(*this, *it, fill_value, fill_value_size, wait_on, ev, 0/*priority*/, requests); Memory mem = it->inst.get_location(); int node = ID(mem).node(); if (((unsigned)node) == gasnet_mynode()) { get_runtime()->optable.add_local_operation(ev, r); r->check_readiness(false, dma_queue); } else { RemoteFillArgs args; args.inst = it->inst; args.offset = it->offset; args.size = it->size; args.before_fill = wait_on; args.after_fill = ev; //args.priority = 0; size_t msglen = r->compute_size(); void *msgdata = malloc(msglen); r->serialize(msgdata); get_runtime()->optable.add_remote_operation(ev, node); RemoteFillMessage::request(node, args, msgdata, msglen, PAYLOAD_FREE); // release local copy of operation r->remove_reference(); } finish_events.insert(ev); } return GenEventImpl::merge_events(finish_events, false /*!ignore faults*/); } Event Domain::copy(RegionInstance src_inst, RegionInstance dst_inst, size_t elem_size, Event wait_on, ReductionOpID redop_id, bool red_fold) const { assert(0); std::vector<CopySrcDstField> srcs, dsts; srcs.push_back(CopySrcDstField(src_inst, 0, elem_size)); dsts.push_back(CopySrcDstField(dst_inst, 0, elem_size)); return copy(srcs, dsts, wait_on, redop_id, red_fold); } }; namespace LegionRuntime { namespace LowLevel { static int select_dma_node(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool red_fold) { int src_node = ID(src_mem).node(); int dst_node = ID(dst_mem).node(); bool src_is_rdma = get_runtime()->get_memory_impl(src_mem)->kind == MemoryImpl::MKIND_GLOBAL; bool dst_is_rdma = get_runtime()->get_memory_impl(dst_mem)->kind == MemoryImpl::MKIND_GLOBAL; if(src_is_rdma) { if(dst_is_rdma) { // gasnet -> gasnet - blech log_dma.warning("WARNING: gasnet->gasnet copy being serialized on local node (%d)", gasnet_mynode()); return gasnet_mynode(); } else { // gathers by the receiver return dst_node; } } else { if(dst_is_rdma) { // writing to gasnet is also best done by the sender return src_node; } else { // if neither side is gasnet, favor the sender (which may be the same as the target) return src_node; } } } void handle_remote_copy(RemoteCopyArgs args, const void *data, size_t msglen) { DetailedTimer::ScopedPush sp(TIME_LOW_LEVEL); // is this a copy or a reduction (they deserialize differently) if(args.redop_id == 0) { // a copy CopyRequest *r = new CopyRequest(data, msglen, args.before_copy, args.after_copy, args.priority); Realm::get_runtime()->optable.add_local_operation(args.after_copy, r); r->check_readiness(false, dma_queue); } else { // a reduction ReduceRequest *r = new ReduceRequest(data, msglen, args.redop_id, args.red_fold, args.before_copy, args.after_copy, args.priority); Realm::get_runtime()->optable.add_local_operation(args.after_copy, r); r->check_readiness(false, dma_queue); } } void handle_remote_fill(RemoteFillArgs args, const void *data, size_t msglen) { FillRequest *r = new FillRequest(data, msglen, args.inst, args.offset, args.size, args.before_fill, args.after_fill, 0 /* no room for args.priority */); Realm::get_runtime()->optable.add_local_operation(args.after_fill, r); r->check_readiness(false, dma_queue); } template <typename T> T min(T a, T b) { return (a < b) ? a : b; } }; }; namespace Realm { Event Domain::copy(const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, Event wait_on, ReductionOpID redop_id, bool red_fold) const { Realm::ProfilingRequestSet reqs; return Domain::copy(srcs, dsts, reqs, wait_on, redop_id, red_fold); } Event Domain::copy(const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, const Realm::ProfilingRequestSet &requests, Event wait_on, ReductionOpID redop_id, bool red_fold) const { if(redop_id == 0) { // not a reduction, so sort fields by src/dst mem pairs OASByMem oas_by_mem; std::vector<CopySrcDstField>::const_iterator src_it = srcs.begin(); std::vector<CopySrcDstField>::const_iterator dst_it = dsts.begin(); unsigned src_suboffset = 0; unsigned dst_suboffset = 0; std::set<Event> finish_events; while((src_it != srcs.end()) && (dst_it != dsts.end())) { InstPair ip(src_it->inst, dst_it->inst); MemPair mp(get_runtime()->get_instance_impl(src_it->inst)->memory, get_runtime()->get_instance_impl(dst_it->inst)->memory); // printf("I:(%x/%x) M:(%x/%x) sub:(%d/%d) src=(%d/%d) dst=(%d/%d)\n", // ip.first.id, ip.second.id, mp.first.id, mp.second.id, // src_suboffset, dst_suboffset, // src_it->offset, src_it->size, // dst_it->offset, dst_it->size); OffsetsAndSize oas; oas.src_offset = src_it->offset + src_suboffset; oas.dst_offset = dst_it->offset + dst_suboffset; oas.size = min(src_it->size - src_suboffset, dst_it->size - dst_suboffset); oas.serdez_id = src_it->serdez_id; // <SERDEZ_DMA> // This is a little bit of hack: if serdez_id != 0 we directly create a // CopyRequest instead of inserting it into ''oasvec'' if (oas.serdez_id != 0) { OASByInst* oas_by_inst = new OASByInst; (*oas_by_inst)[ip].push_back(oas); Event ev = GenEventImpl::create_genevent()->current_event(); int priority = 0; // always have priority zero CopyRequest *r = new CopyRequest(*this, oas_by_inst, wait_on, ev, priority, requests); // ask which node should perform the copy int dma_node = select_dma_node(mp.first, mp.second, redop_id, red_fold); log_dma.info("copy: srcmem=" IDFMT " dstmem=" IDFMT " node=%d", mp.first.id, mp.second.id, dma_node); if(((unsigned)dma_node) == gasnet_mynode()) { log_dma.info("performing serdez on local node"); Realm::get_runtime()->optable.add_local_operation(ev, r); r->check_readiness(false, dma_queue); finish_events.insert(ev); } else { RemoteCopyArgs args; args.redop_id = 0; args.red_fold = false; args.before_copy = wait_on; args.after_copy = ev; args.priority = priority; size_t msglen = r->compute_size(); void *msgdata = malloc(msglen); r->serialize(msgdata); log_dma.info("performing serdez on remote node (%d), event=" IDFMT "/%d", dma_node, args.after_copy.id, args.after_copy.gen); get_runtime()->optable.add_remote_operation(ev, dma_node); RemoteCopyMessage::request(dma_node, args, msgdata, msglen, PAYLOAD_FREE); finish_events.insert(ev); // done with the local copy of the request r->remove_reference(); } } else { // </SERDEZ_DMA> OASByInst *oas_by_inst; OASByMem::iterator it = oas_by_mem.find(mp); if(it != oas_by_mem.end()) { oas_by_inst = it->second; } else { oas_by_inst = new OASByInst; oas_by_mem[mp] = oas_by_inst; } OASVec& oasvec = (*oas_by_inst)[ip]; oasvec.push_back(oas); } src_suboffset += oas.size; assert(src_suboffset <= src_it->size); if(src_suboffset == src_it->size) { src_it++; src_suboffset = 0; } dst_suboffset += oas.size; assert(dst_suboffset <= dst_it->size); if(dst_suboffset == dst_it->size) { dst_it++; dst_suboffset = 0; } } // make sure we used up both assert(src_it == srcs.end()); assert(dst_it == dsts.end()); log_dma.info("copy: %zd distinct src/dst mem pairs, is=" IDFMT "", oas_by_mem.size(), is_id); for(OASByMem::const_iterator it = oas_by_mem.begin(); it != oas_by_mem.end(); it++) { Memory src_mem = it->first.first; Memory dst_mem = it->first.second; OASByInst *oas_by_inst = it->second; Event ev = GenEventImpl::create_genevent()->current_event(); #ifdef EVENT_GRAPH_TRACE Event enclosing = find_enclosing_termination_event(); log_event_graph.info("Copy Request: (" IDFMT ",%d) (" IDFMT ",%d) " "(" IDFMT ",%d) " IDFMT " " IDFMT "", ev.id, ev.gen, wait_on.id, wait_on.gen, enclosing.id, enclosing.gen, src_mem.id, dst_mem.id); #endif int priority = 0; if (get_runtime()->get_memory_impl(src_mem)->kind == MemoryImpl::MKIND_GPUFB) priority = 1; else if (get_runtime()->get_memory_impl(dst_mem)->kind == MemoryImpl::MKIND_GPUFB) priority = 1; CopyRequest *r = new CopyRequest(*this, oas_by_inst, wait_on, ev, priority, requests); // ask which node should perform the copy int dma_node = select_dma_node(src_mem, dst_mem, redop_id, red_fold); log_dma.info("copy: srcmem=" IDFMT " dstmem=" IDFMT " node=%d", src_mem.id, dst_mem.id, dma_node); if(((unsigned)dma_node) == gasnet_mynode()) { log_dma.info("performing copy on local node"); get_runtime()->optable.add_local_operation(ev, r); r->check_readiness(false, dma_queue); finish_events.insert(ev); } else { RemoteCopyArgs args; args.redop_id = 0; args.red_fold = false; args.before_copy = wait_on; args.after_copy = ev; args.priority = priority; size_t msglen = r->compute_size(); void *msgdata = malloc(msglen); r->serialize(msgdata); log_dma.info("performing copy on remote node (%d), event=" IDFMT "/%d", dma_node, args.after_copy.id, args.after_copy.gen); get_runtime()->optable.add_remote_operation(ev, dma_node); RemoteCopyMessage::request(dma_node, args, msgdata, msglen, PAYLOAD_FREE); finish_events.insert(ev); // done with the local copy of the request r->remove_reference(); } } // final event is merge of all individual copies' events return GenEventImpl::merge_events(finish_events, false /*!ignore faults*/); } else { // we're doing a reduction - the semantics require that all source fields be pulled // together and applied as a "structure" to the reduction op // figure out where the source data is int src_node = -1; for(std::vector<CopySrcDstField>::const_iterator src_it = srcs.begin(); src_it != srcs.end(); src_it++) { int n = ID(src_it->inst).node(); if((src_node != -1) && (src_node != n)) { // for now, don't handle case where source data is split across nodes assert(0); } src_node = n; } assert(dsts.size() == 1); // some destinations (e.g. GASNET) need a lock taken to ensure // reductions are applied atomically MemoryImpl::MemoryKind dst_kind = get_runtime()->get_memory_impl(get_runtime()->get_instance_impl(dsts[0].inst)->memory)->kind; bool inst_lock_needed = (dst_kind == MemoryImpl::MKIND_GLOBAL); Event ev = GenEventImpl::create_genevent()->current_event(); ReduceRequest *r = new ReduceRequest(*this, srcs, dsts[0], inst_lock_needed, redop_id, red_fold, wait_on, ev, 0 /*priority*/, requests); if(((unsigned)src_node) == gasnet_mynode()) { log_dma.info("performing reduction on local node"); get_runtime()->optable.add_local_operation(ev, r); r->check_readiness(false, dma_queue); } else { RemoteCopyArgs args; args.redop_id = redop_id; args.red_fold = red_fold; args.before_copy = wait_on; args.after_copy = ev; args.priority = 0 /*priority*/; size_t msglen = r->compute_size(); void *msgdata = malloc(msglen); r->serialize(msgdata); log_dma.info("performing reduction on remote node (%d), event=" IDFMT "/%d", src_node, args.after_copy.id, args.after_copy.gen); get_runtime()->optable.add_remote_operation(ev, src_node); RemoteCopyMessage::request(src_node, args, msgdata, msglen, PAYLOAD_FREE); // done with the local copy of the request r->remove_reference(); } return ev; } } Event Domain::copy(const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, const ElementMask& mask, Event wait_on, ReductionOpID redop_id, bool red_fold) const { assert(redop_id == 0); assert(0); log_dma.warning("ignoring copy\n"); return Event::NO_EVENT; } Event Domain::copy_indirect(const CopySrcDstField& idx, const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, Event wait_on, ReductionOpID redop_id, bool red_fold) const { assert(redop_id == 0); assert(0); } Event Domain::copy_indirect(const CopySrcDstField& idx, const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, const ElementMask& mask, Event wait_on, ReductionOpID redop_id, bool red_fold) const { assert(redop_id == 0); assert(0); } }; dma: check for empty copies/reduces/fills /* Copyright 2016 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "realm/realm_config.h" #include "lowlevel_dma.h" #include "accessor.h" #include "realm/threads.h" #include <errno.h> // included for file memory data transfer #include <unistd.h> #ifdef REALM_USE_KERNEL_AIO #include <linux/aio_abi.h> #include <sys/syscall.h> #else #include <aio.h> #endif #include <queue> #define CHECK_PTHREAD(cmd) do { \ int ret = (cmd); \ if(ret != 0) { \ fprintf(stderr, "PTHREAD: %s = %d (%s)\n", #cmd, ret, strerror(ret)); \ exit(1); \ } \ } while(0) using namespace LegionRuntime::Accessor; #include "atomics.h" #include "realm/timers.h" #include "realm/serialize.h" using namespace Realm::Serialization; namespace LegionRuntime { namespace LowLevel { typedef Realm::GASNetMemory GASNetMemory; typedef Realm::DiskMemory DiskMemory; typedef Realm::FileMemory FileMemory; typedef Realm::Thread Thread; typedef Realm::ThreadLaunchParameters ThreadLaunchParameters; typedef Realm::CoreReservation CoreReservation; typedef Realm::CoreReservationParameters CoreReservationParameters; Logger::Category log_dma("dma"); Logger::Category log_aio("aio"); #ifdef EVENT_GRAPH_TRACE extern Logger::Category log_event_graph; extern Event find_enclosing_termination_event(void); #endif typedef std::pair<Memory, Memory> MemPair; typedef std::pair<RegionInstance, RegionInstance> InstPair; typedef std::map<InstPair, OASVec> OASByInst; typedef std::map<MemPair, OASByInst *> OASByMem; class DmaRequest; class DmaRequestQueue { public: DmaRequestQueue(Realm::CoreReservationSet& crs); void enqueue_request(DmaRequest *r); DmaRequest *dequeue_request(bool sleep = true); void shutdown_queue(void); void start_workers(int count); void worker_thread_loop(void); protected: GASNetHSL queue_mutex; GASNetCondVar queue_condvar; std::map<int, std::list<DmaRequest *> *> queues; int queue_sleepers; bool shutdown_flag; CoreReservation core_rsrv; std::vector<Thread *> worker_threads; }; //////////////////////////////////////////////////////////////////////// // // class DmaRequest // DmaRequest::DmaRequest(int _priority, Event _after_copy) : Operation(_after_copy, Realm::ProfilingRequestSet()), state(STATE_INIT), priority(_priority) { } DmaRequest::DmaRequest(int _priority, Event _after_copy, const Realm::ProfilingRequestSet &reqs) : Realm::Operation(_after_copy, reqs), state(STATE_INIT), priority(_priority) { } DmaRequest::~DmaRequest(void) { } void DmaRequest::print(std::ostream& os) const { os << "DmaRequest"; } //////////////////////////////////////////////////////////////////////// // // class DmaRequest::Waiter // DmaRequest::Waiter::Waiter(void) { } DmaRequest::Waiter::~Waiter(void) { } // dma requests come in two flavors: // 1) CopyRequests, which are per memory pair, and // 2) ReduceRequests, which have to be handled monolithically class CopyRequest : public DmaRequest { public: CopyRequest(const void *data, size_t datalen, Event _before_copy, Event _after_copy, int _priority); CopyRequest(const Domain& _domain, OASByInst *_oas_by_inst, Event _before_copy, Event _after_copy, int _priority, const Realm::ProfilingRequestSet &reqs); protected: // deletion performed when reference count goes to zero virtual ~CopyRequest(void); public: size_t compute_size(void) const; void serialize(void *buffer); virtual bool check_readiness(bool just_check, DmaRequestQueue *rq); void perform_dma_mask(MemPairCopier *mpc); template <unsigned DIM> void perform_dma_rect(MemPairCopier *mpc); virtual void perform_dma(void); virtual bool handler_safe(void) { return(false); } Domain domain; OASByInst *oas_by_inst; Event before_copy; Waiter waiter; // if we need to wait on events }; class ReduceRequest : public DmaRequest { public: ReduceRequest(const void *data, size_t datalen, ReductionOpID _redop_id, bool _red_fold, Event _before_copy, Event _after_copy, int _priority); ReduceRequest(const Domain& _domain, const std::vector<Domain::CopySrcDstField>& _srcs, const Domain::CopySrcDstField& _dst, bool _inst_lock_needed, ReductionOpID _redop_id, bool _red_fold, Event _before_copy, Event _after_copy, int _priority, const Realm::ProfilingRequestSet &reqs); protected: // deletion performed when reference count goes to zero virtual ~ReduceRequest(void); public: size_t compute_size(void); void serialize(void *buffer); virtual bool check_readiness(bool just_check, DmaRequestQueue *rq); void perform_dma_mask(MemPairCopier *mpc); template <unsigned DIM> void perform_dma_rect(MemPairCopier *mpc); virtual void perform_dma(void); virtual bool handler_safe(void) { return(false); } Domain domain; std::vector<Domain::CopySrcDstField> srcs; Domain::CopySrcDstField dst; bool inst_lock_needed; Event inst_lock_event; ReductionOpID redop_id; bool red_fold; Event before_copy; Waiter waiter; // if we need to wait on events }; class FillRequest : public DmaRequest { public: FillRequest(const void *data, size_t msglen, RegionInstance inst, unsigned offset, unsigned size, Event _before_fill, Event _after_fill, int priority); FillRequest(const Domain &_domain, const Domain::CopySrcDstField &_dst, const void *fill_value, size_t fill_size, Event _before_fill, Event _after_fill, int priority, const Realm::ProfilingRequestSet &reqs); protected: // deletion performed when reference count goes to zero virtual ~FillRequest(void); public: size_t compute_size(void); void serialize(void *buffer); virtual bool check_readiness(bool just_check, DmaRequestQueue *rq); virtual void perform_dma(void); virtual bool handler_safe(void) { return(false); } template<int DIM> void perform_dma_rect(MemoryImpl *mem_impl); size_t optimize_fill_buffer(RegionInstanceImpl *impl, int &fill_elmts); Domain domain; Domain::CopySrcDstField dst; void *fill_buffer; size_t fill_size; Event before_fill; Waiter waiter; }; DmaRequestQueue::DmaRequestQueue(Realm::CoreReservationSet& crs) : queue_condvar(queue_mutex) , core_rsrv("DMA request queue", crs, CoreReservationParameters()) { queue_sleepers = 0; shutdown_flag = false; } void DmaRequestQueue::shutdown_queue(void) { queue_mutex.lock(); assert(queues.empty()); // set the shutdown flag and wake up any sleepers shutdown_flag = true; queue_condvar.broadcast(); queue_mutex.unlock(); // reap all the threads for(std::vector<Thread *>::iterator it = worker_threads.begin(); it != worker_threads.end(); it++) { (*it)->join(); delete (*it); } worker_threads.clear(); } void DmaRequestQueue::enqueue_request(DmaRequest *r) { // Record that it is ready - check for cancellation though bool ok_to_run = r->mark_ready(); if(!ok_to_run) { r->mark_finished(false /*!successful*/); return; } queue_mutex.lock(); // there's a queue per priority level // priorities are negated so that the highest logical priority comes first int p = -r->priority; std::map<int, std::list<DmaRequest *> *>::iterator it = queues.find(p); if(it == queues.end()) { // nothing at this priority level - make a new list std::list<DmaRequest *> *l = new std::list<DmaRequest *>; l->push_back(r); queues[p] = l; } else { // push ourselves onto the back of the existing queue it->second->push_back(r); } // if anybody was sleeping, wake them up if(queue_sleepers > 0) { queue_sleepers = 0; queue_condvar.broadcast(); } queue_mutex.unlock(); } DmaRequest *DmaRequestQueue::dequeue_request(bool sleep /*= true*/) { queue_mutex.lock(); // quick check - are there any requests at all? while(queues.empty()) { if(!sleep || shutdown_flag) { queue_mutex.unlock(); return 0; } // sleep until there are, or until shutdown queue_sleepers++; queue_condvar.wait(); } // grab the first request from the highest-priority queue there is // priorities are negated so that the highest logical priority comes first std::map<int, std::list<DmaRequest *> *>::iterator it = queues.begin(); assert(!it->second->empty()); DmaRequest *r = it->second->front(); it->second->pop_front(); // if queue is empty, delete from list if(it->second->empty()) { delete it->second; queues.erase(it); } queue_mutex.unlock(); return r; } CopyRequest::CopyRequest(const void *data, size_t datalen, Event _before_copy, Event _after_copy, int _priority) : DmaRequest(_priority, _after_copy), oas_by_inst(0), before_copy(_before_copy) { const IDType *idata = (const IDType *)data; idata = domain.deserialize(idata); oas_by_inst = new OASByInst; size_t num_pairs = *idata++; for (unsigned idx = 0; idx < num_pairs; idx++) { RegionInstance src_inst = ID((IDType)*idata++).convert<RegionInstance>(); RegionInstance dst_inst = ID((IDType)*idata++).convert<RegionInstance>(); InstPair ip(src_inst, dst_inst); // If either one of the instances is in GPU memory increase priority if (priority == 0) { MemoryImpl::MemoryKind src_kind = get_runtime()->get_memory_impl(get_runtime()->get_instance_impl(src_inst)->memory)->kind; if (src_kind == MemoryImpl::MKIND_GPUFB) priority = 1; else { MemoryImpl::MemoryKind dst_kind = get_runtime()->get_memory_impl(get_runtime()->get_instance_impl(dst_inst)->memory)->kind; if (dst_kind == MemoryImpl::MKIND_GPUFB) priority = 1; } } OASVec& oasvec = (*oas_by_inst)[ip]; unsigned count = *idata++; for(unsigned i = 0; i < count; i++) { OffsetsAndSize oas; oas.src_offset = *idata++; oas.dst_offset = *idata++; oas.size = *idata++; oas.serdez_id = *idata++; oasvec.push_back(oas); } } // Unpack any profiling requests // TODO: unbreak once the serialization stuff is repaired //const void *result = requests.deserialize(idata); //Realm::Operation::reconstruct_measurements(); // better have consumed exactly the right amount of data //assert((((unsigned long)result) - ((unsigned long)data)) == datalen); size_t request_size = *reinterpret_cast<const size_t*>(idata); idata += sizeof(size_t) / sizeof(IDType); FixedBufferDeserializer deserializer(idata, request_size); deserializer >> requests; Realm::Operation::reconstruct_measurements(); log_dma.info("dma request %p deserialized - " IDFMT "[%zd]->" IDFMT "[%zd]:%d (+%zd) (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, oas_by_inst->begin()->first.first.id, oas_by_inst->begin()->second[0].src_offset, oas_by_inst->begin()->first.second.id, oas_by_inst->begin()->second[0].dst_offset, oas_by_inst->begin()->second[0].size, oas_by_inst->begin()->second.size() - 1, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); } CopyRequest::CopyRequest(const Domain& _domain, OASByInst *_oas_by_inst, Event _before_copy, Event _after_copy, int _priority, const Realm::ProfilingRequestSet &reqs) : DmaRequest(_priority, _after_copy, reqs), domain(_domain), oas_by_inst(_oas_by_inst), before_copy(_before_copy) { log_dma.info() << "dma request " << (void *)this << " created - is=" << domain << " before=" << before_copy << " after=" << get_finish_event(); for(OASByInst::const_iterator it = oas_by_inst->begin(); it != oas_by_inst->end(); it++) for(OASVec::const_iterator it2 = it->second.begin(); it2 != it->second.end(); it2++) log_dma.info() << "dma request " << (void *)this << " field: " << it->first.first << "[" << it2->src_offset << "]->" << it->first.second << "[" << it2->dst_offset << "] size=" << it2->size; } CopyRequest::~CopyRequest(void) { delete oas_by_inst; } size_t CopyRequest::compute_size(void) const { size_t result = domain.compute_size(); result += sizeof(IDType); // number of requests; for(OASByInst::iterator it2 = oas_by_inst->begin(); it2 != oas_by_inst->end(); it2++) { OASVec& oasvec = it2->second; result += (3 + oasvec.size() * 4) * sizeof(IDType); } // TODO: unbreak once the serialization stuff is repaired //result += requests.compute_size(); ByteCountSerializer counter; counter << requests; result += sizeof(size_t) + counter.bytes_used(); return result; } void CopyRequest::serialize(void *buffer) { // domain info goes first IDType *msgptr = domain.serialize((IDType *)buffer); *msgptr++ = oas_by_inst->size(); // now OAS vectors for(OASByInst::iterator it2 = oas_by_inst->begin(); it2 != oas_by_inst->end(); it2++) { RegionInstance src_inst = it2->first.first; RegionInstance dst_inst = it2->first.second; OASVec& oasvec = it2->second; *msgptr++ = src_inst.id; *msgptr++ = dst_inst.id; *msgptr++ = oasvec.size(); for(OASVec::iterator it3 = oasvec.begin(); it3 != oasvec.end(); it3++) { *msgptr++ = it3->src_offset; *msgptr++ = it3->dst_offset; *msgptr++ = it3->size; *msgptr++ = it3->serdez_id; } } // TODO: unbreak once the serialization stuff is repaired //requests.serialize(msgptr); // We sent this message remotely, so we need to clear the profiling // so it doesn't get sent accidentally ByteCountSerializer counter; counter << requests; *reinterpret_cast<size_t*>(msgptr) = counter.bytes_used(); msgptr += sizeof(size_t) / sizeof(IDType); FixedBufferSerializer serializer(msgptr, counter.bytes_used()); serializer << requests; clear_profiling(); } void DmaRequest::Waiter::sleep_on_event(Event e, Reservation l /*= Reservation::NO_RESERVATION*/) { current_lock = l; EventImpl::add_waiter(e, this); } bool DmaRequest::Waiter::event_triggered(Event e, bool poisoned) { if(poisoned) { Realm::log_poison.info() << "cancelling poisoned dma operation - op=" << req << " after=" << req->get_finish_event(); // cancel the dma operation - this has to work bool did_cancel = req->attempt_cancellation(Realm::Faults::ERROR_POISONED_PRECONDITION, &e, sizeof(e)); assert(did_cancel); return false; } log_dma.info("request %p triggered in state %d (lock = " IDFMT ")", req, req->state, current_lock.id); if(current_lock.exists()) { current_lock.release(); current_lock = Reservation::NO_RESERVATION; } // this'll enqueue the DMA if it can, or wait on another event if it // can't req->check_readiness(false, queue); // don't delete us! return false; } void DmaRequest::Waiter::print(std::ostream& os) const { os << "dma request " << req << ": after " << req->get_finish_event(); } bool CopyRequest::check_readiness(bool just_check, DmaRequestQueue *rq) { if(state == STATE_INIT) state = STATE_METADATA_FETCH; // remember which queue we're going to be assigned to if we sleep waiter.req = this; waiter.queue = rq; // make sure our node has all the meta data it needs, but don't take more than one lock // at a time if(state == STATE_METADATA_FETCH) { // index space first if(domain.get_dim() == 0) { IndexSpaceImpl *is_impl = get_runtime()->get_index_space_impl(domain.get_index_space()); if(!is_impl->locked_data.valid) { log_dma.info("dma request %p - no index space metadata yet", this); if(just_check) return false; Event e = is_impl->lock.acquire(1, false); if(e.has_triggered()) { log_dma.info("request %p - index space metadata invalid - instant trigger", this); is_impl->lock.release(); } else { log_dma.info("request %p - index space metadata invalid - sleeping on lock " IDFMT "", this, is_impl->lock.me.id); waiter.sleep_on_event(e, is_impl->lock.me); return false; } } // we need more than just the metadata - we also need the valid mask { Event e = is_impl->request_valid_mask(); if(!e.has_triggered()) { log_dma.info("request %p - valid mask needed for index space " IDFMT " - sleeping on event " IDFMT "/%d", this, domain.get_index_space().id, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // now go through all instance pairs for(OASByInst::iterator it = oas_by_inst->begin(); it != oas_by_inst->end(); it++) { RegionInstanceImpl *src_impl = get_runtime()->get_instance_impl(it->first.first); RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(it->first.second); { Event e = src_impl->request_metadata(); if(!e.has_triggered()) { if(just_check) { log_dma.info("dma request %p - no src instance (" IDFMT ") metadata yet", this, src_impl->me.id); return false; } log_dma.info("request %p - src instance metadata invalid - sleeping on event " IDFMT "/%d", this, e.id, e.gen); waiter.sleep_on_event(e); return false; } } { Event e = dst_impl->request_metadata(); if(!e.has_triggered()) { if(just_check) { log_dma.info("dma request %p - no dst instance (" IDFMT ") metadata yet", this, dst_impl->me.id); return false; } log_dma.info("request %p - dst instance metadata invalid - sleeping on event " IDFMT "/%d", this, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // if we got all the way through, we've got all the metadata we need state = STATE_BEFORE_EVENT; } // make sure our functional precondition has occurred if(state == STATE_BEFORE_EVENT) { // has the before event triggered? if not, wait on it if(before_copy.has_triggered()) { log_dma.info("request %p - before event triggered", this); state = STATE_READY; } else { log_dma.info("request %p - before event not triggered", this); if(just_check) return false; log_dma.info("request %p - sleeping on before event", this); waiter.sleep_on_event(before_copy); return false; } } if(state == STATE_READY) { log_dma.info("request %p ready", this); if(just_check) return true; state = STATE_QUEUED; assert(rq != 0); log_dma.info("request %p enqueued", this); // once we're enqueued, we may be deleted at any time, so no more // references rq->enqueue_request(this); return true; } if(state == STATE_QUEUED) return true; assert(0); return false; } namespace RangeExecutors { class Memcpy { public: Memcpy(void *_dst_base, const void *_src_base, size_t _elmt_size) : dst_base((char *)_dst_base), src_base((const char *)_src_base), elmt_size(_elmt_size) {} template <class T> Memcpy(T *_dst_base, const T *_src_base) : dst_base((char *)_dst_base), src_base((const char *)_src_base), elmt_size(sizeof(T)) {} void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; memcpy(dst_base + byte_offset, src_base + byte_offset, byte_count); } protected: char *dst_base; const char *src_base; size_t elmt_size; }; class GasnetPut { public: GasnetPut(MemoryImpl *_tgt_mem, off_t _tgt_offset, const void *_src_ptr, size_t _elmt_size) : tgt_mem(_tgt_mem), tgt_offset(_tgt_offset), src_ptr((const char *)_src_ptr), elmt_size(_elmt_size) {} virtual ~GasnetPut(void) { } void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; tgt_mem->put_bytes(tgt_offset + byte_offset, src_ptr + byte_offset, byte_count); } protected: MemoryImpl *tgt_mem; off_t tgt_offset; const char *src_ptr; size_t elmt_size; }; class GasnetPutBatched { public: GasnetPutBatched(MemoryImpl *_tgt_mem, off_t _tgt_offset, const void *_src_ptr, size_t _elmt_size) : tgt_mem((GASNetMemory *)_tgt_mem), tgt_offset(_tgt_offset), src_ptr((const char *)_src_ptr), elmt_size(_elmt_size) {} void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; offsets.push_back(tgt_offset + byte_offset); srcs.push_back(src_ptr + byte_offset); sizes.push_back(byte_count); } void finish(void) { if(offsets.size() > 0) { DetailedTimer::ScopedPush sp(TIME_SYSTEM); tgt_mem->put_batch(offsets.size(), &offsets[0], &srcs[0], &sizes[0]); } } protected: GASNetMemory *tgt_mem; off_t tgt_offset; const char *src_ptr; size_t elmt_size; std::vector<off_t> offsets; std::vector<const void *> srcs; std::vector<size_t> sizes; }; class GasnetPutReduce : public GasnetPut { public: GasnetPutReduce(MemoryImpl *_tgt_mem, off_t _tgt_offset, const ReductionOpUntyped *_redop, bool _redfold, const void *_src_ptr, size_t _elmt_size) : GasnetPut(_tgt_mem, _tgt_offset, _src_ptr, _elmt_size), redop(_redop), redfold(_redfold) {} virtual ~GasnetPutReduce(void) { } void do_span(int offset, int count) { assert(redfold == false); off_t tgt_byte_offset = offset * redop->sizeof_lhs; off_t src_byte_offset = offset * elmt_size; assert(elmt_size == redop->sizeof_rhs); char buffer[1024]; assert(redop->sizeof_lhs <= 1024); for(int i = 0; i < count; i++) { tgt_mem->get_bytes(tgt_offset + tgt_byte_offset, buffer, redop->sizeof_lhs); redop->apply(buffer, src_ptr + src_byte_offset, 1, true); tgt_mem->put_bytes(tgt_offset + tgt_byte_offset, buffer, redop->sizeof_lhs); } } protected: const ReductionOpUntyped *redop; bool redfold; }; class GasnetPutRedList : public GasnetPut { public: GasnetPutRedList(MemoryImpl *_tgt_mem, off_t _tgt_offset, ReductionOpID _redopid, const ReductionOpUntyped *_redop, const void *_src_ptr, size_t _elmt_size) : GasnetPut(_tgt_mem, _tgt_offset, _src_ptr, _elmt_size), redopid(_redopid), redop(_redop) {} virtual ~GasnetPutRedList(void) { } void do_span(int offset, int count) { if(count == 0) return; assert(offset == 0); // too lazy to do pointer math on _src_ptr unsigned *ptrs = new unsigned[count]; redop->get_list_pointers(ptrs, src_ptr, count); // now figure out how many reductions go to each node unsigned *nodecounts = new unsigned[gasnet_nodes()]; for(unsigned i = 0; i < gasnet_nodes(); i++) nodecounts[i] = 0; for(int i = 0; i < count; i++) { off_t elem_offset = tgt_offset + ptrs[i] * redop->sizeof_lhs; int home_node = tgt_mem->get_home_node(elem_offset, redop->sizeof_lhs); assert(home_node >= 0); ptrs[i] = home_node; nodecounts[home_node]++; } size_t max_entries_per_msg = (1 << 20) / redop->sizeof_list_entry; char *entry_buffer = new char[max_entries_per_msg * redop->sizeof_list_entry]; for(unsigned i = 0; i < gasnet_nodes(); i++) { unsigned pos = 0; for(int j = 0; j < count; j++) { //printf("S: [%d] = %d\n", j, ptrs[j]); if(ptrs[j] != i) continue; memcpy(entry_buffer + (pos * redop->sizeof_list_entry), ((const char *)src_ptr) + (j * redop->sizeof_list_entry), redop->sizeof_list_entry); pos++; if(pos == max_entries_per_msg) { if(i == gasnet_mynode()) { tgt_mem->apply_reduction_list(tgt_offset, redop, pos, entry_buffer); } else { do_remote_apply_red_list(i, tgt_mem->me, tgt_offset, redopid, entry_buffer, pos * redop->sizeof_list_entry, 0); } pos = 0; } } if(pos > 0) { if(i == gasnet_mynode()) { tgt_mem->apply_reduction_list(tgt_offset, redop, pos, entry_buffer); } else { do_remote_apply_red_list(i, tgt_mem->me, tgt_offset, redopid, entry_buffer, pos * redop->sizeof_list_entry, 0); } } } delete[] entry_buffer; delete[] ptrs; delete[] nodecounts; } protected: ReductionOpID redopid; const ReductionOpUntyped *redop; }; class GasnetGet { public: GasnetGet(void *_tgt_ptr, MemoryImpl *_src_mem, off_t _src_offset, size_t _elmt_size) : tgt_ptr((char *)_tgt_ptr), src_mem(_src_mem), src_offset(_src_offset), elmt_size(_elmt_size) {} void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; DetailedTimer::ScopedPush sp(TIME_SYSTEM); src_mem->get_bytes(src_offset + byte_offset, tgt_ptr + byte_offset, byte_count); } protected: char *tgt_ptr; MemoryImpl *src_mem; off_t src_offset; size_t elmt_size; }; class GasnetGetBatched { public: GasnetGetBatched(void *_tgt_ptr, MemoryImpl *_src_mem, off_t _src_offset, size_t _elmt_size) : tgt_ptr((char *)_tgt_ptr), src_mem((GASNetMemory *)_src_mem), src_offset(_src_offset), elmt_size(_elmt_size) {} void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; offsets.push_back(src_offset + byte_offset); dsts.push_back(tgt_ptr + byte_offset); sizes.push_back(byte_count); } void finish(void) { if(offsets.size() > 0) { DetailedTimer::ScopedPush sp(TIME_SYSTEM); src_mem->get_batch(offsets.size(), &offsets[0], &dsts[0], &sizes[0]); } } protected: char *tgt_ptr; GASNetMemory *src_mem; off_t src_offset; size_t elmt_size; std::vector<off_t> offsets; std::vector<void *> dsts; std::vector<size_t> sizes; }; class GasnetGetAndPut { public: GasnetGetAndPut(MemoryImpl *_tgt_mem, off_t _tgt_offset, MemoryImpl *_src_mem, off_t _src_offset, size_t _elmt_size) : tgt_mem(_tgt_mem), tgt_offset(_tgt_offset), src_mem(_src_mem), src_offset(_src_offset), elmt_size(_elmt_size) {} static const size_t CHUNK_SIZE = 16384; void do_span(int offset, int count) { off_t byte_offset = offset * elmt_size; size_t byte_count = count * elmt_size; while(byte_count > CHUNK_SIZE) { src_mem->get_bytes(src_offset + byte_offset, chunk, CHUNK_SIZE); tgt_mem->put_bytes(tgt_offset + byte_offset, chunk, CHUNK_SIZE); byte_offset += CHUNK_SIZE; byte_count -= CHUNK_SIZE; } if(byte_count > 0) { src_mem->get_bytes(src_offset + byte_offset, chunk, byte_count); tgt_mem->put_bytes(tgt_offset + byte_offset, chunk, byte_count); } } protected: MemoryImpl *tgt_mem; off_t tgt_offset; MemoryImpl *src_mem; off_t src_offset; size_t elmt_size; char chunk[CHUNK_SIZE]; }; #ifdef DEAD_DMA_CODE class RemoteWrite { public: RemoteWrite(Memory _tgt_mem, off_t _tgt_offset, const void *_src_ptr, size_t _elmt_size, Event _event) : tgt_mem(_tgt_mem), tgt_offset(_tgt_offset), src_ptr((const char *)_src_ptr), elmt_size(_elmt_size), event(_event), span_count(0) {} void do_span(int offset, int count) { // if this isn't the first span, push the previous one out before // we overwrite it if(span_count > 0) really_do_span(false); span_count++; prev_offset = offset; prev_count = count; } Event finish(void) { log_dma.debug("remote write done with %d spans", span_count); // if we got any spans, the last one is still waiting to go out if(span_count > 0) { really_do_span(true); return Event::NO_EVENT; // recipient will trigger the event } return event; } protected: void really_do_span(bool last) { off_t byte_offset = prev_offset * elmt_size; size_t byte_count = prev_count * elmt_size; // if we don't have an event for our completion, we need one now if(!event.exists()) event = GenEventImpl::create_genevent()->current_event(); DetailedTimer::ScopedPush sp(TIME_SYSTEM); do_remote_write(tgt_mem, tgt_offset + byte_offset, src_ptr + byte_offset, byte_count, 0, last ? event : Event::NO_EVENT); } Memory tgt_mem; off_t tgt_offset; const char *src_ptr; size_t elmt_size; Event event; int span_count; int prev_offset, prev_count; }; #endif }; // namespace RangeExecutors // helper function to figure out which field we're in void find_field_start(const std::vector<size_t>& field_sizes, off_t byte_offset, size_t size, off_t& field_start, int& field_size) { off_t start = 0; for(std::vector<size_t>::const_iterator it = field_sizes.begin(); it != field_sizes.end(); it++) { assert((*it) > 0); if(byte_offset < (off_t)(*it)) { assert((byte_offset + size) <= (*it)); field_start = start; field_size = (*it); return; } start += (*it); byte_offset -= (*it); } assert(0); } class RemoteWriteInstPairCopier : public InstPairCopier { public: RemoteWriteInstPairCopier(RegionInstance src_inst, RegionInstance dst_inst, OASVec &_oas_vec) : src_acc(src_inst.get_accessor()), dst_acc(dst_inst.get_accessor()), oas_vec(_oas_vec) {} virtual ~RemoteWriteInstPairCopier(void) { } virtual void copy_field(int src_index, int dst_index, int elem_count, unsigned offset_index) { unsigned src_offset = oas_vec[offset_index].src_offset; unsigned dst_offset = oas_vec[offset_index].dst_offset; unsigned bytes = oas_vec[offset_index].size; char buffer[1024]; for(int i = 0; i < elem_count; i++) { src_acc.read_untyped(ptr_t(src_index + i), buffer, bytes, src_offset); if(0 && i == 0) { printf("remote write: (%d:%d->%d:%d) %d bytes:", src_index + i, src_offset, dst_index + i, dst_offset, bytes); for(unsigned j = 0; j < bytes; j++) printf(" %02x", (unsigned char)(buffer[j])); printf("\n"); } dst_acc.write_untyped(ptr_t(dst_index + i), buffer, bytes, dst_offset); } } virtual void flush(void) {} protected: RegionAccessor<AccessorType::Generic> src_acc; RegionAccessor<AccessorType::Generic> dst_acc; OASVec &oas_vec; }; //////////////////////////////////////////////////////////////////////// // // class MemPairCopier // MemPairCopier::MemPairCopier(void) : total_reqs(0), total_bytes(0) { } MemPairCopier::~MemPairCopier(void) { } // default behavior of flush is just to report bytes (maybe) void MemPairCopier::flush(DmaRequest *req) { #ifdef EVENT_GRAPH_TRACE log_event_graph.debug("Copy Size: (" IDFMT ",%d) %ld", after_copy.id, after_copy.gen, total_bytes); report_bytes(after_copy); #endif } void MemPairCopier::record_bytes(size_t bytes) { total_reqs++; total_bytes += bytes; } //////////////////////////////////////////////////////////////////////// // // class MemPairCopierFactory // MemPairCopierFactory::MemPairCopierFactory(const std::string& _name) : name(_name) { } MemPairCopierFactory::~MemPairCopierFactory(void) { } const std::string& MemPairCopierFactory::get_name(void) const { return name; } class BufferedMemPairCopier : public MemPairCopier { public: BufferedMemPairCopier(Memory _src_mem, Memory _dst_mem, size_t _buffer_size = 32768) : buffer_size(_buffer_size) { src_mem = get_runtime()->get_memory_impl(_src_mem); dst_mem = get_runtime()->get_memory_impl(_dst_mem); buffer = new char[buffer_size]; } virtual ~BufferedMemPairCopier(void) { delete[] buffer; } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<BufferedMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("buffered copy of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); while(bytes > buffer_size) { src_mem->get_bytes(src_offset, buffer, buffer_size); dst_mem->put_bytes(dst_offset, buffer, buffer_size); src_offset += buffer_size; dst_offset += buffer_size; bytes -= buffer_size; record_bytes(buffer_size); } if(bytes > 0) { src_mem->get_bytes(src_offset, buffer, bytes); dst_mem->put_bytes(dst_offset, buffer, bytes); record_bytes(bytes); } } // default behavior of 2D copy is to unroll to 1D copies void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: size_t buffer_size; MemoryImpl *src_mem, *dst_mem; char *buffer; }; class MemcpyMemPairCopier : public MemPairCopier { public: MemcpyMemPairCopier(Memory _src_mem, Memory _dst_mem) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_impl->get_direct_ptr(0, src_impl->size)); assert(src_base); MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); assert(dst_base); } virtual ~MemcpyMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<MemcpyMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("memcpy of %zd bytes\n", bytes); memcpy(dst_base + dst_offset, src_base + src_offset, bytes); record_bytes(bytes); } // default behavior of 2D copy is to unroll to 1D copies void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: const char *src_base; char *dst_base; }; class LocalReductionMemPairCopier : public MemPairCopier { public: LocalReductionMemPairCopier(Memory _src_mem, Memory _dst_mem, ReductionOpID redop_id, bool _fold) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_impl->get_direct_ptr(0, src_impl->size)); assert(src_base); MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); assert(dst_base); redop = get_runtime()->reduce_op_table[redop_id]; fold = _fold; } virtual ~LocalReductionMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<LocalReductionMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("reduction of %zd bytes\n", bytes); assert((bytes % redop->sizeof_rhs) == 0); if(fold) redop->fold(dst_base + dst_offset, src_base + src_offset, bytes / redop->sizeof_rhs, false /*non-exclusive*/); else redop->apply(dst_base + dst_offset, src_base + src_offset, bytes / redop->sizeof_rhs, false /*non-exclusive*/); } // default behavior of 2D copy is to unroll to 1D copies void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { // two cases here: // 1) if bytes == sizeof_rhs, we can use the apply/fold_strided calls if(bytes == redop->sizeof_rhs) { if(fold) redop->fold_strided(dst_base + dst_offset, src_base + src_offset, src_stride, dst_stride, lines, false /*non-exclusive*/); else redop->apply_strided(dst_base + dst_offset, src_base + src_offset, src_stride, dst_stride, lines, false /*non-exclusive*/); return; } // 2) with multiple elements per line, have to do a apply/fold call per line while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: const char *src_base; char *dst_base; const ReductionOpUntyped *redop; bool fold; }; class BufferedReductionMemPairCopier : public MemPairCopier { public: BufferedReductionMemPairCopier(Memory _src_mem, Memory _dst_mem, ReductionOpID redop_id, bool _fold, size_t _buffer_size = 1024) // in elements : buffer_size(_buffer_size) { src_mem = get_runtime()->get_memory_impl(_src_mem); dst_mem = get_runtime()->get_memory_impl(_dst_mem); redop = get_runtime()->reduce_op_table[redop_id]; fold = _fold; src_buffer = new char[buffer_size * redop->sizeof_rhs]; dst_buffer = new char[buffer_size * (fold ? redop->sizeof_rhs : redop->sizeof_lhs)]; } virtual ~BufferedReductionMemPairCopier(void) { delete[] src_buffer; delete[] dst_buffer; } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<BufferedReductionMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("buffered copy of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); size_t dst_size = fold ? redop->sizeof_rhs : redop->sizeof_lhs; assert((bytes % redop->sizeof_rhs) == 0); size_t elems = bytes / redop->sizeof_rhs; while(elems > 0) { // figure out how many elements we can do at a time size_t count = (elems > buffer_size) ? buffer_size : elems; // fetch source and dest data into buffers src_mem->get_bytes(src_offset, src_buffer, count * redop->sizeof_rhs); dst_mem->get_bytes(dst_offset, dst_buffer, count * dst_size); // apply reduction to local buffers if(fold) redop->fold(dst_buffer, src_buffer, count, true /*exclusive*/); else redop->apply(dst_buffer, src_buffer, count, true /*exclusive*/); dst_mem->put_bytes(dst_offset, dst_buffer, count * dst_size); src_offset += count * redop->sizeof_rhs; dst_offset += count * dst_size; elems -= count; } } // default behavior of 2D copy is to unroll to 1D copies void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: size_t buffer_size; MemoryImpl *src_mem, *dst_mem; char *src_buffer; char *dst_buffer; const ReductionOpUntyped *redop; bool fold; }; #if 0 // a MemPairCopier that keeps a list of events for component copies and doesn't trigger // the completion event until they're all done class DelayedMemPairCopierX : public MemPairCopier { public: DelayedMemPairCopierX(void) {} virtual ~DelayedMemPairCopierX(void) {} virtual void flush(Event after_copy) { // create a merged event for all the copies and used that to perform a delayed trigger // of the after_copy event (if it exists) if(after_copy.exists()) { if(events.size() > 0) { Event merged = GenEventImpl::merge_events(events); // deferred trigger based on this merged event get_runtime()->get_genevent_impl(after_copy)->trigger(after_copy.gen, gasnet_mynode(), merged); } else { // no actual copies occurred, so manually trigger event ourselves get_runtime()->get_genevent_impl(after_copy)->trigger(after_copy.gen, gasnet_mynode()); } } else { if(events.size() > 0) { // we don't have an event we can use to signal completion, so wait on the events ourself for(std::set<Event>::const_iterator it = events.begin(); it != events.end(); it++) (*it).wait(); } else { // nothing happened and we don't need to tell anyone - life is simple } } #ifdef EVENT_GRAPH_TRACE report_bytes(after_copy); #endif } protected: std::set<Event> events; }; #endif static unsigned rdma_sequence_no = 1; class RemoteWriteMemPairCopier : public MemPairCopier { public: RemoteWriteMemPairCopier(Memory _src_mem, Memory _dst_mem) { src_mem = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_mem->get_direct_ptr(0, src_mem->size)); assert(src_base); dst_mem = get_runtime()->get_memory_impl(_dst_mem); #ifdef TIME_REMOTE_WRITES span_time = 0; gather_time = 0; #endif sequence_id = __sync_fetch_and_add(&rdma_sequence_no, 1); num_writes = 0; } virtual ~RemoteWriteMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<RemoteWriteMemPairCopier>(this, src_inst, dst_inst, oas_vec); } struct PendingGather { off_t dst_start; off_t dst_size; SpanList src_spans; }; // this is no longer limited by LMB size, so try for large blocks when // possible static const size_t TARGET_XFER_SIZE = 4 << 20; void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("remote write of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #ifdef TIME_REMOTE_WRITES unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif record_bytes(bytes); if(bytes >= TARGET_XFER_SIZE) { // large enough that we can transfer it by itself #ifdef DEBUG_REMOTE_WRITES printf("remote write of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #endif num_writes += do_remote_write(dst_mem->me, dst_offset, src_base + src_offset, bytes, sequence_id, false /* no copy */); } else { // see if this can be added to an existing gather PendingGather *g; std::map<off_t, PendingGather *>::iterator it = gathers.find(dst_offset); if(it != gathers.end()) { g = it->second; gathers.erase(it); // remove from the existing location - we'll re-add it (probably) with the updated offset } else { // nope, start a new one g = new PendingGather; g->dst_start = dst_offset; g->dst_size = 0; } // sanity checks assert((g->dst_start + g->dst_size) == dst_offset); // now see if this particular span is disjoint or can be tacked on to the end of the last one if(g->src_spans.size() > 0) { SpanListEntry& last_span = g->src_spans.back(); if(((char *)(last_span.first) + last_span.second) == (src_base + src_offset)) { // append last_span.second += bytes; } else { g->src_spans.push_back(std::make_pair(src_base + src_offset, bytes)); } } else { // first span g->src_spans.push_back(std::make_pair(src_base + src_offset, bytes)); } g->dst_size += bytes; // is this span big enough to push now? if((size_t)g->dst_size >= TARGET_XFER_SIZE) { // yes, copy it copy_gather(g); delete g; } else { // no, put it back in the pending list, keyed by the next dst_offset that'll match it gathers.insert(std::make_pair(g->dst_start + g->dst_size, g)); } } #ifdef TIME_REMOTE_WRITES unsigned long long stop = TimeStamp::get_current_time_in_micros(); span_time += (stop - start); #endif } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { // case 1: although described as 2D, both src and dst coalesce if(((size_t)src_stride == bytes) && ((size_t)dst_stride == bytes)) { copy_span(src_offset, dst_offset, bytes * lines); return; } // case 2: if dst coalesces, we'll let the RDMA code do the gather for us - // this won't merge with any other copies though if((size_t)dst_stride == bytes) { #ifdef NEW2D_DEBUG printf("GATHER copy\n"); #endif num_writes += do_remote_write(dst_mem->me, dst_offset, src_base + src_offset, bytes, src_stride, lines, sequence_id, false /* no copy */); record_bytes(bytes * lines); return; } // default is to unroll the lines here, and let the PendingGather code try to // put things back in bigger pieces while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } void copy_gather(const PendingGather *g) { #ifdef TIME_REMOTE_WRITES unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif // special case: if there's only one source span, it's not actually // a gather (so we don't need to make a copy) if(g->src_spans.size() == 1) { const SpanListEntry& span = *(g->src_spans.begin()); #ifdef DEBUG_REMOTE_WRITES printf("remote write of %zd bytes (singleton " IDFMT ":%zd -> " IDFMT ":%zd)\n", span.second, src_mem->me.id, (char *)span.first - src_base, dst_mem->me.id, g->dst_start); printf(" datb[%p]: %08x %08x %08x %08x %08x %08x %08x %08x\n", span.first, ((unsigned *)(span.first))[0], ((unsigned *)(span.first))[1], ((unsigned *)(span.first))[2], ((unsigned *)(span.first))[3], ((unsigned *)(span.first))[4], ((unsigned *)(span.first))[5], ((unsigned *)(span.first))[6], ((unsigned *)(span.first))[7]); #endif // TODO: handle case where single write can include event trigger in message //num_writes += do_remote_write(dst_mem->me, g->dst_start, span.first, span.second, trigger, false /* no copy */); num_writes += do_remote_write(dst_mem->me, g->dst_start, span.first, span.second, sequence_id, false /* no copy */); return; } // general case: do_remote_write knows how to take a span list now, so let it // handle the actual gathering #ifdef DEBUG_REMOTE_WRITES printf("remote write of %zd bytes (gather -> " IDFMT ":%zd), trigger=" IDFMT "/%d\n", g->dst_size, dst_mem->me.id, g->dst_start, trigger.id, trigger.gen); #endif // TODO: handle case where single write can include event trigger in message num_writes += do_remote_write(dst_mem->me, g->dst_start, g->src_spans, g->dst_size, sequence_id, false /* no copy - data won't change til copy event triggers */); #ifdef TIME_REMOTE_WRITES unsigned long long stop = TimeStamp::get_current_time_in_micros(); gather_time += (stop - start); #endif } virtual void flush(DmaRequest *req) { #ifdef TIME_REMOTE_WRITES size_t total_gathers = gathers.size(); size_t total_spans = 0; for (std::map<off_t,PendingGather*>::const_iterator it = gathers.begin(); it != gathers.end(); it++) { total_spans += it->second->src_spans.size(); } unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif // do we have any pending gathers to push out? while(!gathers.empty()) { std::map<off_t, PendingGather *>::iterator it = gathers.begin(); PendingGather *g = it->second; gathers.erase(it); copy_gather(g); delete g; } // if we did any remote writes, we need a fence, and the DMA request // needs to know about it if(total_reqs > 0) { Realm::RemoteWriteFence *fence = new Realm::RemoteWriteFence(req); req->add_async_work_item(fence); do_remote_fence(dst_mem->me, sequence_id, num_writes, fence); } #ifdef TIME_REMOTE_WRITES unsigned long long stop = TimeStamp::get_current_time_in_micros(); gather_time += (stop - start); printf("Remote Write: span time: %lld gather time %lld " "total gathers %ld total spans %d\n", span_time, gather_time, total_gathers, total_spans); #endif MemPairCopier::flush(req); } protected: MemoryImpl *src_mem, *dst_mem; const char *src_base; std::map<off_t, PendingGather *> gathers; #ifdef TIME_REMOTE_WRITES unsigned long long span_time; unsigned long long gather_time; #endif unsigned sequence_id, num_writes; }; class RemoteReduceMemPairCopier : public MemPairCopier { public: RemoteReduceMemPairCopier(Memory _src_mem, Memory _dst_mem, ReductionOpID _redop_id, bool _fold) { src_mem = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_mem->get_direct_ptr(0, src_mem->size)); assert(src_base); dst_mem = get_runtime()->get_memory_impl(_dst_mem); redop_id = _redop_id; redop = get_runtime()->reduce_op_table[redop_id]; fold = _fold; sequence_id = __sync_fetch_and_add(&rdma_sequence_no, 1); num_writes = 0; } virtual ~RemoteReduceMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<RemoteReduceMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("remote write of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #ifdef TIME_REMOTE_WRITES unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif #ifdef DEBUG_REMOTE_WRITES printf("remote reduce of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #endif num_writes += do_remote_reduce(dst_mem->me, dst_offset, redop_id, fold, src_base + src_offset, bytes / redop->sizeof_rhs, redop->sizeof_rhs, redop->sizeof_lhs, sequence_id, false /* no copy */); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { // TODO: figure out 2D coalescing for reduction case (sizes may not match) //if((src_stride == bytes) && (dst_stride == bytes)) { // copy_span(src_offset, dst_offset, bytes * lines); // return; //} // default is to unroll the lines here while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } virtual void flush(DmaRequest *req) { // if we did any remote writes, we need a fence, and the DMA request // needs to know about it if(total_reqs > 0) { Realm::RemoteWriteFence *fence = new Realm::RemoteWriteFence(req); req->add_async_work_item(fence); do_remote_fence(dst_mem->me, sequence_id, num_writes, fence); } MemPairCopier::flush(req); } protected: MemoryImpl *src_mem, *dst_mem; const char *src_base; unsigned sequence_id, num_writes; ReductionOpID redop_id; const ReductionOpUntyped *redop; bool fold; }; class RemoteSerdezMemPairCopier : public MemPairCopier { public: RemoteSerdezMemPairCopier(Memory _src_mem, Memory _dst_mem, CustomSerdezID _serdez_id) { src_mem = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_mem->get_direct_ptr(0, src_mem->size)); assert(src_base); dst_mem = get_runtime()->get_memory_impl(_dst_mem); serdez_id = _serdez_id; serdez_op = get_runtime()->custom_serdez_table[serdez_id]; sequence_id = __sync_fetch_and_add(&rdma_sequence_no, 1); num_writes = 0; } virtual ~RemoteSerdezMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new SpanBasedInstPairCopier<RemoteSerdezMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("remote write of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #ifdef TIME_REMOTE_WRITES unsigned long long start = TimeStamp::get_current_time_in_micros(); #endif #ifdef DEBUG_REMOTE_WRITES printf("remote serdez of %zd bytes (" IDFMT ":%zd -> " IDFMT ":%zd)\n", bytes, src_mem->me.id, src_offset, dst_mem->me.id, dst_offset); #endif num_writes += do_remote_serdez(dst_mem->me, dst_offset, serdez_id, src_base + src_offset, bytes / serdez_op->sizeof_field_type, sequence_id); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { // TODO: figure out 2D coalescing for reduction case (sizes may not match) //if((src_stride == bytes) && (dst_stride == bytes)) { // copy_span(src_offset, dst_offset, bytes * lines); // return; //} // default is to unroll the lines here while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } virtual void flush(DmaRequest *req) { // if we did any remote writes, we need a fence, and the DMA request // needs to know about it if(total_reqs > 0) { Realm::RemoteWriteFence *fence = new Realm::RemoteWriteFence(req); req->add_async_work_item(fence); do_remote_fence(dst_mem->me, sequence_id, num_writes, fence); } MemPairCopier::flush(req); } protected: MemoryImpl *src_mem, *dst_mem; const char *src_base; unsigned sequence_id, num_writes; CustomSerdezID serdez_id; const CustomSerdezUntyped *serdez_op; }; class AsyncFileIOContext { public: AsyncFileIOContext(int _max_depth); ~AsyncFileIOContext(void); void enqueue_write(int fd, size_t offset, size_t bytes, const void *buffer); void enqueue_read(int fd, size_t offset, size_t bytes, void *buffer); void enqueue_fence(DmaRequest *req); bool empty(void); void make_progress(void); class AIOOperation { public: virtual ~AIOOperation(void) {} virtual void launch(void) = 0; virtual bool check_completion(void) = 0; bool completed; }; int max_depth; std::deque<AIOOperation *> launched_operations, pending_operations; GASNetHSL mutex; #ifdef REALM_USE_KERNEL_AIO aio_context_t aio_ctx; #endif }; static AsyncFileIOContext *aio_context = 0; #ifdef REALM_USE_KERNEL_AIO inline int io_setup(unsigned nr, aio_context_t *ctxp) { return syscall(__NR_io_setup, nr, ctxp); } inline int io_destroy(aio_context_t ctx) { return syscall(__NR_io_destroy, ctx); } inline int io_submit(aio_context_t ctx, long nr, struct iocb **iocbpp) { return syscall(__NR_io_submit, ctx, nr, iocbpp); } inline int io_getevents(aio_context_t ctx, long min_nr, long max_nr, struct io_event *events, struct timespec *timeout) { return syscall(__NR_io_getevents, ctx, min_nr, max_nr, events, timeout); } class KernelAIOWrite : public AsyncFileIOContext::AIOOperation { public: KernelAIOWrite(aio_context_t aio_ctx, int fd, size_t offset, size_t bytes, const void *buffer); virtual void launch(void); virtual bool check_completion(void); public: aio_context_t ctx; struct iocb cb; }; KernelAIOWrite::KernelAIOWrite(aio_context_t aio_ctx, int fd, size_t offset, size_t bytes, const void *buffer) { completed = false; ctx = aio_ctx; memset(&cb, 0, sizeof(cb)); cb.aio_data = (uint64_t)this; cb.aio_fildes = fd; cb.aio_lio_opcode = IOCB_CMD_PWRITE; cb.aio_buf = (uint64_t)buffer; cb.aio_offset = offset; cb.aio_nbytes = bytes; } void KernelAIOWrite::launch(void) { struct iocb *cbs[1]; cbs[0] = &cb; log_aio.debug("write issued: op=%p cb=%p", this, &cb); int ret = io_submit(ctx, 1, cbs); assert(ret == 1); } bool KernelAIOWrite::check_completion(void) { return completed; } class KernelAIORead : public AsyncFileIOContext::AIOOperation { public: KernelAIORead(aio_context_t aio_ctx, int fd, size_t offset, size_t bytes, void *buffer); virtual void launch(void); virtual bool check_completion(void); public: aio_context_t ctx; struct iocb cb; }; KernelAIORead::KernelAIORead(aio_context_t aio_ctx, int fd, size_t offset, size_t bytes, void *buffer) { completed = false; ctx = aio_ctx; memset(&cb, 0, sizeof(cb)); cb.aio_data = (uint64_t)this; cb.aio_fildes = fd; cb.aio_lio_opcode = IOCB_CMD_PREAD; cb.aio_buf = (uint64_t)buffer; cb.aio_offset = offset; cb.aio_nbytes = bytes; } void KernelAIORead::launch(void) { struct iocb *cbs[1]; cbs[0] = &cb; log_aio.debug("read issued: op=%p cb=%p", this, &cb); int ret = io_submit(ctx, 1, cbs); assert(ret == 1); } bool KernelAIORead::check_completion(void) { return completed; } #else class PosixAIOWrite : public AsyncFileIOContext::AIOOperation { public: PosixAIOWrite(int fd, size_t offset, size_t bytes, const void *buffer); virtual void launch(void); virtual bool check_completion(void); public: struct aiocb cb; }; PosixAIOWrite::PosixAIOWrite(int fd, size_t offset, size_t bytes, const void *buffer) { completed = false; memset(&cb, 0, sizeof(cb)); cb.aio_fildes = fd; cb.aio_buf = (void *)buffer; cb.aio_offset = offset; cb.aio_nbytes = bytes; } void PosixAIOWrite::launch(void) { log_aio.debug("write issued: op=%p cb=%p", this, &cb); #ifndef NDEBUG int ret = #endif aio_write(&cb); assert(ret == 0); } bool PosixAIOWrite::check_completion(void) { int ret = aio_error(&cb); if(ret == EINPROGRESS) return false; log_aio.debug("write returned: op=%p cb=%p ret=%d", this, &cb, ret); assert(ret == 0); return true; } class PosixAIORead : public AsyncFileIOContext::AIOOperation { public: PosixAIORead(int fd, size_t offset, size_t bytes, void *buffer); virtual void launch(void); virtual bool check_completion(void); public: struct aiocb cb; }; PosixAIORead::PosixAIORead(int fd, size_t offset, size_t bytes, void *buffer) { completed = false; memset(&cb, 0, sizeof(cb)); cb.aio_fildes = fd; cb.aio_buf = buffer; cb.aio_offset = offset; cb.aio_nbytes = bytes; } void PosixAIORead::launch(void) { log_aio.debug("read issued: op=%p cb=%p", this, &cb); #ifndef NDEBUG int ret = #endif aio_read(&cb); assert(ret == 0); } bool PosixAIORead::check_completion(void) { int ret = aio_error(&cb); if(ret == EINPROGRESS) return false; log_aio.debug("read returned: op=%p cb=%p ret=%d", this, &cb, ret); assert(ret == 0); return true; } #endif class AIOFence : public Realm::Operation::AsyncWorkItem { public: AIOFence(Realm::Operation *_op) : Realm::Operation::AsyncWorkItem(_op) {} virtual void request_cancellation(void) {} virtual void print(std::ostream& os) const { os << "AIOFence"; } }; class AIOFenceOp : public AsyncFileIOContext::AIOOperation { public: AIOFenceOp(DmaRequest *_req); virtual void launch(void); virtual bool check_completion(void); public: DmaRequest *req; AIOFence *f; }; AIOFenceOp::AIOFenceOp(DmaRequest *_req) { completed = false; req = _req; f = new AIOFence(req); req->add_async_work_item(f); } void AIOFenceOp::launch(void) { log_aio.debug("fence launched: op=%p req=%p", this, req); completed = true; } bool AIOFenceOp::check_completion(void) { assert(completed); log_aio.debug("fence completed: op=%p req=%p", this, req); f->mark_finished(true /*successful*/); return true; } AsyncFileIOContext::AsyncFileIOContext(int _max_depth) : max_depth(_max_depth) { #ifdef REALM_USE_KERNEL_AIO aio_ctx = 0; int ret = io_setup(max_depth, &aio_ctx); assert(ret == 0); #endif } AsyncFileIOContext::~AsyncFileIOContext(void) { assert(pending_operations.empty()); assert(launched_operations.empty()); #ifdef REALM_USE_KERNEL_AIO int ret = io_destroy(aio_ctx); assert(ret == 0); #endif } void AsyncFileIOContext::enqueue_write(int fd, size_t offset, size_t bytes, const void *buffer) { #ifdef REALM_USE_KERNEL_AIO KernelAIOWrite *op = new KernelAIOWrite(aio_ctx, fd, offset, bytes, buffer); #else PosixAIOWrite *op = new PosixAIOWrite(fd, offset, bytes, buffer); #endif { AutoHSLLock al(mutex); if(launched_operations.size() < (size_t)max_depth) { op->launch(); launched_operations.push_back(op); } else { pending_operations.push_back(op); } } } void AsyncFileIOContext::enqueue_read(int fd, size_t offset, size_t bytes, void *buffer) { #ifdef REALM_USE_KERNEL_AIO KernelAIORead *op = new KernelAIORead(aio_ctx, fd, offset, bytes, buffer); #else PosixAIORead *op = new PosixAIORead(fd, offset, bytes, buffer); #endif { AutoHSLLock al(mutex); if(launched_operations.size() < (size_t)max_depth) { op->launch(); launched_operations.push_back(op); } else { pending_operations.push_back(op); } } } void AsyncFileIOContext::enqueue_fence(DmaRequest *req) { AIOFenceOp *op = new AIOFenceOp(req); { AutoHSLLock al(mutex); if(launched_operations.size() < (size_t)max_depth) { op->launch(); launched_operations.push_back(op); } else { pending_operations.push_back(op); } } } bool AsyncFileIOContext::empty(void) { AutoHSLLock al(mutex); return launched_operations.empty(); } void AsyncFileIOContext::make_progress(void) { AutoHSLLock al(mutex); // first, reap as many events as we can - oldest first #ifdef REALM_USE_KERNEL_AIO while(true) { struct io_event events[8]; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 0; // no delay int ret = io_getevents(aio_ctx, 1, 8, events, &ts); if(ret == 0) break; log_aio.debug("io_getevents returned %d events", ret); for(int i = 0; i < ret; i++) { AIOOperation *op = (AIOOperation *)(events[i].data); log_aio.debug("io_getevents: event[%d] = %p", i, op); op->completed = true; } } #endif // now actually mark events completed in oldest-first order while(!launched_operations.empty()) { AIOOperation *op = launched_operations.front(); if(!op->check_completion()) break; log_aio.debug("aio op completed: op=%p", op); delete op; launched_operations.pop_front(); } // finally, if there are any pending ops, and room for them, launch them while((launched_operations.size() < (size_t)max_depth) && !pending_operations.empty()) { AIOOperation *op = pending_operations.front(); pending_operations.pop_front(); op->launch(); launched_operations.push_back(op); } } // MemPairCopier from disk memory to cpu memory class DisktoCPUMemPairCopier : public MemPairCopier { public: DisktoCPUMemPairCopier(int _fd, Memory _dst_mem) { MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); assert(dst_base); fd = _fd; } virtual ~DisktoCPUMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &osa_vec) { return new SpanBasedInstPairCopier<DisktoCPUMemPairCopier>(this, src_inst, dst_inst, osa_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { aio_context->enqueue_read(fd, src_offset, bytes, dst_base + dst_offset); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } void flush(DmaRequest *req) { aio_context->enqueue_fence(req); MemPairCopier::flush(req); } protected: char *dst_base; int fd; // file descriptor }; // MemPairCopier from disk memory to cpu memory class DiskfromCPUMemPairCopier : public MemPairCopier { public: DiskfromCPUMemPairCopier(Memory _src_mem, int _fd) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (char *)(src_impl->get_direct_ptr(0, src_impl->size)); assert(src_base); fd = _fd; } virtual ~DiskfromCPUMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &osa_vec) { return new SpanBasedInstPairCopier<DiskfromCPUMemPairCopier>(this, src_inst, dst_inst, osa_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { aio_context->enqueue_write(fd, dst_offset, bytes, src_base + src_offset); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } void flush(DmaRequest *req) { aio_context->enqueue_fence(req); MemPairCopier::flush(req); } protected: char *src_base; int fd; // file descriptor }; class FilefromCPUMemPairCopier : public MemPairCopier { public: class FileWriteCopier : public InstPairCopier { public: enum {max_nr = 1}; FileWriteCopier(int _fd, char* _base, RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec, FilefromCPUMemPairCopier *_mpc) { fd = _fd; inst_copier = new SpanBasedInstPairCopier<FileWriteCopier>(this, src_inst, dst_inst, oas_vec); src_base = _base; mpc = _mpc; } ~FileWriteCopier(void) { delete inst_copier; } virtual void copy_field(int src_index, int dst_index, int elem_count, unsigned offset_index) { inst_copier->copy_field(src_index, dst_index, elem_count, offset_index); } virtual void copy_all_fields(int src_index, int dst_index, int elem_count) { inst_copier->copy_all_fields(src_index, dst_index, elem_count); } virtual void copy_all_fields(int src_index, int dst_index, int count_per_line, int src_stride, int dst_stride, int lines) { inst_copier->copy_all_fields(src_index, dst_index, count_per_line, src_stride, dst_stride, lines); } virtual void flush(void) { inst_copier->flush(); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { aio_context->enqueue_write(fd, dst_offset, bytes, src_base + src_offset); mpc->record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: int fd; char *src_base; InstPairCopier* inst_copier; FilefromCPUMemPairCopier *mpc; }; FilefromCPUMemPairCopier(Memory _src_mem, Memory _dst_mem) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (char *)(src_impl->get_direct_ptr(0, src_impl->size)); dst_mem = (FileMemory*) get_runtime()->get_memory_impl(_dst_mem); } virtual ~FilefromCPUMemPairCopier(void) {} virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { ID id(dst_inst); unsigned index = id.index_l(); int fd = dst_mem->get_file_des(index); return new FileWriteCopier(fd, src_base, src_inst, dst_inst, oas_vec, this); } void flush(DmaRequest *req) { aio_context->enqueue_fence(req); MemPairCopier::flush(req); } protected: char *src_base; FileMemory *dst_mem; }; class FiletoCPUMemPairCopier : public MemPairCopier { public: class FileReadCopier : public InstPairCopier { public: enum {max_nr = 1}; FileReadCopier(int _fd, char* _base, RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec, FiletoCPUMemPairCopier *_mpc) { fd = _fd; inst_copier = new SpanBasedInstPairCopier<FileReadCopier>(this, src_inst, dst_inst, oas_vec); dst_base = _base; mpc = _mpc; } ~FileReadCopier(void) { delete inst_copier; } virtual void copy_field(int src_index, int dst_index, int elem_count, unsigned offset_index) { inst_copier->copy_field(src_index, dst_index, elem_count, offset_index); } virtual void copy_all_fields(int src_index, int dst_index, int elem_count) { inst_copier->copy_all_fields(src_index, dst_index, elem_count); } virtual void copy_all_fields(int src_index, int dst_index, int count_per_line, int src_stride, int dst_stride, int lines) { inst_copier->copy_all_fields(src_index, dst_index, count_per_line, src_stride, dst_stride, lines); } virtual void flush(void) { inst_copier->flush(); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { aio_context->enqueue_read(fd, src_offset, bytes, dst_base + dst_offset); mpc->record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { while(lines-- > 0) { copy_span(src_offset, dst_offset, bytes); src_offset += src_stride; dst_offset += dst_stride; } } protected: int fd; char *dst_base; InstPairCopier* inst_copier; FiletoCPUMemPairCopier *mpc; }; FiletoCPUMemPairCopier(Memory _src_mem, Memory _dst_mem) { MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); src_mem = (FileMemory*) get_runtime()->get_memory_impl(_src_mem); } virtual ~FiletoCPUMemPairCopier(void) {} virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { ID id(src_inst); unsigned index = id.index_l(); int fd = src_mem->get_file_des(index); return new FileReadCopier(fd, dst_base, src_inst, dst_inst, oas_vec, this); } void flush(DmaRequest *req) { aio_context->enqueue_fence(req); MemPairCopier::flush(req); } protected: char *dst_base; FileMemory *src_mem; }; // most of the smarts from MemPairCopier::create_copier are now captured in the various factories class MemcpyMemPairCopierFactory : public MemPairCopierFactory { public: MemcpyMemPairCopierFactory(void) : MemPairCopierFactory("memcpy") {} virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // non-reduction copies between anything SYSMEM and/or ZC // (TODO: really should be anything with a direct CPU pointer, but GPUFBMemory // returns non-null for that right now...) if(redop_id != 0) return false; MemoryImpl *src_impl = get_runtime()->get_memory_impl(src_mem); MemoryImpl::MemoryKind src_kind = src_impl->kind; if((src_kind != MemoryImpl::MKIND_SYSMEM) && (src_kind != MemoryImpl::MKIND_ZEROCOPY)) return false; MemoryImpl *dst_impl = get_runtime()->get_memory_impl(dst_mem); MemoryImpl::MemoryKind dst_kind = dst_impl->kind; if((dst_kind != MemoryImpl::MKIND_SYSMEM) && (dst_kind != MemoryImpl::MKIND_ZEROCOPY)) return false; return true; } virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { return new MemcpyMemPairCopier(src_mem, dst_mem); } }; void create_builtin_dma_channels(Realm::RuntimeImpl *r) { r->add_dma_channel(new MemcpyMemPairCopierFactory); } MemPairCopier *MemPairCopier::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id /*= 0*/, CustomSerdezID serdez_id /*= 0*/, bool fold /*= false*/) { // try to use new DMA channels first const std::vector<MemPairCopierFactory *>& channels = get_runtime()->get_dma_channels(); for(std::vector<MemPairCopierFactory *>::const_iterator it = channels.begin(); it != channels.end(); it++) { if((*it)->can_perform_copy(src_mem, dst_mem, redop_id, fold)) { // impls and kinds are just for logging now MemoryImpl *src_impl = get_runtime()->get_memory_impl(src_mem); MemoryImpl *dst_impl = get_runtime()->get_memory_impl(dst_mem); MemoryImpl::MemoryKind src_kind = src_impl->kind; MemoryImpl::MemoryKind dst_kind = dst_impl->kind; log_dma.info("copier: " IDFMT "(%d) -> " IDFMT "(%d) = %s", src_mem.id, src_kind, dst_mem.id, dst_kind, (*it)->get_name().c_str()); return (*it)->create_copier(src_mem, dst_mem, redop_id, fold); } } // old style - various options in here are being turned into assert(0)'s as they are // replaced by DMA channel-provided copiers MemoryImpl *src_impl = get_runtime()->get_memory_impl(src_mem); MemoryImpl *dst_impl = get_runtime()->get_memory_impl(dst_mem); MemoryImpl::MemoryKind src_kind = src_impl->kind; MemoryImpl::MemoryKind dst_kind = dst_impl->kind; log_dma.info("copier: " IDFMT "(%d) -> " IDFMT "(%d)", src_mem.id, src_kind, dst_mem.id, dst_kind); if(redop_id == 0) { if (serdez_id != 0) { // handle serdez cases, for now we only support remote serdez case if((dst_kind == MemoryImpl::MKIND_REMOTE) || (dst_kind == MemoryImpl::MKIND_RDMA)) { assert(src_kind != MemoryImpl::MKIND_REMOTE); return new RemoteSerdezMemPairCopier(src_mem, dst_mem, serdez_id); } log_dma.warning("Unsupported serdez transfer case (" IDFMT " -> " IDFMT ")", src_mem.id, dst_mem.id); assert(0); } // can we perform simple memcpy's? if(((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY)) && ((dst_kind == MemoryImpl::MKIND_SYSMEM) || (dst_kind == MemoryImpl::MKIND_ZEROCOPY))) { assert(0); //return new MemcpyMemPairCopier(src_mem, dst_mem); } // can we perform transfer between disk and cpu memory if (((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY)) && (dst_kind == MemoryImpl::MKIND_DISK)) { // printf("Create DiskfromCPUMemPairCopier\n"); int fd = ((DiskMemory *)dst_impl)->fd; return new DiskfromCPUMemPairCopier(src_mem, fd); } if ((src_kind == MemoryImpl::MKIND_DISK) && ((dst_kind == MemoryImpl::MKIND_SYSMEM) || (dst_kind == MemoryImpl::MKIND_ZEROCOPY))) { // printf("Create DisktoCPUMemPairCopier\n"); int fd = ((DiskMemory *)src_impl)->fd; return new DisktoCPUMemPairCopier(fd, dst_mem); } // can we perform transfer between cpu and file memory if (((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY)) && (dst_kind == MemoryImpl::MKIND_FILE)) { //printf("Create FilefromCPUMemPairCopier\n"); return new FilefromCPUMemPairCopier(src_mem, dst_mem); } if ((src_kind == MemoryImpl::MKIND_FILE) && ((dst_kind == MemoryImpl::MKIND_SYSMEM) || (dst_kind == MemoryImpl::MKIND_ZEROCOPY))) { //printf("Create FiletoCPUMemPairCopier\n"); return new FiletoCPUMemPairCopier(src_mem, dst_mem); } // GPU FB-related copies should be handled by module-provided dma channels now if((src_kind == MemoryImpl::MKIND_GPUFB) || (dst_kind == MemoryImpl::MKIND_GPUFB)) { assert(0); } // try as many things as we can think of if((dst_kind == MemoryImpl::MKIND_REMOTE) || (dst_kind == MemoryImpl::MKIND_RDMA)) { assert(src_kind != MemoryImpl::MKIND_REMOTE); return new RemoteWriteMemPairCopier(src_mem, dst_mem); } // fallback return new BufferedMemPairCopier(src_mem, dst_mem); } else { // reduction case // can we perform simple memcpy's? if(((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY)) && ((dst_kind == MemoryImpl::MKIND_SYSMEM) || (dst_kind == MemoryImpl::MKIND_ZEROCOPY))) { return new LocalReductionMemPairCopier(src_mem, dst_mem, redop_id, fold); } // reductions to a remote memory get shipped over there to be applied if((dst_kind == MemoryImpl::MKIND_REMOTE) || (dst_kind == MemoryImpl::MKIND_RDMA)) { assert(src_kind != MemoryImpl::MKIND_REMOTE); return new RemoteReduceMemPairCopier(src_mem, dst_mem, redop_id, fold); } // fallback is pretty damn slow log_dma.warning("using a buffering copier for reductions (" IDFMT " -> " IDFMT ")", src_mem.id, dst_mem.id); return new BufferedReductionMemPairCopier(src_mem, dst_mem, redop_id, fold); } } template <unsigned DIM> static unsigned compress_strides(const Rect<DIM> &r, const Point<1> in1[DIM], const Point<1> in2[DIM], Point<DIM>& extents, Point<1> out1[DIM], Point<1> out2[DIM]) { // sort the dimensions by the first set of strides for maximum gathering goodness unsigned stride_order[DIM]; for(unsigned i = 0; i < DIM; i++) stride_order[i] = i; // yay, bubble sort! for(unsigned i = 0; i < DIM; i++) for(unsigned j = 0; j < i; j++) if(in1[stride_order[j]] > in1[stride_order[j+1]]) { int t = stride_order[j]; stride_order[j] = stride_order[j+1]; stride_order[j+1] = t; } int curdim = -1; int exp1 = 0, exp2 = 0; // now go through dimensions, collapsing each if it matches the expected stride for // both sets (can't collapse for first) for(unsigned i = 0; i < DIM; i++) { unsigned d = stride_order[i]; unsigned e = r.dim_size(d); if(i && (exp1 == in1[d][0]) && (exp2 == in2[d][0])) { // collapse and grow extent extents.x[curdim] *= e; exp1 *= e; exp2 *= e; } else { // no match - create a new dimension curdim++; extents.x[curdim] = e; exp1 = in1[d][0] * e; exp2 = in2[d][0] * e; out1[curdim] = in1[d]; out2[curdim] = in2[d]; } } return curdim+1; } void CopyRequest::perform_dma_mask(MemPairCopier *mpc) { IndexSpaceImpl *ispace = get_runtime()->get_index_space_impl(domain.get_index_space()); assert(ispace->valid_mask_complete); // this is the SOA-friendly loop nesting for(OASByInst::iterator it = oas_by_inst->begin(); it != oas_by_inst->end(); it++) { RegionInstance src_inst = it->first.first; RegionInstance dst_inst = it->first.second; OASVec& oasvec = it->second; InstPairCopier *ipc = mpc->inst_pair(src_inst, dst_inst, oasvec); // index space instances use 1D linearizations for translation Arrays::Mapping<1, 1> *src_linearization = get_runtime()->get_instance_impl(src_inst)->metadata.linearization.get_mapping<1>(); Arrays::Mapping<1, 1> *dst_linearization = get_runtime()->get_instance_impl(dst_inst)->metadata.linearization.get_mapping<1>(); // does the destination instance space's index space match what we're copying? if so, // it's ok to copy extra elements (to decrease sparsity) because they're unused in // the destination assert(get_runtime()->get_instance_impl(dst_inst)->metadata.is_valid()); int rlen_target; if(ispace->me == get_runtime()->get_instance_impl(dst_inst)->metadata.is) { rlen_target = 32768 / 4; // aim for ~32KB transfers at least } else { rlen_target = 1; } ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, rlen; while(e->get_next(rstart, rlen)) { // do we want to copy extra elements to fill in some holes? while(rlen < rlen_target) { // see where the next valid elements are int rstart2, rlen2; // if none, stop if(!e->peek_next(rstart2, rlen2)) break; // or if they don't even start until outside the window, stop if(rstart2 > (rstart + rlen_target)) break; // ok, include the next valid element(s) and any invalid ones in between //printf("bloating from %d to %d\n", rlen, rstart2 + rlen2 - rstart); rlen = rstart2 + rlen2 - rstart; // and actually take the next range from the enumerator e->get_next(rstart2, rlen2); } int sstart = src_linearization->image(rstart); int dstart = dst_linearization->image(rstart); #ifdef DEBUG_LOW_LEVEL assert(src_linearization->image_is_dense(Rect<1>(rstart, rstart + rlen - 1))); assert(dst_linearization->image_is_dense(Rect<1>(rstart, rstart + rlen - 1))); #endif //printf("X: %d+%d %d %d\n", rstart, rlen, sstart, dstart); for (unsigned idx = 0; idx < oasvec.size(); idx++) ipc->copy_field(sstart, dstart, rlen, idx); } delete e; delete ipc; } } template <unsigned DIM> void CopyRequest::perform_dma_rect(MemPairCopier *mpc) { Arrays::Rect<DIM> orig_rect = domain.get_rect<DIM>(); // empty rectangles are easy to copy... if(orig_rect.volume() == 0) return; // this is the SOA-friendly loop nesting for(OASByInst::iterator it = oas_by_inst->begin(); it != oas_by_inst->end(); it++) { RegionInstance src_inst = it->first.first; RegionInstance dst_inst = it->first.second; OASVec& oasvec = it->second; InstPairCopier *ipc = mpc->inst_pair(src_inst, dst_inst, oasvec); RegionInstanceImpl *src_impl = get_runtime()->get_instance_impl(src_inst); RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst_inst); assert(src_impl->metadata.is_valid()); assert(dst_impl->metadata.is_valid()); Arrays::Mapping<DIM, 1> *src_linearization = src_impl->metadata.linearization.get_mapping<DIM>(); Arrays::Mapping<DIM, 1> *dst_linearization = dst_impl->metadata.linearization.get_mapping<DIM>(); // see what linear subrects we can get - again, iterate over destination first for gathering for(typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lso(orig_rect, *dst_linearization); lso; lso++) { for(typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lsi(lso.subrect, *src_linearization); lsi; lsi++) { // see if we can compress the strides for a more efficient copy Point<1> src_cstrides[DIM], dst_cstrides[DIM]; Point<DIM> extents; int cdim = compress_strides(lsi.subrect, lso.strides, lsi.strides, extents, dst_cstrides, src_cstrides); #ifdef NEW2D_DEBUG printf("ORIG: (%d,%d,%d)->(%d,%d,%d)\n", orig_rect.lo[0], orig_rect.lo[1], orig_rect.lo[2], orig_rect.hi[0], orig_rect.hi[1], orig_rect.hi[2]); printf("DST: (%d,%d,%d)->(%d,%d,%d) %d+(%d,%d,%d)\n", lso.subrect.lo[0], lso.subrect.lo[1], lso.subrect.lo[2], lso.subrect.hi[0], lso.subrect.hi[1], lso.subrect.hi[2], lso.image_lo[0], lso.strides[0][0], lso.strides[1][0], lso.strides[2][0]); printf("SRC: (%d,%d,%d)->(%d,%d,%d) %d+(%d,%d,%d)\n", lsi.subrect.lo[0], lsi.subrect.lo[1], lsi.subrect.lo[2], lsi.subrect.hi[0], lsi.subrect.hi[1], lsi.subrect.hi[2], lsi.image_lo[0], lsi.strides[0][0], lsi.strides[1][0], lsi.strides[2][0]); printf("CMP: %d (%d,%d,%d) +(%d,%d,%d) +(%d,%d,%d)\n", cdim, extents[0], extents[1], extents[2], dst_cstrides[0][0], dst_cstrides[1][0], dst_cstrides[2][0], src_cstrides[0][0], src_cstrides[1][0], src_cstrides[2][0]); #endif if((cdim == 1) && (dst_cstrides[0][0] == 1) && (src_cstrides[0][0] == 1)) { // all the dimension(s) collapse to a 1-D extent in both source and dest, so one big copy ipc->copy_all_fields(lsi.image_lo[0], lso.image_lo[0], extents[0]); continue; } if((cdim == 2) && (dst_cstrides[0][0] == 1) && (src_cstrides[0][0] == 1)) { // source and/or destination need a 2-D description ipc->copy_all_fields(lsi.image_lo[0], lso.image_lo[0], extents[0], src_cstrides[1][0], dst_cstrides[1][0], extents[1]); continue; } // fall through - just identify dense (sub)subrects and copy them // iterate by output rectangle first - this gives us a chance to gather data when linearizations // don't match up for(Arrays::GenericDenseSubrectIterator<Arrays::Mapping<DIM, 1> > dso(lsi.subrect, *dst_linearization); dso; dso++) { // dense subrect in dst might not be dense in src for(Arrays::GenericDenseSubrectIterator<Arrays::Mapping<DIM, 1> > dsi(dso.subrect, *src_linearization); dsi; dsi++) { Rect<1> irect = dsi.image; // rectangle in output must be recalculated Rect<DIM> subrect_check; Rect<1> orect = dst_linearization->image_dense_subrect(dsi.subrect, subrect_check); assert(dsi.subrect == subrect_check); //for(OASVec::iterator it2 = oasvec.begin(); it2 != oasvec.end(); it2++) for (unsigned idx = 0; idx < oasvec.size(); idx++) ipc->copy_field(irect.lo, orect.lo, irect.hi[0] - irect.lo[0] + 1, idx); //it2->src_offset, it2->dst_offset, it2->size); } } } } // Dammit Sean stop leaking things! delete ipc; } } void CopyRequest::perform_dma(void) { log_dma.info("request %p executing", this); DetailedTimer::ScopedPush sp(TIME_COPY); // create a copier for the memory used by all of these instance pairs Memory src_mem = get_runtime()->get_instance_impl(oas_by_inst->begin()->first.first)->memory; Memory dst_mem = get_runtime()->get_instance_impl(oas_by_inst->begin()->first.second)->memory; CustomSerdezID serdez_id = oas_by_inst->begin()->second.begin()->serdez_id; // for now we launches an individual copy request for every serdez copy assert(serdez_id == 0 || (oas_by_inst->size() == 1 && oas_by_inst->begin()->second.size() == 1)); MemPairCopier *mpc = MemPairCopier::create_copier(src_mem, dst_mem, 0, serdez_id); log_dma.info("mpc created"); switch(domain.get_dim()) { case 0: { // iterate over valid ranges of an index space perform_dma_mask(mpc); break; } // rectangle cases case 1: perform_dma_rect<1>(mpc); break; case 2: perform_dma_rect<2>(mpc); break; case 3: perform_dma_rect<3>(mpc); break; default: assert(0); }; log_dma.info("dma request %p finished - " IDFMT "[%zd]->" IDFMT "[%zd]:%d (+%zd) (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, oas_by_inst->begin()->first.first.id, oas_by_inst->begin()->second[0].src_offset, oas_by_inst->begin()->first.second.id, oas_by_inst->begin()->second[0].dst_offset, oas_by_inst->begin()->second[0].size, oas_by_inst->begin()->second.size() - 1, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); mpc->flush(this); if(measurements.wants_measurement<Realm::ProfilingMeasurements::OperationMemoryUsage>()) { const InstPair &pair = oas_by_inst->begin()->first; Realm::ProfilingMeasurements::OperationMemoryUsage usage; usage.source = pair.first.get_location(); usage.target = pair.second.get_location(); usage.size = mpc->get_total_bytes(); measurements.add_measurement(usage); } // if(after_copy.exists()) // after_copy.impl()->trigger(after_copy.gen, gasnet_mynode()); delete mpc; #ifdef EVEN_MORE_DEAD_DMA_CODE RegionInstanceImpl *src_impl = src.impl(); RegionInstanceImpl *tgt_impl = target.impl(); // we should have already arranged to have access to this data, so // assert if we don't StaticAccess<RegionInstanceImpl> src_data(src_impl, true); StaticAccess<RegionInstanceImpl> tgt_data(tgt_impl, true); // code path for copies to/from reduction-only instances not done yet // are we doing a reduction? const ReductionOpUntyped *redop = ((src_data->redopid >= 0) ? get_runtime()->reduce_op_table[src_data->redopid] : 0); bool red_fold = (tgt_data->redopid >= 0); // if destination is a reduction, source must be also and must match assert(tgt_data->redopid == src_data->redopid); // for now, a reduction list instance can only be copied back to a // non-reduction instance bool red_list = (src_data->redopid >= 0) && (src_data->red_list_size >= 0); if(red_list) assert(tgt_data->redopid < 0); MemoryImpl *src_mem = src_impl->memory.impl(); MemoryImpl *tgt_mem = tgt_impl->memory.impl(); // get valid masks from region to limit copy to correct data IndexSpaceImpl *is_impl = is.impl(); //RegionMetaDataUntyped::Impl *src_reg = src_data->region.impl(); //RegionMetaDataUntyped::Impl *tgt_reg = tgt_data->region.impl(); log_dma.info("copy: " IDFMT "->" IDFMT " (" IDFMT "/%p)", src.id, target.id, is.id, is_impl->valid_mask); // if we're missing the valid mask at this point, we've screwed up if(!is_impl->valid_mask_complete) { assert(is_impl->valid_mask_complete); } log_dma.debug("performing copy " IDFMT " (%d) -> " IDFMT " (%d) - %zd bytes (%zd)", src.id, src_mem->kind, target.id, tgt_mem->kind, bytes_to_copy, elmt_size); switch(src_mem->kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { const void *src_ptr = src_mem->get_direct_ptr(src_data->alloc_offset, bytes_to_copy); assert(src_ptr != 0); switch(tgt_mem->kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { void *tgt_ptr = tgt_mem->get_direct_ptr(tgt_data->alloc_offset, bytes_to_copy); assert(tgt_ptr != 0); assert(!redop); RangeExecutors::Memcpy rexec(tgt_ptr, src_ptr, elmt_size); ElementMask::forall_ranges(rexec, *is_impl->valid_mask); } break; case MemoryImpl::MKIND_GLOBAL: { if(redop) { if(red_list) { RangeExecutors::GasnetPutRedList rexec(tgt_mem, tgt_data->alloc_offset, src_data->redopid, redop, src_ptr, redop->sizeof_list_entry); size_t count; src_mem->get_bytes(src_data->count_offset, &count, sizeof(size_t)); if(count > 0) { rexec.do_span(0, count); count = 0; src_mem->put_bytes(src_data->count_offset, &count, sizeof(size_t)); } } else { RangeExecutors::GasnetPutReduce rexec(tgt_mem, tgt_data->alloc_offset, redop, red_fold, src_ptr, elmt_size); ElementMask::forall_ranges(rexec, *is_impl->valid_mask); } } else { #define USE_BATCHED_GASNET_XFERS #ifdef USE_BATCHED_GASNET_XFERS RangeExecutors::GasnetPutBatched rexec(tgt_mem, tgt_data->alloc_offset, src_ptr, elmt_size); #else RangeExecutors::GasnetPut rexec(tgt_mem, tgt_data->alloc_offset, src_ptr, elmt_size); #endif ElementMask::forall_ranges(rexec, *is_impl->valid_mask); #ifdef USE_BATCHED_GASNET_XFERS rexec.finish(); #endif } } break; case MemoryImpl::MKIND_GPUFB: { // all GPU operations are deferred, so we need an event if // we don't already have one created assert(!redop); if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)tgt_mem)->gpu->copy_to_fb(tgt_data->alloc_offset, src_ptr, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; case MemoryImpl::MKIND_REMOTE: { // use active messages to push data to other node RangeExecutors::RemoteWrite rexec(tgt_impl->memory, tgt_data->alloc_offset, src_ptr, elmt_size, after_copy); ElementMask::forall_ranges(rexec, *is_impl->valid_mask); // if no copies actually occur, we'll get the event back // from the range executor and we have to trigger it ourselves Event finish_event = rexec.finish(); if(finish_event.exists()) { log_dma.info("triggering event " IDFMT "/%d after empty remote copy", finish_event.id, finish_event.gen); assert(finish_event == after_copy); get_runtime()->get_singleevent_impl(finish_event)->trigger(finish_event.gen, gasnet_mynode()); } return; } default: assert(0); } } break; case MemoryImpl::MKIND_GLOBAL: { switch(tgt_mem->kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { void *tgt_ptr = tgt_mem->get_direct_ptr(tgt_data->alloc_offset, bytes_to_copy); assert(tgt_ptr != 0); assert(!redop); #ifdef USE_BATCHED_GASNET_XFERS RangeExecutors::GasnetGetBatched rexec(tgt_ptr, src_mem, src_data->alloc_offset, elmt_size); #else RangeExecutors::GasnetGet rexec(tgt_ptr, src_mem, src_data->alloc_offset, elmt_size); #endif ElementMask::forall_ranges(rexec, *is_impl->valid_mask); #ifdef USE_BATCHED_GASNET_XFERS rexec.finish(); #endif } break; case MemoryImpl::MKIND_GLOBAL: { assert(!redop); RangeExecutors::GasnetGetAndPut rexec(tgt_mem, tgt_data->alloc_offset, src_mem, src_data->alloc_offset, elmt_size); ElementMask::forall_ranges(rexec, *is_impl->valid_mask); } break; case MemoryImpl::MKIND_GPUFB: { assert(!redop); // all GPU operations are deferred, so we need an event if // we don't already have one created if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)tgt_mem)->gpu->copy_to_fb_generic(tgt_data->alloc_offset, src_mem, src_data->alloc_offset, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; default: assert(0); } } break; case MemoryImpl::MKIND_GPUFB: { switch(tgt_mem->kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { void *tgt_ptr = tgt_mem->get_direct_ptr(tgt_data->alloc_offset, bytes_to_copy); assert(tgt_ptr != 0); assert(!redop); // all GPU operations are deferred, so we need an event if // we don't already have one created if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)src_mem)->gpu->copy_from_fb(tgt_ptr, src_data->alloc_offset, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; case MemoryImpl::MKIND_GLOBAL: { assert(!redop); // all GPU operations are deferred, so we need an event if // we don't already have one created if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)src_mem)->gpu->copy_from_fb_generic(tgt_mem, tgt_data->alloc_offset, src_data->alloc_offset, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; case MemoryImpl::MKIND_GPUFB: { // only support copies within the same FB for now assert(src_mem == tgt_mem); assert(!redop); // all GPU operations are deferred, so we need an event if // we don't already have one created if(!after_copy.exists()) after_copy = Event::Impl::create_event(); ((GPUFBMemory *)src_mem)->gpu->copy_within_fb(tgt_data->alloc_offset, src_data->alloc_offset, is_impl->valid_mask, elmt_size, Event::NO_EVENT, after_copy); return; } break; default: assert(0); } } break; default: assert(0); } log_dma.debug("finished copy " IDFMT " (%d) -> " IDFMT " (%d) - %zd bytes (%zd), event=" IDFMT "/%d", src.id, src_mem->kind, target.id, tgt_mem->kind, bytes_to_copy, elmt_size, after_copy.id, after_copy.gen); #endif } ReduceRequest::ReduceRequest(const void *data, size_t datalen, ReductionOpID _redop_id, bool _red_fold, Event _before_copy, Event _after_copy, int _priority) : DmaRequest(_priority, _after_copy), inst_lock_event(Event::NO_EVENT), redop_id(_redop_id), red_fold(_red_fold), before_copy(_before_copy) { const IDType *idata = (const IDType *)data; idata = domain.deserialize(idata); priority = 0; // get sources int n_srcs = *idata++; for(int i = 0; i < n_srcs; i++) { Domain::CopySrcDstField f; f.inst.id = *idata++; f.offset = *idata++; f.size = *idata++; srcs.push_back(f); } // single dst field dst.inst.id = *idata++; dst.offset = *idata++; dst.size = *idata++; inst_lock_needed = *idata++; // Unpack any requests that we have // TODO: unbreak once the serialization stuff is repaired //const void *result = requests.deserialize(idata); //Realm::Operation::reconstruct_measurements(); // better have consumed exactly the right amount of data //assert((((unsigned long long)result) - ((unsigned long long)data)) == datalen); size_t request_size = *reinterpret_cast<const size_t*>(idata); idata += sizeof(size_t) / sizeof(IDType); FixedBufferDeserializer deserializer(idata, request_size); deserializer >> requests; Realm::Operation::reconstruct_measurements(); log_dma.info("dma request %p deserialized - " IDFMT "[%d]->" IDFMT "[%d]:%d (+%zd) %s %d (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, srcs[0].inst.id, srcs[0].offset, dst.inst.id, dst.offset, dst.size, srcs.size() - 1, (red_fold ? "fold" : "apply"), redop_id, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); } ReduceRequest::ReduceRequest(const Domain& _domain, const std::vector<Domain::CopySrcDstField>& _srcs, const Domain::CopySrcDstField& _dst, bool _inst_lock_needed, ReductionOpID _redop_id, bool _red_fold, Event _before_copy, Event _after_copy, int _priority, const Realm::ProfilingRequestSet &reqs) : DmaRequest(_priority, _after_copy, reqs), domain(_domain), dst(_dst), inst_lock_needed(_inst_lock_needed), inst_lock_event(Event::NO_EVENT), redop_id(_redop_id), red_fold(_red_fold), before_copy(_before_copy) { srcs.insert(srcs.end(), _srcs.begin(), _srcs.end()); log_dma.info("dma request %p created - " IDFMT "[%d]->" IDFMT "[%d]:%d (+%zd) %s %d (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, srcs[0].inst.id, srcs[0].offset, dst.inst.id, dst.offset, dst.size, srcs.size() - 1, (red_fold ? "fold" : "apply"), redop_id, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); } ReduceRequest::~ReduceRequest(void) { } size_t ReduceRequest::compute_size(void) { size_t result = domain.compute_size(); result += (4 + 3 * srcs.size()) * sizeof(IDType); result += sizeof(IDType); // for inst_lock_needed // TODO: unbreak once the serialization stuff is repaired //result += requests.compute_size(); ByteCountSerializer counter; counter << requests; result += sizeof(size_t) + counter.bytes_used(); return result; } void ReduceRequest::serialize(void *buffer) { // domain info goes first IDType *msgptr = domain.serialize((IDType *)buffer); // now source fields *msgptr++ = srcs.size(); for(std::vector<Domain::CopySrcDstField>::const_iterator it = srcs.begin(); it != srcs.end(); it++) { *msgptr++ = it->inst.id; *msgptr++ = it->offset; *msgptr++ = it->size; } // and the dest field *msgptr++ = dst.inst.id; *msgptr++ = dst.offset; *msgptr++ = dst.size; *msgptr++ = inst_lock_needed; // TODO: unbreak once the serialization stuff is repaired //requests.serialize(msgptr); // We sent this request remotely so we need to clear it's profiling ByteCountSerializer counter; counter << requests; *reinterpret_cast<size_t*>(msgptr) = counter.bytes_used(); msgptr += sizeof(size_t) / sizeof(IDType); FixedBufferSerializer serializer(msgptr, counter.bytes_used()); serializer << requests; clear_profiling(); } bool ReduceRequest::check_readiness(bool just_check, DmaRequestQueue *rq) { if(state == STATE_INIT) state = STATE_METADATA_FETCH; // remember which queue we're going to be assigned to if we sleep waiter.req = this; waiter.queue = rq; // make sure our node has all the meta data it needs, but don't take more than one lock // at a time if(state == STATE_METADATA_FETCH) { // index space first if(domain.get_dim() == 0) { IndexSpaceImpl *is_impl = get_runtime()->get_index_space_impl(domain.get_index_space()); if(!is_impl->locked_data.valid) { log_dma.info("dma request %p - no index space metadata yet", this); if(just_check) return false; Event e = is_impl->lock.acquire(1, false); if(e.has_triggered()) { log_dma.info("request %p - index space metadata invalid - instant trigger", this); is_impl->lock.release(); } else { log_dma.info("request %p - index space metadata invalid - sleeping on lock " IDFMT "", this, is_impl->lock.me.id); waiter.sleep_on_event(e, is_impl->lock.me); return false; } } // we need more than just the metadata - we also need the valid mask { Event e = is_impl->request_valid_mask(); if(!e.has_triggered()) { log_dma.info("request %p - valid mask needed for index space " IDFMT " - sleeping on event " IDFMT "/%d", this, domain.get_index_space().id, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // now go through all source instance pairs for(std::vector<Domain::CopySrcDstField>::iterator it = srcs.begin(); it != srcs.end(); it++) { RegionInstanceImpl *src_impl = get_runtime()->get_instance_impl(it->inst); { Event e = src_impl->request_metadata(); if(!e.has_triggered()) { if(just_check) { log_dma.info("dma request %p - no src instance (" IDFMT ") metadata yet", this, src_impl->me.id); return false; } log_dma.info("request %p - src instance metadata invalid - sleeping on event " IDFMT "/%d", this, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } { RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst.inst); { Event e = dst_impl->request_metadata(); if(!e.has_triggered()) { if(just_check) { log_dma.info("dma request %p - no dst instance (" IDFMT ") metadata yet", this, dst_impl->me.id); return false; } log_dma.info("request %p - dst instance metadata invalid - sleeping on event " IDFMT "/%d", this, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // if we got all the way through, we've got all the metadata we need state = STATE_BEFORE_EVENT; } // make sure our functional precondition has occurred if(state == STATE_BEFORE_EVENT) { // has the before event triggered? if not, wait on it if(before_copy.has_triggered()) { log_dma.info("request %p - before event triggered", this); if(inst_lock_needed) { // request an exclusive lock on the instance to protect reductions inst_lock_event = get_runtime()->get_instance_impl(dst.inst)->lock.acquire(0, true /*excl*/); state = STATE_INST_LOCK; log_dma.info("request %p - instance lock acquire event " IDFMT "/%d", this, inst_lock_event.id, inst_lock_event.gen); } else { // go straight to ready state = STATE_READY; } } else { log_dma.info("request %p - before event not triggered", this); if(just_check) return false; log_dma.info("request %p - sleeping on before event", this); waiter.sleep_on_event(before_copy); return false; } } if(state == STATE_INST_LOCK) { if(inst_lock_event.has_triggered()) { log_dma.info("request %p - instance lock acquired", this); state = STATE_READY; } else { log_dma.info("request %p - instance lock - sleeping on event " IDFMT "/%d", this, inst_lock_event.id, inst_lock_event.gen); waiter.sleep_on_event(inst_lock_event); return false; } } if(state == STATE_READY) { log_dma.info("request %p ready", this); if(just_check) return true; state = STATE_QUEUED; assert(rq != 0); log_dma.info("request %p enqueued", this); // once we're enqueued, we may be deleted at any time, so no more // references rq->enqueue_request(this); return true; } if(state == STATE_QUEUED) return true; assert(0); } template <unsigned DIM> void ReduceRequest::perform_dma_rect(MemPairCopier *mpc) { Arrays::Rect<DIM> orig_rect = domain.get_rect<DIM>(); // empty rectangles are easy to copy... if(orig_rect.volume() == 0) return; const ReductionOpUntyped *redop = get_runtime()->reduce_op_table[redop_id]; // single source field for now assert(srcs.size() == 1); // manufacture an OASVec for the copier OASVec oasvec(1); oasvec[0].src_offset = srcs[0].offset; oasvec[0].dst_offset = dst.offset; oasvec[0].size = redop->sizeof_rhs; RegionInstance src_inst = srcs[0].inst; RegionInstance dst_inst = dst.inst; InstPairCopier *ipc = mpc->inst_pair(src_inst, dst_inst, oasvec); RegionInstanceImpl *src_impl = get_runtime()->get_instance_impl(src_inst); RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst_inst); assert(src_impl->metadata.is_valid()); assert(dst_impl->metadata.is_valid()); Arrays::Mapping<DIM, 1> *src_linearization = src_impl->metadata.linearization.get_mapping<DIM>(); Arrays::Mapping<DIM, 1> *dst_linearization = dst_impl->metadata.linearization.get_mapping<DIM>(); // see what linear subrects we can get - again, iterate over destination first for gathering for(typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lso(orig_rect, *dst_linearization); lso; lso++) { for(typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lsi(lso.subrect, *src_linearization); lsi; lsi++) { // see if we can compress the strides for a more efficient copy Point<1> src_cstrides[DIM], dst_cstrides[DIM]; Point<DIM> extents; int cdim = compress_strides(lsi.subrect, lso.strides, lsi.strides, extents, dst_cstrides, src_cstrides); #ifdef NEW2D_DEBUG printf("ORIG: (%d,%d,%d)->(%d,%d,%d)\n", orig_rect.lo[0], orig_rect.lo[1], orig_rect.lo[2], orig_rect.hi[0], orig_rect.hi[1], orig_rect.hi[2]); printf("DST: (%d,%d,%d)->(%d,%d,%d) %d+(%d,%d,%d)\n", lso.subrect.lo[0], lso.subrect.lo[1], lso.subrect.lo[2], lso.subrect.hi[0], lso.subrect.hi[1], lso.subrect.hi[2], lso.image_lo[0], lso.strides[0][0], lso.strides[1][0], lso.strides[2][0]); printf("SRC: (%d,%d,%d)->(%d,%d,%d) %d+(%d,%d,%d)\n", lsi.subrect.lo[0], lsi.subrect.lo[1], lsi.subrect.lo[2], lsi.subrect.hi[0], lsi.subrect.hi[1], lsi.subrect.hi[2], lsi.image_lo[0], lsi.strides[0][0], lsi.strides[1][0], lsi.strides[2][0]); printf("CMP: %d (%d,%d,%d) +(%d,%d,%d) +(%d,%d,%d)\n", cdim, extents[0], extents[1], extents[2], dst_cstrides[0][0], dst_cstrides[1][0], dst_cstrides[2][0], src_cstrides[0][0], src_cstrides[1][0], src_cstrides[2][0]); #endif if((cdim == 1) && (dst_cstrides[0][0] == 1) && (src_cstrides[0][0] == 1)) { // all the dimension(s) collapse to a 1-D extent in both source and dest, so one big copy ipc->copy_all_fields(lsi.image_lo[0], lso.image_lo[0], extents[0]); continue; } if((cdim == 2) && (dst_cstrides[0][0] == 1) && (src_cstrides[0][0] == 1)) { // source and/or destination need a 2-D description ipc->copy_all_fields(lsi.image_lo[0], lso.image_lo[0], extents[0], src_cstrides[1][0], dst_cstrides[1][0], extents[1]); continue; } // fall through - just identify dense (sub)subrects and copy them // iterate by output rectangle first - this gives us a chance to gather data when linearizations // don't match up for(Arrays::GenericDenseSubrectIterator<Arrays::Mapping<DIM, 1> > dso(lsi.subrect, *dst_linearization); dso; dso++) { // dense subrect in dst might not be dense in src for(Arrays::GenericDenseSubrectIterator<Arrays::Mapping<DIM, 1> > dsi(dso.subrect, *src_linearization); dsi; dsi++) { Rect<1> irect = dsi.image; // rectangle in output must be recalculated Rect<DIM> subrect_check; Rect<1> orect = dst_linearization->image_dense_subrect(dsi.subrect, subrect_check); assert(dsi.subrect == subrect_check); //for(OASVec::iterator it2 = oasvec.begin(); it2 != oasvec.end(); it2++) for (unsigned idx = 0; idx < oasvec.size(); idx++) ipc->copy_field(irect.lo, orect.lo, irect.hi[0] - irect.lo[0] + 1, idx); //it2->src_offset, it2->dst_offset, it2->size); } } } } delete ipc; } void ReduceRequest::perform_dma(void) { log_dma.info("request %p executing", this); DetailedTimer::ScopedPush sp(TIME_COPY); // code assumes a single source field for now assert(srcs.size() == 1); Memory src_mem = get_runtime()->get_instance_impl(srcs[0].inst)->memory; Memory dst_mem = get_runtime()->get_instance_impl(dst.inst)->memory; MemoryImpl::MemoryKind src_kind = get_runtime()->get_memory_impl(src_mem)->kind; MemoryImpl::MemoryKind dst_kind = get_runtime()->get_memory_impl(dst_mem)->kind; const ReductionOpUntyped *redop = get_runtime()->reduce_op_table[redop_id]; //printf("kinds: " IDFMT "=%d " IDFMT "=%d\n", src_mem.id, src_mem.impl()->kind, dst_mem.id, dst_mem.impl()->kind); // we have the same jumble of memory type and layout permutations here - again we'll // solve a few of them point-wise and then try to unify later size_t total_bytes = 0; if(domain.get_dim() == 0) { // index space IndexSpaceImpl *ispace = get_runtime()->get_index_space_impl(domain.get_index_space()); assert(ispace->valid_mask_complete); if((src_kind == MemoryImpl::MKIND_SYSMEM) || (src_kind == MemoryImpl::MKIND_ZEROCOPY) || (src_kind == MemoryImpl::MKIND_RDMA)) { void *src_base = 0; size_t src_stride = 0; #ifndef NDEBUG bool src_ok = #endif get_runtime()->get_instance_impl(srcs[0].inst)->get_strided_parameters(src_base, src_stride, srcs[0].offset); assert(src_ok); switch(dst_kind) { case MemoryImpl::MKIND_SYSMEM: case MemoryImpl::MKIND_ZEROCOPY: { void *dst_base = 0; size_t dst_stride = 0; #ifndef NDEBUG bool dst_ok = #endif get_runtime()->get_instance_impl(dst.inst)->get_strided_parameters(dst_base, dst_stride, dst.offset); assert(dst_ok); // if source and dest are ok, we can just walk the index space's spans ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, rlen; while(e->get_next(rstart, rlen)) { if(red_fold) redop->fold_strided(((char *)dst_base) + (rstart * dst_stride), ((const char *)src_base) + (rstart * src_stride), dst_stride, src_stride, rlen, false /*not exclusive*/); else redop->apply_strided(((char *)dst_base) + (rstart * dst_stride), ((const char *)src_base) + (rstart * src_stride), dst_stride, src_stride, rlen, false /*not exclusive*/); } delete e; break; } case MemoryImpl::MKIND_REMOTE: case MemoryImpl::MKIND_RDMA: { // we need to figure out how to calculate offsets in the destination memory RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst.inst); assert(dst_impl->metadata.is_valid()); off_t dst_field_start=0; int dst_field_size=0; find_field_start(dst_impl->metadata.field_sizes, dst.offset, dst.size, dst_field_start, dst_field_size); assert(dst.size == (size_t)dst_field_size); // index space instances use 1D linearizations for translation Arrays::Mapping<1, 1> *dst_linearization = dst_impl->metadata.linearization.get_mapping<1>(); ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, rlen; // get an RDMA sequence number so we can have the far side trigger the event once all reductions have been // applied unsigned sequence_id = __sync_fetch_and_add(&rdma_sequence_no, 1); unsigned rdma_count = 0; // for a reduction from a fold instance, it's always ok to copy unused elements, since they'll have an // identity value stored for them int rlen_target = 32768 / dst_field_size; while(e->get_next(rstart, rlen)) { // do we want to copy extra elements to fill in some holes? while(rlen < rlen_target) { // see where the next valid elements are int rstart2, rlen2; // if none, stop if(!e->peek_next(rstart2, rlen2)) break; // or if they don't even start until outside the window, stop if(rstart2 > (rstart + rlen_target)) break; // ok, include the next valid element(s) and any invalid ones in between //printf("bloating from %d to %d\n", rlen, rstart2 + rlen2 - rstart); rlen = rstart2 + rlen2 - rstart; // and actually take the next range from the enumerator e->get_next(rstart2, rlen2); } // translate the index space point to the dst instance's linearization int dstart = dst_linearization->image(rstart); // now do an offset calculation for the destination off_t dst_offset; off_t dst_stride; if(dst_impl->metadata.block_size > 1) { // straddling a block boundary is complicated assert((dstart / dst_impl->metadata.block_size) == ((dstart + rlen - 1) / dst_impl->metadata.block_size)); dst_offset = calc_mem_loc(dst_impl->metadata.alloc_offset, dst_field_start, dst_field_size, dst_impl->metadata.elmt_size, dst_impl->metadata.block_size, dstart); dst_stride = dst_field_size; } else { // easy case dst_offset = dst_impl->metadata.alloc_offset + (dstart * dst_impl->metadata.elmt_size) + dst_field_start; dst_stride = dst_impl->metadata.elmt_size; } rdma_count += do_remote_reduce(dst_mem, dst_offset, redop_id, red_fold, ((const char *)src_base) + (rstart * src_stride), rlen, src_stride, dst_stride, sequence_id); } // if we did any actual reductions, send a fence, otherwise trigger here if(rdma_count > 0) { Realm::RemoteWriteFence *fence = new Realm::RemoteWriteFence(this); this->add_async_work_item(fence); do_remote_fence(dst_mem, sequence_id, rdma_count, fence); } delete e; break; } case MemoryImpl::MKIND_GLOBAL: { // make sure we've requested a lock on the dst instance assert(inst_lock_needed); // we need to figure out how to calculate offsets in the destination memory RegionInstanceImpl *dst_impl = get_runtime()->get_instance_impl(dst.inst); assert(dst_impl->metadata.is_valid()); off_t dst_field_start=0; int dst_field_size=0; find_field_start(dst_impl->metadata.field_sizes, dst.offset, dst.size, dst_field_start, dst_field_size); assert(dst.size == (size_t)dst_field_size); // index space instances use 1D linearizations for translation Arrays::Mapping<1, 1> *dst_linearization = dst_impl->metadata.linearization.get_mapping<1>(); // if source and dest are ok, we can just walk the index space's spans ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, rlen; while(e->get_next(rstart, rlen)) { // translate the index space point to the dst instance's linearization int dstart = dst_linearization->image(rstart); // now do an offset calculation for the destination off_t dst_offset; off_t dst_stride; if(dst_impl->metadata.block_size > 1) { // straddling a block boundary is complicated assert((dstart / dst_impl->metadata.block_size) == ((dstart + rlen - 1) / dst_impl->metadata.block_size)); dst_offset = calc_mem_loc(dst_impl->metadata.alloc_offset, dst_field_start, dst_field_size, dst_impl->metadata.elmt_size, dst_impl->metadata.block_size, dstart); dst_stride = dst_field_size; } else { // easy case dst_offset = dst_impl->metadata.alloc_offset + (dstart * dst_impl->metadata.elmt_size) + dst_field_start; dst_stride = dst_impl->metadata.elmt_size; } // get a temporary buffer in local memory // this may have extra data if stride > field_size, but that's // ok - we'll write back whatever we read void *buffer = malloc(dst_stride * rlen); get_runtime()->get_memory_impl(dst_mem)->get_bytes(dst_offset, buffer, dst_stride * rlen); if(red_fold) redop->fold_strided(buffer, ((const char *)src_base) + (rstart * src_stride), dst_stride, src_stride, rlen, true /*exclusive*/); else redop->apply_strided(buffer, ((const char *)src_base) + (rstart * src_stride), dst_stride, src_stride, rlen, true /*exclusive*/); get_runtime()->get_memory_impl(dst_mem)->put_bytes(dst_offset, buffer, dst_stride * rlen); // release the temp buffer free(buffer); } // also release the instance lock dst_impl->lock.release(); delete e; break; } default: assert(0); } } // TODO: we don't track the size of reduction on unstructred index spaces total_bytes = 0; } else { MemPairCopier *mpc = MemPairCopier::create_copier(src_mem, dst_mem, redop_id, red_fold); switch(domain.get_dim()) { case 1: perform_dma_rect<1>(mpc); break; case 2: perform_dma_rect<2>(mpc); break; case 3: perform_dma_rect<3>(mpc); break; default: assert(0); } mpc->flush(this); total_bytes = mpc->get_total_bytes(); // if an instance lock was taken, release it after copy completes if(inst_lock_needed) get_runtime()->get_instance_impl(dst.inst)->lock.me.release(get_finish_event()); delete mpc; } log_dma.info("dma request %p finished - " IDFMT "[%d]->" IDFMT "[%d]:%d (+%zd) %s %d (" IDFMT ") " IDFMT "/%d " IDFMT "/%d", this, srcs[0].inst.id, srcs[0].offset, dst.inst.id, dst.offset, dst.size, srcs.size() - 1, (red_fold ? "fold" : "apply"), redop_id, domain.is_id, before_copy.id, before_copy.gen, get_finish_event().id, get_finish_event().gen); if(measurements.wants_measurement<Realm::ProfilingMeasurements::OperationMemoryUsage>()) { Realm::ProfilingMeasurements::OperationMemoryUsage usage; // Not precise, but close enough for now usage.source = srcs[0].inst.get_location(); usage.target = dst.inst.get_location(); usage.size = total_bytes; measurements.add_measurement(usage); } } FillRequest::FillRequest(const void *data, size_t datalen, RegionInstance inst, unsigned offset, unsigned size, Event _before_fill, Event _after_fill, int _priority) : DmaRequest(_priority, _after_fill), before_fill(_before_fill) { dst.inst = inst; dst.offset = offset; dst.size = size; const IDType *idata = (const IDType *)data; idata = domain.deserialize(idata); size_t elmts = *idata++; fill_size = dst.size; fill_buffer = malloc(fill_size); memcpy(fill_buffer, idata, fill_size); idata += elmts; // TODO: unbreak once the serialization stuff is repaired //const void *result = requests.deserialize(idata); //Realm::Operation::reconstruct_measurements(); // better have consumed exactly the right amount of data //assert((((unsigned long)result) - ((unsigned long)data)) == datalen); } FillRequest::FillRequest(const Domain &d, const Domain::CopySrcDstField &_dst, const void *_fill_value, size_t _fill_size, Event _before_fill, Event _after_fill, int _priority, const Realm::ProfilingRequestSet &reqs) : DmaRequest(_priority, _after_fill, reqs), domain(d), dst(_dst), before_fill(_before_fill) { fill_size = _fill_size; fill_buffer = malloc(fill_size); memcpy(fill_buffer, _fill_value, fill_size); } FillRequest::~FillRequest(void) { // clean up our mess free(fill_buffer); } size_t FillRequest::compute_size(void) { size_t result = domain.compute_size(); size_t elmts = (fill_size + sizeof(IDType) - 1)/sizeof(IDType); result += ((elmts+1) * sizeof(IDType)); // +1 for fill size in bytes // TODO: unbreak once the serialization stuff is repaired //result += requests.compute_size(); return result; } void FillRequest::serialize(void *buffer) { IDType *msgptr = domain.serialize((IDType *)buffer); assert(dst.size == fill_size); size_t elmts = (fill_size + sizeof(IDType) - 1)/sizeof(IDType); *msgptr++ = elmts; memcpy(msgptr, fill_buffer, fill_size); msgptr += elmts; // TODO: unbreak once the serialization stuff is repaired //requests.serialize(msgptr); // We sent this message remotely, so we need to clear the profiling // so it doesn't get sent accidentally clear_profiling(); } bool FillRequest::check_readiness(bool just_check, DmaRequestQueue *rq) { if(state == STATE_INIT) state = STATE_METADATA_FETCH; // remember which queue we're going to be assigned to if we sleep waiter.req = this; waiter.queue = rq; // make sure our node has all the meta data it needs, but don't take more than one lock // at a time if(state == STATE_METADATA_FETCH) { // index space first if(domain.get_dim() == 0) { IndexSpaceImpl *is_impl = get_runtime()->get_index_space_impl(domain.get_index_space()); if(!is_impl->locked_data.valid) { log_dma.info("dma request %p - no index space metadata yet", this); if(just_check) return false; Event e = is_impl->lock.acquire(1, false); if(e.has_triggered()) { log_dma.info("request %p - index space metadata invalid - instant trigger", this); is_impl->lock.release(); } else { log_dma.info("request %p - index space metadata invalid - sleeping on lock " IDFMT "", this, is_impl->lock.me.id); waiter.sleep_on_event(e, is_impl->lock.me); return false; } } // we need more than just the metadata - we also need the valid mask { Event e = is_impl->request_valid_mask(); if(!e.has_triggered()) { log_dma.info("request %p - valid mask needed for index space " IDFMT " - sleeping on event " IDFMT "/%d", this, domain.get_index_space().id, e.id, e.gen); waiter.sleep_on_event(e); return false; } } } // No need to check the instance, we are on its local node state = STATE_BEFORE_EVENT; } // make sure our functional precondition has occurred if(state == STATE_BEFORE_EVENT) { // has the before event triggered? if not, wait on it if(before_fill.has_triggered()) { log_dma.info("request %p - before event triggered", this); state = STATE_READY; } else { log_dma.info("request %p - before event not triggered", this); if(just_check) return false; log_dma.info("request %p - sleeping on before event", this); waiter.sleep_on_event(before_fill); return false; } } if(state == STATE_READY) { log_dma.info("request %p ready", this); if(just_check) return true; state = STATE_QUEUED; assert(rq != 0); log_dma.info("request %p enqueued", this); // once we're enqueued, we may be deleted at any time, so no more // references rq->enqueue_request(this); return true; } if(state == STATE_QUEUED) return true; assert(0); return false; } void FillRequest::perform_dma(void) { // First switch on the memory type MemoryImpl *mem_impl = get_runtime()->get_memory_impl(dst.inst.get_location()); MemoryImpl::MemoryKind mem_kind = mem_impl->kind; // TODO: optimize transfers for framebuffer to use a memset kernel if ((mem_kind == MemoryImpl::MKIND_SYSMEM) || (mem_kind == MemoryImpl::MKIND_ZEROCOPY) || (mem_kind == MemoryImpl::MKIND_RDMA) || (mem_kind == MemoryImpl::MKIND_GPUFB) || (mem_kind == MemoryImpl::MKIND_ZEROCOPY)) { switch (domain.get_dim()) { case 0: { // Iterate over all the points and get the IndexSpaceImpl *ispace = get_runtime()->get_index_space_impl(domain.get_index_space()); assert(ispace->valid_mask_complete); RegionInstanceImpl *inst_impl = get_runtime()->get_instance_impl(dst.inst); off_t field_start=0; int field_size=0; find_field_start(inst_impl->metadata.field_sizes, dst.offset, dst.size, field_start, field_size); assert(field_size <= int(fill_size)); int fill_elmts = 1; // Optimize our buffer for the target instance size_t fill_elmts_size = optimize_fill_buffer(inst_impl, fill_elmts); Arrays::Mapping<1, 1> *dst_linearization = inst_impl->metadata.linearization.get_mapping<1>(); ElementMask::Enumerator *e = ispace->valid_mask->enumerate_enabled(); int rstart, elem_count; while(e->get_next(rstart, elem_count)) { int dst_index = dst_linearization->image(rstart); int done = 0; while (done < elem_count) { int dst_in_this_block = inst_impl->metadata.block_size - ((dst_index + done) % inst_impl->metadata.block_size); int todo = min(elem_count, dst_in_this_block); off_t dst_start = calc_mem_loc(inst_impl->metadata.alloc_offset, field_start, field_size, inst_impl->metadata.elmt_size, inst_impl->metadata.block_size, dst_index + done); // Record how many we've done done += todo; // Now do as many bulk transfers as we can while (todo >= fill_elmts) { mem_impl->put_bytes(dst_start, fill_buffer, fill_elmts_size); dst_start += fill_elmts_size; todo -= fill_elmts; } // Handle any remainder elemts if (todo > 0) { mem_impl->put_bytes(dst_start, fill_buffer, todo*fill_size); } } } delete e; break; } case 1: { perform_dma_rect<1>(mem_impl); break; } case 2: { perform_dma_rect<2>(mem_impl); break; } case 3: { perform_dma_rect<3>(mem_impl); break; } default: assert(false); } } else { // TODO: Implement GASNet and Disk assert(false); } if(measurements.wants_measurement<Realm::ProfilingMeasurements::OperationMemoryUsage>()) { Realm::ProfilingMeasurements::OperationMemoryUsage usage; usage.source = Memory::NO_MEMORY; usage.target = dst.inst.get_location(); measurements.add_measurement(usage); } } template<int DIM> void FillRequest::perform_dma_rect(MemoryImpl *mem_impl) { typename Arrays::Rect<DIM> rect = domain.get_rect<DIM>(); // empty rectangles are easy to fill... if(rect.volume() == 0) return; RegionInstanceImpl *inst_impl = get_runtime()->get_instance_impl(dst.inst); off_t field_start=0; int field_size=0; find_field_start(inst_impl->metadata.field_sizes, dst.offset, dst.size, field_start, field_size); assert(field_size <= (int)fill_size); typename Arrays::Mapping<DIM, 1> *dst_linearization = inst_impl->metadata.linearization.get_mapping<DIM>(); int fill_elmts = 1; // Optimize our buffer for the target instance size_t fill_elmts_size = optimize_fill_buffer(inst_impl, fill_elmts); for (typename Arrays::Mapping<DIM, 1>::LinearSubrectIterator lso(rect, *dst_linearization); lso; lso++) { int dst_index = lso.image_lo[0]; int elem_count = lso.subrect.volume(); int done = 0; while (done < elem_count) { int dst_in_this_block = inst_impl->metadata.block_size - ((dst_index + done) % inst_impl->metadata.block_size); int todo = min(elem_count, dst_in_this_block); off_t dst_start = calc_mem_loc(inst_impl->metadata.alloc_offset, field_start, field_size, inst_impl->metadata.elmt_size, inst_impl->metadata.block_size, dst_index + done); // Record how many we've done done += todo; // Now do as many bulk transfers as we can while (todo >= fill_elmts) { mem_impl->put_bytes(dst_start, fill_buffer, fill_elmts_size); dst_start += fill_elmts_size; todo -= fill_elmts; } // Handle any remainder elemts if (todo > 0) { mem_impl->put_bytes(dst_start, fill_buffer, todo*fill_size); } } } } size_t FillRequest::optimize_fill_buffer(RegionInstanceImpl *inst_impl, int &fill_elmts) { const size_t max_size = 1024; // Only do this optimization for "small" fields // which are less than half a page if (fill_size <= max_size) { // If we have a single-field instance or we have a set // of contiguous elmts then make a bulk buffer to use if ((inst_impl->metadata.elmt_size == fill_size) || (inst_impl->metadata.block_size > 1)) { fill_elmts = min(inst_impl->metadata.block_size,2*max_size/fill_size); size_t fill_elmts_size = fill_elmts * fill_size; char *next_buffer = (char*)malloc(fill_elmts_size); char *next_ptr = next_buffer; for (int idx = 0; idx < fill_elmts; idx++) { memcpy(next_ptr, fill_buffer, fill_size); next_ptr += fill_size; } // Free the old buffer and replace it free(fill_buffer); fill_buffer = next_buffer; return fill_elmts_size; } } return fill_size; } #if 0 class CopyCompletionProfiler : public EventWaiter, public Realm::Operation::AsyncWorkItem { public: CopyCompletionProfiler(DmaRequest* _req) : Realm::Operation::AsyncWorkItem(_req), req(_req) { } virtual ~CopyCompletionProfiler(void) { } virtual bool event_triggered(Event e) { mark_finished(); return false; } virtual void print_info(FILE *f) { fprintf(f, "copy completion profiler - " IDFMT "/%d\n", req->get_finish_event().id, req->get_finish_event().gen); } virtual void request_cancellation(void) { // ignored for now } protected: DmaRequest* req; }; #endif // for now we use a single queue for all (local) dmas static DmaRequestQueue *dma_queue = 0; void DmaRequestQueue::worker_thread_loop(void) { log_dma.info("dma worker thread created"); while(!shutdown_flag) { aio_context->make_progress(); bool aio_idle = aio_context->empty(); // get a request, sleeping as necessary DmaRequest *r = dequeue_request(aio_idle); if(r) { bool ok_to_run = r->mark_started(); if(ok_to_run) { // this will automatically add any necessary AsyncWorkItem's r->perform_dma(); r->mark_finished(true /*successful*/); } else r->mark_finished(false /*!successful*/); } } log_dma.info("dma worker thread terminating"); } void DmaRequestQueue::start_workers(int count) { ThreadLaunchParameters tlp; for(int i = 0; i < count; i++) { Thread *t = Thread::create_kernel_thread<DmaRequestQueue, &DmaRequestQueue::worker_thread_loop>(this, tlp, core_rsrv, 0 /* default scheduler*/); worker_threads.push_back(t); } } void start_dma_worker_threads(int count, Realm::CoreReservationSet& crs) { aio_context = new AsyncFileIOContext(256); dma_queue = new DmaRequestQueue(crs); dma_queue->start_workers(count); } void stop_dma_worker_threads(void) { dma_queue->shutdown_queue(); delete dma_queue; dma_queue = 0; delete aio_context; aio_context = 0; } }; }; namespace Realm { using namespace LegionRuntime::LowLevel; Event Domain::fill(const std::vector<CopySrcDstField> &dsts, const void *fill_value, size_t fill_value_size, Event wait_on /*= Event::NO_EVENT*/) const { Realm::ProfilingRequestSet reqs; return Domain::fill(dsts, reqs, fill_value, fill_value_size, wait_on); } Event Domain::fill(const std::vector<CopySrcDstField> &dsts, const Realm::ProfilingRequestSet &requests, const void *fill_value, size_t fill_value_size, Event wait_on /*= Event::NO_EVENT*/) const { std::set<Event> finish_events; for (std::vector<CopySrcDstField>::const_iterator it = dsts.begin(); it != dsts.end(); it++) { Event ev = GenEventImpl::create_genevent()->current_event(); FillRequest *r = new FillRequest(*this, *it, fill_value, fill_value_size, wait_on, ev, 0/*priority*/, requests); Memory mem = it->inst.get_location(); int node = ID(mem).node(); if (((unsigned)node) == gasnet_mynode()) { get_runtime()->optable.add_local_operation(ev, r); r->check_readiness(false, dma_queue); } else { RemoteFillArgs args; args.inst = it->inst; args.offset = it->offset; args.size = it->size; args.before_fill = wait_on; args.after_fill = ev; //args.priority = 0; size_t msglen = r->compute_size(); void *msgdata = malloc(msglen); r->serialize(msgdata); get_runtime()->optable.add_remote_operation(ev, node); RemoteFillMessage::request(node, args, msgdata, msglen, PAYLOAD_FREE); // release local copy of operation r->remove_reference(); } finish_events.insert(ev); } return GenEventImpl::merge_events(finish_events, false /*!ignore faults*/); } Event Domain::copy(RegionInstance src_inst, RegionInstance dst_inst, size_t elem_size, Event wait_on, ReductionOpID redop_id, bool red_fold) const { assert(0); std::vector<CopySrcDstField> srcs, dsts; srcs.push_back(CopySrcDstField(src_inst, 0, elem_size)); dsts.push_back(CopySrcDstField(dst_inst, 0, elem_size)); return copy(srcs, dsts, wait_on, redop_id, red_fold); } }; namespace LegionRuntime { namespace LowLevel { static int select_dma_node(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool red_fold) { int src_node = ID(src_mem).node(); int dst_node = ID(dst_mem).node(); bool src_is_rdma = get_runtime()->get_memory_impl(src_mem)->kind == MemoryImpl::MKIND_GLOBAL; bool dst_is_rdma = get_runtime()->get_memory_impl(dst_mem)->kind == MemoryImpl::MKIND_GLOBAL; if(src_is_rdma) { if(dst_is_rdma) { // gasnet -> gasnet - blech log_dma.warning("WARNING: gasnet->gasnet copy being serialized on local node (%d)", gasnet_mynode()); return gasnet_mynode(); } else { // gathers by the receiver return dst_node; } } else { if(dst_is_rdma) { // writing to gasnet is also best done by the sender return src_node; } else { // if neither side is gasnet, favor the sender (which may be the same as the target) return src_node; } } } void handle_remote_copy(RemoteCopyArgs args, const void *data, size_t msglen) { DetailedTimer::ScopedPush sp(TIME_LOW_LEVEL); // is this a copy or a reduction (they deserialize differently) if(args.redop_id == 0) { // a copy CopyRequest *r = new CopyRequest(data, msglen, args.before_copy, args.after_copy, args.priority); Realm::get_runtime()->optable.add_local_operation(args.after_copy, r); r->check_readiness(false, dma_queue); } else { // a reduction ReduceRequest *r = new ReduceRequest(data, msglen, args.redop_id, args.red_fold, args.before_copy, args.after_copy, args.priority); Realm::get_runtime()->optable.add_local_operation(args.after_copy, r); r->check_readiness(false, dma_queue); } } void handle_remote_fill(RemoteFillArgs args, const void *data, size_t msglen) { FillRequest *r = new FillRequest(data, msglen, args.inst, args.offset, args.size, args.before_fill, args.after_fill, 0 /* no room for args.priority */); Realm::get_runtime()->optable.add_local_operation(args.after_fill, r); r->check_readiness(false, dma_queue); } template <typename T> T min(T a, T b) { return (a < b) ? a : b; } }; }; namespace Realm { Event Domain::copy(const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, Event wait_on, ReductionOpID redop_id, bool red_fold) const { Realm::ProfilingRequestSet reqs; return Domain::copy(srcs, dsts, reqs, wait_on, redop_id, red_fold); } Event Domain::copy(const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, const Realm::ProfilingRequestSet &requests, Event wait_on, ReductionOpID redop_id, bool red_fold) const { if(redop_id == 0) { // not a reduction, so sort fields by src/dst mem pairs OASByMem oas_by_mem; std::vector<CopySrcDstField>::const_iterator src_it = srcs.begin(); std::vector<CopySrcDstField>::const_iterator dst_it = dsts.begin(); unsigned src_suboffset = 0; unsigned dst_suboffset = 0; std::set<Event> finish_events; while((src_it != srcs.end()) && (dst_it != dsts.end())) { InstPair ip(src_it->inst, dst_it->inst); MemPair mp(get_runtime()->get_instance_impl(src_it->inst)->memory, get_runtime()->get_instance_impl(dst_it->inst)->memory); // printf("I:(%x/%x) M:(%x/%x) sub:(%d/%d) src=(%d/%d) dst=(%d/%d)\n", // ip.first.id, ip.second.id, mp.first.id, mp.second.id, // src_suboffset, dst_suboffset, // src_it->offset, src_it->size, // dst_it->offset, dst_it->size); OffsetsAndSize oas; oas.src_offset = src_it->offset + src_suboffset; oas.dst_offset = dst_it->offset + dst_suboffset; oas.size = min(src_it->size - src_suboffset, dst_it->size - dst_suboffset); oas.serdez_id = src_it->serdez_id; // <SERDEZ_DMA> // This is a little bit of hack: if serdez_id != 0 we directly create a // CopyRequest instead of inserting it into ''oasvec'' if (oas.serdez_id != 0) { OASByInst* oas_by_inst = new OASByInst; (*oas_by_inst)[ip].push_back(oas); Event ev = GenEventImpl::create_genevent()->current_event(); int priority = 0; // always have priority zero CopyRequest *r = new CopyRequest(*this, oas_by_inst, wait_on, ev, priority, requests); // ask which node should perform the copy int dma_node = select_dma_node(mp.first, mp.second, redop_id, red_fold); log_dma.info("copy: srcmem=" IDFMT " dstmem=" IDFMT " node=%d", mp.first.id, mp.second.id, dma_node); if(((unsigned)dma_node) == gasnet_mynode()) { log_dma.info("performing serdez on local node"); Realm::get_runtime()->optable.add_local_operation(ev, r); r->check_readiness(false, dma_queue); finish_events.insert(ev); } else { RemoteCopyArgs args; args.redop_id = 0; args.red_fold = false; args.before_copy = wait_on; args.after_copy = ev; args.priority = priority; size_t msglen = r->compute_size(); void *msgdata = malloc(msglen); r->serialize(msgdata); log_dma.info("performing serdez on remote node (%d), event=" IDFMT "/%d", dma_node, args.after_copy.id, args.after_copy.gen); get_runtime()->optable.add_remote_operation(ev, dma_node); RemoteCopyMessage::request(dma_node, args, msgdata, msglen, PAYLOAD_FREE); finish_events.insert(ev); // done with the local copy of the request r->remove_reference(); } } else { // </SERDEZ_DMA> OASByInst *oas_by_inst; OASByMem::iterator it = oas_by_mem.find(mp); if(it != oas_by_mem.end()) { oas_by_inst = it->second; } else { oas_by_inst = new OASByInst; oas_by_mem[mp] = oas_by_inst; } OASVec& oasvec = (*oas_by_inst)[ip]; oasvec.push_back(oas); } src_suboffset += oas.size; assert(src_suboffset <= src_it->size); if(src_suboffset == src_it->size) { src_it++; src_suboffset = 0; } dst_suboffset += oas.size; assert(dst_suboffset <= dst_it->size); if(dst_suboffset == dst_it->size) { dst_it++; dst_suboffset = 0; } } // make sure we used up both assert(src_it == srcs.end()); assert(dst_it == dsts.end()); log_dma.info("copy: %zd distinct src/dst mem pairs, is=" IDFMT "", oas_by_mem.size(), is_id); for(OASByMem::const_iterator it = oas_by_mem.begin(); it != oas_by_mem.end(); it++) { Memory src_mem = it->first.first; Memory dst_mem = it->first.second; OASByInst *oas_by_inst = it->second; Event ev = GenEventImpl::create_genevent()->current_event(); #ifdef EVENT_GRAPH_TRACE Event enclosing = find_enclosing_termination_event(); log_event_graph.info("Copy Request: (" IDFMT ",%d) (" IDFMT ",%d) " "(" IDFMT ",%d) " IDFMT " " IDFMT "", ev.id, ev.gen, wait_on.id, wait_on.gen, enclosing.id, enclosing.gen, src_mem.id, dst_mem.id); #endif int priority = 0; if (get_runtime()->get_memory_impl(src_mem)->kind == MemoryImpl::MKIND_GPUFB) priority = 1; else if (get_runtime()->get_memory_impl(dst_mem)->kind == MemoryImpl::MKIND_GPUFB) priority = 1; CopyRequest *r = new CopyRequest(*this, oas_by_inst, wait_on, ev, priority, requests); // ask which node should perform the copy int dma_node = select_dma_node(src_mem, dst_mem, redop_id, red_fold); log_dma.info("copy: srcmem=" IDFMT " dstmem=" IDFMT " node=%d", src_mem.id, dst_mem.id, dma_node); if(((unsigned)dma_node) == gasnet_mynode()) { log_dma.info("performing copy on local node"); get_runtime()->optable.add_local_operation(ev, r); r->check_readiness(false, dma_queue); finish_events.insert(ev); } else { RemoteCopyArgs args; args.redop_id = 0; args.red_fold = false; args.before_copy = wait_on; args.after_copy = ev; args.priority = priority; size_t msglen = r->compute_size(); void *msgdata = malloc(msglen); r->serialize(msgdata); log_dma.info("performing copy on remote node (%d), event=" IDFMT "/%d", dma_node, args.after_copy.id, args.after_copy.gen); get_runtime()->optable.add_remote_operation(ev, dma_node); RemoteCopyMessage::request(dma_node, args, msgdata, msglen, PAYLOAD_FREE); finish_events.insert(ev); // done with the local copy of the request r->remove_reference(); } } // final event is merge of all individual copies' events return GenEventImpl::merge_events(finish_events, false /*!ignore faults*/); } else { // we're doing a reduction - the semantics require that all source fields be pulled // together and applied as a "structure" to the reduction op // figure out where the source data is int src_node = -1; for(std::vector<CopySrcDstField>::const_iterator src_it = srcs.begin(); src_it != srcs.end(); src_it++) { int n = ID(src_it->inst).node(); if((src_node != -1) && (src_node != n)) { // for now, don't handle case where source data is split across nodes assert(0); } src_node = n; } assert(dsts.size() == 1); // some destinations (e.g. GASNET) need a lock taken to ensure // reductions are applied atomically MemoryImpl::MemoryKind dst_kind = get_runtime()->get_memory_impl(get_runtime()->get_instance_impl(dsts[0].inst)->memory)->kind; bool inst_lock_needed = (dst_kind == MemoryImpl::MKIND_GLOBAL); Event ev = GenEventImpl::create_genevent()->current_event(); ReduceRequest *r = new ReduceRequest(*this, srcs, dsts[0], inst_lock_needed, redop_id, red_fold, wait_on, ev, 0 /*priority*/, requests); if(((unsigned)src_node) == gasnet_mynode()) { log_dma.info("performing reduction on local node"); get_runtime()->optable.add_local_operation(ev, r); r->check_readiness(false, dma_queue); } else { RemoteCopyArgs args; args.redop_id = redop_id; args.red_fold = red_fold; args.before_copy = wait_on; args.after_copy = ev; args.priority = 0 /*priority*/; size_t msglen = r->compute_size(); void *msgdata = malloc(msglen); r->serialize(msgdata); log_dma.info("performing reduction on remote node (%d), event=" IDFMT "/%d", src_node, args.after_copy.id, args.after_copy.gen); get_runtime()->optable.add_remote_operation(ev, src_node); RemoteCopyMessage::request(src_node, args, msgdata, msglen, PAYLOAD_FREE); // done with the local copy of the request r->remove_reference(); } return ev; } } Event Domain::copy(const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, const ElementMask& mask, Event wait_on, ReductionOpID redop_id, bool red_fold) const { assert(redop_id == 0); assert(0); log_dma.warning("ignoring copy\n"); return Event::NO_EVENT; } Event Domain::copy_indirect(const CopySrcDstField& idx, const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, Event wait_on, ReductionOpID redop_id, bool red_fold) const { assert(redop_id == 0); assert(0); } Event Domain::copy_indirect(const CopySrcDstField& idx, const std::vector<CopySrcDstField>& srcs, const std::vector<CopySrcDstField>& dsts, const ElementMask& mask, Event wait_on, ReductionOpID redop_id, bool red_fold) const { assert(redop_id == 0); assert(0); } };
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.36 2001/03/02 19:44:11 barbera modified to taking into account new version tracking v1 Revision 1.35 2001/02/28 18:16:46 mariana Make the code compatible with the new AliRun Revision 1.34 2001/02/11 15:51:39 mariana Set protection in MakeBranch Revision 1.33 2001/02/10 22:26:39 mariana Move the initialization of the containers for raw clusters in MakeTreeC() Revision 1.32 2001/02/08 23:55:31 nilsen Removed fMajor/MinorVersion variables in favor of variables in derived classes. Set arrays char *det[3] = {"SPD","SDD","SSD"} as const. Revision 1.31 2001/02/02 23:57:28 nilsen Added include file that are no londer included in AliITSgeom.h Revision 1.30 2001/01/30 09:23:13 hristov Streamers removed (R.Brun) Revision 1.29 2001/01/26 20:01:09 hristov Major upgrade of AliRoot code Revision 1.28 2000/12/18 14:02:00 barbera new version of the ITS tracking to take into account the new TPC track parametrization Revision 1.27 2000/12/08 13:49:27 barbera Hidden declaration in a for loop removed to be compliant with HP-UX compiler Revision 1.26 2000/11/27 13:12:13 barbera New version containing the files for tracking Revision 1.25 2000/11/12 22:38:05 barbera Added header file for the SPD Bari model Revision 1.24 2000/10/09 22:18:12 barbera Bug fixes from MAriana to le AliITStest.C run correctly Revision 1.23 2000/10/05 20:47:42 nilsen fixed dependencies of include files. Tryed but failed to get a root automaticly generates streamer function to work. Modified SetDefaults. Revision 1.9.2.15 2000/10/04 16:56:40 nilsen Needed to include stdlib.h ======= Revision 1.22 2000/10/04 19:45:52 barbera Corrected by F. Carminati for v3.04 Revision 1.21 2000/10/02 21:28:08 fca Removal of useless dependecies via forward declarations Revision 1.20 2000/10/02 16:31:39 barbera General code clean-up Revision 1.9.2.14 2000/10/02 15:43:51 barbera General code clean-up (e.g., printf -> cout) Revision 1.19 2000/09/22 12:13:25 nilsen Patches and updates for fixes to this and other routines. Revision 1.18 2000/07/12 05:32:20 fca Correcting several syntax problem with static members Revision 1.17 2000/07/10 16:07:18 fca Release version of ITS code Revision 1.9.2.3 2000/02/02 13:42:09 barbera fixed AliITS.cxx for new AliRun structure. Added ITS hits list to list of hits which will have their track numbers updated Revision 1.9.2.2 2000/01/23 03:03:13 nilsen //fixed FillModule. Removed fi(fabs(xl)<dx.... Revision 1.9.2.1 2000/01/12 19:03:32 nilsen This is the version of the files after the merging done in December 1999. See the ReadMe110100.txt file for details Revision 1.9 1999/11/14 14:33:25 fca Correct problems with distructors and pointers, thanks to I.Hrivnacova Revision 1.8 1999/09/29 09:24:19 fca Introduction of the Copyright and cvs Log */ /////////////////////////////////////////////////////////////////////////////// // // An overview of the basic philosophy of the ITS code development // and analysis is show in the figure below. //Begin_Html /* <img src="picts/ITS/ITS_Analysis_schema.gif"> </pre> <br clear=left> <font size=+2 color=red> <p>Roberto Barbera is in charge of the ITS Offline code (1999). <a href="mailto:roberto.barbera@ct.infn.it">Roberto Barbera</a>. </font> <pre> */ //End_Html // // AliITS. Inner Traking System base class. // This class contains the base procedures for the Inner Tracking System // //Begin_Html /* <img src="picts/ITS/AliITS_Class_Diagram.gif"> </pre> <br clear=left> <font size=+2 color=red> <p>This show the class diagram of the different elements that are part of the AliITS class. </font> <pre> */ //End_Html // // Version: 0 // Written by Rene Brun, Federico Carminati, and Roberto Barbera // // Version: 1 // Modified and documented by Bjorn S. Nilsen // July 11 1999 // // Version: 2 // Modified and documented by A. Bologna // October 18 1999 // // AliITS is the general base class for the ITS. Also see AliDetector for // futher information. // /////////////////////////////////////////////////////////////////////////////// #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include <stdlib.h> #include <TMath.h> #include <TRandom.h> #include <TBranch.h> #include <TVector.h> #include <TClonesArray.h> #include <TROOT.h> #include <TObjectTable.h> #include <TFile.h> #include <TTree.h> #include <TString.h> #include <TParticle.h> #include "AliRun.h" #include "AliITS.h" #include "AliITSMap.h" #include "AliITSDetType.h" #include "AliITSClusterFinder.h" //#include "AliITSsimulation.h" #include "AliITSsimulationSPD.h" #include "AliITSsimulationSDD.h" #include "AliITSsimulationSSD.h" #include "AliITSresponse.h" #include "AliITSsegmentationSPD.h" #include "AliITSresponseSPD.h" #include "AliITSresponseSPDbari.h" #include "AliITSsegmentationSDD.h" #include "AliITSresponseSDD.h" #include "AliITSsegmentationSSD.h" #include "AliITSresponseSSD.h" #include "AliITShit.h" #include "AliITSgeom.h" #include "AliITSdigit.h" #include "AliITSmodule.h" #include "AliITSRecPoint.h" #include "AliITSRawCluster.h" #include "AliMC.h" #include "stdlib.h" #include "AliITStrack.h" #include "AliITSiotrack.h" #include "AliITStracking.h" #include "AliITSRad.h" #include "../TPC/AliTPC.h" #include "../TPC/AliTPCParam.h" ClassImp(AliITS) //_____________________________________________________________________________ AliITS::AliITS() : AliDetector() { // // Default initialiser for ITS // The default constructor of the AliITS class. In addition to // creating the AliITS class it zeros the variables fIshunt (a member // of AliDetector class), fEuclidOut, and fIdN, and zeros the pointers // fITSpoints, fIdSens, and fIdName. The AliDetector default constructor // is also called. // fIshunt = 0; fEuclidOut = 0; fNDetTypes = kNTYPES; fIdN = 0; fIdName = 0; fIdSens = 0; fITSmodules = 0; // fDetTypes = 0; // fDtype = 0; fNdtype = 0; fCtype = 0; fNctype = 0; fRecPoints = 0; fNRecPoints = 0; fTreeC = 0; // fITSgeom=0; } //_____________________________________________________________________________ AliITS::AliITS(const char *name, const char *title):AliDetector(name,title){ // // Default initialiser for ITS // The constructor of the AliITS class. In addition to creating the // AliITS class, it allocates memory for the TClonesArrays fHits and // fDigits, and for the TObjArray fITSpoints. It also zeros the variables // fIshunt (a member of AliDetector class), fEuclidOut, and fIdN, and zeros // the pointers fIdSens and fIdName. To help in displaying hits via the ROOT // macro display.C AliITS also sets the marker color to red. The variables // passes with this constructor, const char *name and *title, are used by // the constructor of AliDetector class. See AliDetector class for a // description of these parameters and its constructor functions. // fHits = new TClonesArray("AliITShit", 1560); gAlice->AddHitList(fHits); fNDetTypes = kNTYPES; fNdtype = new Int_t[kNTYPES]; fDtype = new TObjArray(kNTYPES); fNctype = new Int_t[kNTYPES]; fCtype = new TObjArray(kNTYPES); fRecPoints = 0; fNRecPoints = 0; fTreeC = 0; fITSmodules = 0; fIshunt = 0; fEuclidOut = 0; fIdN = 0; fIdName = 0; fIdSens = 0; fDetTypes = new TObjArray(kNTYPES); Int_t i; for(i=0;i<kNTYPES;i++) { (*fDetTypes)[i]=new AliITSDetType(); fNdtype[i]=0; fNctype[i]=0; } // SetMarkerColor(kRed); fITSgeom=0; } //___________________________________________________________________________ AliITS::AliITS(AliITS &source){ // copy constructor if(this==&source) return; Error("AliITS::Copy constructor", "You are not allowed to make a copy of the AliITS"); exit(1); } //____________________________________________________________________________ AliITS& AliITS::operator=(AliITS &source){ // assignment operator if(this==&source) return *this; Error("AliITS::operator=", "You are not allowed to make a copy of the AliITS"); exit(1); return *this; //fake return } //____________________________________________________________________________ void AliITS::ClearModules(){ //clear the modules TObjArray if(fITSmodules) fITSmodules->Delete(); } //_____________________________________________________________________________ AliITS::~AliITS(){ // // Default distructor for ITS // The default destructor of the AliITS class. In addition to deleting // the AliITS class it deletes the memory pointed to by the fHits, fDigits, // fIdSens, fIdName, and fITSpoints. // delete fHits; delete fDigits; delete fRecPoints; // delete fIdName; // TObjArray of TObjStrings if(fIdName!=0) delete[] fIdName; // Array of TStrings if(fIdSens!=0) delete[] fIdSens; if(fITSmodules!=0) { this->ClearModules(); delete fITSmodules; }// end if fITSmodules!=0 // if(fDtype) { fDtype->Delete(); delete fDtype; } delete [] fNdtype; if (fCtype) { fCtype->Delete(); delete fCtype; } delete [] fNctype; // if (fDetTypes) { fDetTypes->Delete(); delete fDetTypes; } if (fTreeC) delete fTreeC; if (fITSgeom) delete fITSgeom; } //___________________________________________ AliITSDetType* AliITS::DetType(Int_t id) { //return pointer to id detector type return ((AliITSDetType*) (*fDetTypes)[id]); } //___________________________________________ void AliITS::SetClasses(Int_t id, const char *digit, const char *cluster) { //set the digit and cluster classes to be used for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->ClassNames(digit,cluster); } //___________________________________________ void AliITS::SetResponseModel(Int_t id, AliITSresponse *response) { //set the response model for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->ResponseModel(response); } //___________________________________________ void AliITS::SetSegmentationModel(Int_t id, AliITSsegmentation *seg) { //set the segmentation model for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->SegmentationModel(seg); } //___________________________________________ void AliITS::SetSimulationModel(Int_t id, AliITSsimulation *sim) { //set the simulation model for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->SimulationModel(sim); } //___________________________________________ void AliITS::SetReconstructionModel(Int_t id, AliITSClusterFinder *reconst) { //set the cluster finder model for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->ReconstructionModel(reconst); } //_____________________________________________________________________________ void AliITS::AddHit(Int_t track, Int_t *vol, Float_t *hits){ // // Add an ITS hit // The function to add information to the AliITShit class. See the // AliITShit class for a full description. This function allocates the // necessary new space for the hit information and passes the variable // track, and the pointers *vol and *hits to the AliITShit constructor // function. // TClonesArray &lhits = *fHits; new(lhits[fNhits++]) AliITShit(fIshunt,track,vol,hits); } //_____________________________________________________________________________ void AliITS::AddRealDigit(Int_t id, Int_t *digits) { // add a real digit - as coming from data TClonesArray &ldigits = *((TClonesArray*)(*fDtype)[id]); new(ldigits[fNdtype[id]++]) AliITSdigit(digits); } //_____________________________________________________________________________ void AliITS::AddSimDigit(Int_t id, AliITSdigit *d) { // add a simulated digit TClonesArray &ldigits = *((TClonesArray*)(*fDtype)[id]); switch(id) { case 0: new(ldigits[fNdtype[id]++]) AliITSdigitSPD(*((AliITSdigitSPD*)d)); break; case 1: new(ldigits[fNdtype[id]++]) AliITSdigitSDD(*((AliITSdigitSDD*)d)); break; case 2: new(ldigits[fNdtype[id]++]) AliITSdigitSSD(*((AliITSdigitSSD*)d)); break; } } //_____________________________________________________________________________ void AliITS::AddSimDigit(Int_t id,Float_t phys,Int_t *digits,Int_t *tracks,Int_t *hits,Float_t *charges){ // add a simulated digit to the list TClonesArray &ldigits = *((TClonesArray*)(*fDtype)[id]); switch(id) { case 0: new(ldigits[fNdtype[id]++]) AliITSdigitSPD(digits,tracks,hits); break; case 1: new(ldigits[fNdtype[id]++]) AliITSdigitSDD(phys,digits,tracks,hits,charges); break; case 2: new(ldigits[fNdtype[id]++]) AliITSdigitSSD(digits,tracks,hits); break; } } //_____________________________________________________________________________ void AliITS::AddCluster(Int_t id, AliITSRawCluster *c) { // add a cluster to the list TClonesArray &lcl = *((TClonesArray*)(*fCtype)[id]); switch(id) { case 0: new(lcl[fNctype[id]++]) AliITSRawClusterSPD(*((AliITSRawClusterSPD*)c)); break; case 1: new(lcl[fNctype[id]++]) AliITSRawClusterSDD(*((AliITSRawClusterSDD*)c)); break; case 2: new(lcl[fNctype[id]++]) AliITSRawClusterSSD(*((AliITSRawClusterSSD*)c)); break; } } //_____________________________________________________________________________ void AliITS::AddRecPoint(const AliITSRecPoint &r) { // // Add a reconstructed space point to the list // TClonesArray &lrecp = *fRecPoints; new(lrecp[fNRecPoints++]) AliITSRecPoint(r); } //____________________________________________ void AliITS::ResetDigits() { // // Reset number of digits and the digits array for the ITS detector // if (!fDtype) return; Int_t i; for (i=0;i<kNTYPES;i++ ) { if ((*fDtype)[i]) ((TClonesArray*)(*fDtype)[i])->Clear(); if (fNdtype) fNdtype[i]=0; } } //____________________________________________ void AliITS::ResetDigits(Int_t i) { // // Reset number of digits and the digits array for this branch // if ((*fDtype)[i]) ((TClonesArray*)(*fDtype)[i])->Clear(); if (fNdtype) fNdtype[i]=0; } //____________________________________________ void AliITS::ResetClusters() { // // Reset number of clusters and the clusters array for ITS // Int_t i; for (i=0;i<kNTYPES;i++ ) { if ((*fCtype)[i]) ((TClonesArray*)(*fCtype)[i])->Clear(); if (fNctype) fNctype[i]=0; } } //____________________________________________ void AliITS::ResetClusters(Int_t i) { // // Reset number of clusters and the clusters array for this branch // if ((*fCtype)[i]) ((TClonesArray*)(*fCtype)[i])->Clear(); if (fNctype) fNctype[i]=0; } //____________________________________________ void AliITS::ResetRecPoints() { // // Reset number of rec points and the rec points array // if (fRecPoints) fRecPoints->Clear(); fNRecPoints = 0; } //_____________________________________________________________________________ Int_t AliITS::DistancetoPrimitive(Int_t , Int_t ){ // // Distance from mouse to ITS on the screen. Dummy routine // A dummy routine used by the ROOT macro display.C to allow for the // use of the mouse (pointing device) in the macro. In general this should // never be called. If it is it returns the number 9999 for any value of // x and y. // return 9999; } //_____________________________________________________________________________ void AliITS::Init(){ // // Initialise ITS after it has been built // This routine initializes the AliITS class. It is intended to be called // from the Init function in AliITSv?. Besides displaying a banner // indicating that it has been called it initializes the array fIdSens // and sets the default segmentation, response, digit and raw cluster classes // Therefore it should be called after a call to CreateGeometry. // Int_t i; // SetDefaults(); // Array of TStrings for(i=0;i<fIdN;i++) fIdSens[i] = gMC->VolId(fIdName[i]); // } //_____________________________________________________________________________ void AliITS::SetDefaults() { // sets the default segmentation, response, digit and raw cluster classes printf("SetDefaults\n"); AliITSDetType *iDetType; //SPD iDetType=DetType(0); if (!iDetType->GetSegmentationModel()) { AliITSsegmentationSPD *seg0=new AliITSsegmentationSPD(fITSgeom); SetSegmentationModel(0,seg0); } if (!iDetType->GetResponseModel()) { SetResponseModel(0,new AliITSresponseSPD()); } // set digit and raw cluster classes to be used const char *kData0=(iDetType->GetResponseModel())->DataType(); if (strstr(kData0,"real")) { iDetType->ClassNames("AliITSdigit","AliITSRawClusterSPD"); } else iDetType->ClassNames("AliITSdigitSPD","AliITSRawClusterSPD"); // SDD // iDetType=DetType(1); if (!iDetType->GetResponseModel()) { SetResponseModel(1,new AliITSresponseSDD()); } AliITSresponse *resp1=iDetType->GetResponseModel(); if (!iDetType->GetSegmentationModel()) { AliITSsegmentationSDD *seg1=new AliITSsegmentationSDD(fITSgeom,resp1); SetSegmentationModel(1,seg1); } const char *kData1=(iDetType->GetResponseModel())->DataType(); const char *kopt=iDetType->GetResponseModel()->ZeroSuppOption(); if ((!strstr(kopt,"2D")) && (!strstr(kopt,"1D")) || strstr(kData1,"real") ) { iDetType->ClassNames("AliITSdigit","AliITSRawClusterSDD"); } else iDetType->ClassNames("AliITSdigitSDD","AliITSRawClusterSDD"); // SSD iDetType=DetType(2); if (!iDetType->GetSegmentationModel()) { AliITSsegmentationSSD *seg2=new AliITSsegmentationSSD(fITSgeom); SetSegmentationModel(2,seg2); } if (!iDetType->GetResponseModel()) { SetResponseModel(2,new AliITSresponseSSD()); } const char *kData2=(iDetType->GetResponseModel())->DataType(); if (strstr(kData2,"real")) { iDetType->ClassNames("AliITSdigit","AliITSRawClusterSSD"); } else iDetType->ClassNames("AliITSdigitSSD","AliITSRawClusterSSD"); if (kNTYPES>3) { Warning("SetDefaults","Only the three basic detector types are initialised!"); } } //_____________________________________________________________________________ void AliITS::SetDefaultSimulation() { // to be written } //_____________________________________________________________________________ void AliITS::SetDefaultClusterFinders() { // to be written } //_____________________________________________________________________________ void AliITS::MakeTreeC(Option_t *option) { // create a separate tree to store the clusters cout << "AliITS::MakeTreeC" << endl; char *optC = strstr(option,"C"); if (optC && !fTreeC) fTreeC = new TTree("TC","Clusters in ITS"); else return; Int_t buffersize = 4000; char branchname[30]; const char *det[3] = {"SPD","SDD","SSD"}; char digclass[40]; char clclass[40]; // one branch for Clusters per type of detector Int_t i; for (i=0; i<kNTYPES ;i++) { AliITSDetType *iDetType=DetType(i); iDetType->GetClassNames(digclass,clclass); // clusters (*fCtype)[i] = new TClonesArray(clclass,10000); if (kNTYPES==3) sprintf(branchname,"%sClusters%s",GetName(),det[i]); else sprintf(branchname,"%sClusters%d",GetName(),i+1); if (fCtype && fTreeC) { TreeC()->Branch(branchname,&((*fCtype)[i]), buffersize); cout << "Making Branch " << branchname; cout << " for Clusters of detector type " << i+1 << endl; } } } //_____________________________________________________________________________ void AliITS::GetTreeC(Int_t event) { cout << "AliITS::GetTreeC" << endl; // get the clusters tree for this event and set the branch address char treeName[20]; char branchname[30]; const char *det[3] = {"SPD","SDD","SSD"}; ResetClusters(); if (fTreeC) { delete fTreeC; } sprintf(treeName,"TreeC%d",event); fTreeC = (TTree*)gDirectory->Get(treeName); TBranch *branch; if (fTreeC) { Int_t i; for (i=0; i<kNTYPES; i++) { if (kNTYPES==3) sprintf(branchname,"%sClusters%s",GetName(),det[i]); else sprintf(branchname,"%sClusters%d",GetName(),i+1); if (fCtype) { branch = fTreeC->GetBranch(branchname); if (branch) branch->SetAddress(&((*fCtype)[i])); } } } else { Error("AliITS::GetTreeC", "cannot find Clusters Tree for event:%d\n",event); } } //_____________________________________________________________________________ void AliITS::MakeBranch(Option_t* option, char *file) { // // Creates Tree branches for the ITS. // // Int_t buffersize = 4000; char branchname[30]; sprintf(branchname,"%s",GetName()); AliDetector::MakeBranch(option,file); char *cD = strstr(option,"D"); char *cR = strstr(option,"R"); if (cD) { // // one branch for digits per type of detector // const char *det[3] = {"SPD","SDD","SSD"}; char digclass[40]; char clclass[40]; Int_t i; for (i=0; i<kNTYPES ;i++) { AliITSDetType *iDetType=DetType(i); iDetType->GetClassNames(digclass,clclass); // digits if(!((*fDtype)[i])) (*fDtype)[i] = new TClonesArray(digclass,10000); else ResetDigits(i); } for (i=0; i<kNTYPES ;i++) { if (kNTYPES==3) sprintf(branchname,"%sDigits%s",GetName(),det[i]); else sprintf(branchname,"%sDigits%d",GetName(),i+1); if (fDtype && gAlice->TreeD()) { gAlice->MakeBranchInTree(gAlice->TreeD(), branchname, &((*fDtype)[i]), buffersize, file); cout << "Making Branch " << branchname; cout << " for digits of type "<< i+1 << endl; } } } if (cR) { // // only one branch for rec points for all detector types // sprintf(branchname,"%sRecPoints",GetName()); if(!fRecPoints) fRecPoints=new TClonesArray("AliITSRecPoint",10000); if (fRecPoints && gAlice->TreeR()) { gAlice->MakeBranchInTree(gAlice->TreeR(), branchname, &fRecPoints, buffersize, file) ; cout << "Making Branch " << branchname; cout << " for reconstructed space points" << endl; } } } //___________________________________________ void AliITS::SetTreeAddress() { // Set branch address for the Trees. char branchname[30]; AliDetector::SetTreeAddress(); const char *det[3] = {"SPD","SDD","SSD"}; TBranch *branch; TTree *treeD = gAlice->TreeD(); TTree *treeR = gAlice->TreeR(); Int_t i; if (treeD) { for (i=0; i<kNTYPES; i++) { if (kNTYPES==3) sprintf(branchname,"%sDigits%s",GetName(),det[i]); else sprintf(branchname,"%sDigits%d",GetName(),i+1); if (fDtype) { branch = treeD->GetBranch(branchname); if (branch) branch->SetAddress(&((*fDtype)[i])); } } } if (treeR) { sprintf(branchname,"%sRecPoints",GetName()); branch = treeR->GetBranch(branchname); if (branch) branch->SetAddress(&fRecPoints); } } //____________________________________________________________________________ void AliITS::InitModules(Int_t size,Int_t &nmodules){ //initialize the modules array if(fITSmodules){ fITSmodules->Delete(); delete fITSmodules; } Int_t nl,indexMAX,index; if(size<=0){ // default to using data stored in AliITSgeom if(fITSgeom==0) { Error("AliITS::InitModules", "in AliITS::InitModule fITSgeom not defined\n"); return; } // end if fITSgeom==0 nl = fITSgeom->GetNlayers(); indexMAX = fITSgeom->GetModuleIndex(nl,fITSgeom->GetNladders(nl), fITSgeom->GetNdetectors(nl))+1; nmodules = indexMAX; fITSmodules = new TObjArray(indexMAX); for(index=0;index<indexMAX;index++){ fITSmodules->AddAt( new AliITSmodule(index),index); } // end for index }else{ fITSmodules = new TObjArray(size); for(index=0;index<size;index++) { fITSmodules->AddAt( new AliITSmodule(index),index); } nmodules = size; } // end i size<=0 } //____________________________________________________________________________ void AliITS::FillModules(Int_t evnt,Int_t bgrev,Int_t nmodules,Option_t *option,Text_t *filename){ // fill the modules with the sorted by module hits; add hits from background // if option=Add static TTree *trH1; //Tree with background hits static TClonesArray *fHits2; //List of hits for one track only static Bool_t first=kTRUE; static TFile *file; char *addBgr = strstr(option,"Add"); if (addBgr ) { if(first) { cout<<"filename "<<filename<<endl; file=new TFile(filename); cout<<"I have opened "<<filename<<" file "<<endl; fHits2 = new TClonesArray("AliITShit",1000 ); } first=kFALSE; file->cd(); file->ls(); // Get Hits Tree header from file if(fHits2) fHits2->Clear(); if(trH1) delete trH1; trH1=0; char treeName[20]; sprintf(treeName,"TreeH%d",bgrev); trH1 = (TTree*)gDirectory->Get(treeName); //printf("TrH1 %p of treename %s for event %d \n",trH1,treeName,bgrev); if (!trH1) { Error("AliITS::FillModules", "cannot find Hits Tree for event:%d\n",bgrev); } // Set branch addresses TBranch *branch; char branchname[20]; sprintf(branchname,"%s",GetName()); if (trH1 && fHits2) { branch = trH1->GetBranch(branchname); if (branch) branch->SetAddress(&fHits2); } // test //Int_t ntracks1 =(Int_t)TrH1->GetEntries(); //printf("background - ntracks1 - %d\n",ntracks1); } //Int_t npart = gAlice->GetEvent(evnt); //if(npart<=0) return; TClonesArray *itsHits = this->Hits(); Int_t lay,lad,det,index; AliITShit *itsHit=0; AliITSmodule *mod=0; TTree *iTH = gAlice->TreeH(); Int_t ntracks =(Int_t) iTH->GetEntries(); Int_t t,h; for(t=0; t<ntracks; t++){ gAlice->ResetHits(); iTH->GetEvent(t); Int_t nhits = itsHits->GetEntriesFast(); //printf("nhits %d\n",nhits); if (!nhits) continue; for(h=0; h<nhits; h++){ itsHit = (AliITShit *)itsHits->UncheckedAt(h); itsHit->GetDetectorID(lay,lad,det); // temporarily index=det-1 !!! if(fITSgeom) index = fITSgeom->GetModuleIndex(lay,lad,det); else index=det-1; // mod = this->GetModule(index); mod->AddHit(itsHit,t,h); } // end loop over hits } // end loop over tracks // open the file with background if (addBgr ) { Int_t track,i; ntracks =(Int_t)trH1->GetEntries(); //printf("background - ntracks1 %d\n",ntracks); //printf("background - Start loop over tracks \n"); // Loop over tracks for (track=0; track<ntracks; track++) { if (fHits2) fHits2->Clear(); trH1->GetEvent(track); // Loop over hits for(i=0;i<fHits2->GetEntriesFast();++i) { itsHit=(AliITShit*) (*fHits2)[i]; itsHit->GetDetectorID(lay,lad,det); // temporarily index=det-1 !!! if(fITSgeom) index = fITSgeom->GetModuleIndex(lay,lad,det); else index=det-1; // mod = this->GetModule(index); mod->AddHit(itsHit,track,i); } // end loop over hits } // end loop over tracks TTree *fAli=gAlice->TreeK(); TFile *fileAli=0; if (fAli) fileAli =fAli->GetCurrentFile(); fileAli->cd(); } // end if add //gObjectTable->Print(); } //____________________________________________________________________________ void AliITS::SDigits2Digits() { AliITSgeom *geom = GetITSgeom(); // SPD AliITSDetType *iDetType; iDetType=DetType(0); AliITSsegmentationSPD *seg0=(AliITSsegmentationSPD*)iDetType->GetSegmentationModel(); AliITSresponseSPD *res0 = (AliITSresponseSPD*)iDetType->GetResponseModel(); AliITSsimulationSPD *sim0=new AliITSsimulationSPD(seg0,res0); SetSimulationModel(0,sim0); // test // printf("SPD dimensions %f %f \n",seg0->Dx(),seg0->Dz()); // printf("SPD npixels %d %d \n",seg0->Npz(),seg0->Npx()); // printf("SPD pitches %d %d \n",seg0->Dpz(0),seg0->Dpx(0)); // end test // // SDD //Set response functions Float_t baseline = 10.; Float_t noise = 1.75; // SDD compression param: 2 fDecrease, 2fTmin, 2fTmax or disable, 2 fTolerance iDetType=DetType(1); AliITSresponseSDD *res1 = (AliITSresponseSDD*)iDetType->GetResponseModel(); if (!res1) { res1=new AliITSresponseSDD(); SetResponseModel(1,res1); } res1->SetMagicValue(900.); Float_t maxadc = res1->MaxAdc(); Float_t topValue = res1->MagicValue(); Float_t norm = maxadc/topValue; Float_t fCutAmp = baseline + 2.*noise; fCutAmp *= norm; Int_t cp[8]={0,0,(int)fCutAmp,(int)fCutAmp,0,0,0,0}; //1D //res1->SetZeroSupp("2D"); res1->SetZeroSupp("1D"); res1->SetNoiseParam(noise,baseline); res1->SetDo10to8(kTRUE); res1->SetCompressParam(cp); res1->SetMinVal(4); res1->SetDiffCoeff(3.6,40.); //res1->SetMagicValue(96.95); AliITSsegmentationSDD *seg1=(AliITSsegmentationSDD*)iDetType->GetSegmentationModel(); if (!seg1) { seg1 = new AliITSsegmentationSDD(geom,res1); SetSegmentationModel(1,seg1); } AliITSsimulationSDD *sim1=new AliITSsimulationSDD(seg1,res1); sim1->SetDoFFT(1); sim1->SetCheckNoise(kFALSE); SetSimulationModel(1,sim1); // SSD iDetType=DetType(2); AliITSsegmentationSSD *seg2=(AliITSsegmentationSSD*)iDetType->GetSegmentationModel(); AliITSresponseSSD *res2 = (AliITSresponseSSD*)iDetType->GetResponseModel(); res2->SetSigmaSpread(3.,2.); AliITSsimulationSSD *sim2=new AliITSsimulationSSD(seg2,res2); SetSimulationModel(2,sim2); cerr<<"Digitizing ITS...\n"; TStopwatch timer; timer.Start(); HitsToDigits(0,0,-1," ","All"," "); timer.Stop(); timer.Print(); delete sim0; delete sim1; delete sim2; } //____________________________________________________________________________ void AliITS::HitsToDigits(Int_t evNumber,Int_t bgrev,Int_t size, Option_t *option, Option_t *opt,Text_t *filename) { // keep galice.root for signal and name differently the file for // background when add! otherwise the track info for signal will be lost ! // the condition below will disappear when the geom class will be // initialised for all versions - for the moment it is only for v5 ! // 7 is the SDD beam test version Int_t ver = this->IsVersion(); if(ver!=5 && ver!=7) return; char *all = strstr(opt,"All"); char *det[3] = {strstr(opt,"SPD"),strstr(opt,"SDD"),strstr(opt,"SSD")}; Int_t nmodules; InitModules(size,nmodules); FillModules(evNumber,bgrev,nmodules,option,filename); //TBranch *branch; AliITSsimulation* sim; //TObjArray *branches=gAlice->TreeD()->GetListOfBranches(); AliITSgeom *geom = GetITSgeom(); Int_t id,module; Int_t first,last; for (id=0;id<kNTYPES;id++) { if (!all && !det[id]) continue; //branch = (TBranch*)branches->UncheckedAt(id); AliITSDetType *iDetType=DetType(id); sim = (AliITSsimulation*)iDetType->GetSimulationModel(); if (!sim) { Error("HitsToDigits","The simulation class was not instantiated!"); exit(1); // or SetDefaultSimulation(); } if(geom) { first = geom->GetStartDet(id); last = geom->GetLastDet(id); } else first=last=0; cout << "det type " << id << " first, last "<< first << last << endl; for(module=first;module<=last;module++) { AliITSmodule *mod = (AliITSmodule *)fITSmodules->At(module); sim->DigitiseModule(mod,module,evNumber); // fills all branches - wasted disk space gAlice->TreeD()->Fill(); ResetDigits(); // try and fill only the branch //branch->Fill(); //ResetDigits(id); } // loop over modules } // loop over detector types ClearModules(); Int_t nentries=(Int_t)gAlice->TreeD()->GetEntries(); cout << "nentries in TreeD" << nentries << endl; char hname[30]; sprintf(hname,"TreeD%d",evNumber); gAlice->TreeD()->Write(hname,TObject::kOverwrite); // reset tree gAlice->TreeD()->Reset(); } //____________________________________________________________________________ void AliITS::DigitsToRecPoints(Int_t evNumber,Int_t lastentry,Option_t *opt) { // cluster finding and reconstruction of space points // the condition below will disappear when the geom class will be // initialised for all versions - for the moment it is only for v5 ! // 7 is the SDD beam test version Int_t ver = this->IsVersion(); if(ver!=5) return; char *all = strstr(opt,"All"); char *det[3] = {strstr(opt,"SPD"),strstr(opt,"SDD"),strstr(opt,"SSD")}; static Bool_t first=kTRUE; if (!TreeC() && first) { MakeTreeC("C"); first=kFALSE; } TTree *treeC=TreeC(); //TBranch *branch; AliITSClusterFinder* rec; //TObjArray *branches=gAlice->TreeR()->GetListOfBranches(); AliITSgeom *geom = GetITSgeom(); Int_t id,module; for (id=0;id<kNTYPES;id++) { if (!all && !det[id]) continue; //branch = (TBranch*)branches->UncheckedAt(id); AliITSDetType *iDetType=DetType(id); rec = (AliITSClusterFinder*)iDetType->GetReconstructionModel(); if (!rec) { Error("DigitsToRecPoints","The cluster finder class was not instantiated!"); exit(1); // or SetDefaultClusterFinders(); } TClonesArray *itsDigits = this->DigitsAddress(id); Int_t first,last; if(geom) { first = geom->GetStartDet(id); last = geom->GetLastDet(id); } else first=last=0; //printf("first last %d %d\n",first,last); for(module=first;module<=last;module++) { this->ResetDigits(); if (all) gAlice->TreeD()->GetEvent(lastentry+module); else gAlice->TreeD()->GetEvent(lastentry+(module-first)); Int_t ndigits = itsDigits->GetEntriesFast(); if (ndigits) rec->FindRawClusters(); gAlice->TreeR()->Fill(); ResetRecPoints(); treeC->Fill(); ResetClusters(); // try and fill only the branch //branch->Fill(); //ResetRecPoints(id); } // loop over modules } // loop over detector types Int_t nentries=(Int_t)gAlice->TreeR()->GetEntries(); Int_t ncentries=(Int_t)treeC->GetEntries(); cout << " nentries ncentries " << nentries << ncentries << endl; char hname[30]; sprintf(hname,"TreeR%d",evNumber); gAlice->TreeR()->Write(hname,TObject::kOverwrite); // reset tree gAlice->TreeR()->Reset(); sprintf(hname,"TreeC%d",evNumber); treeC->Write(hname,TObject::kOverwrite); treeC->Reset(); } //____________________________________________________________________________ void AliITS::HitsToFastRecPoints(Int_t evNumber,Int_t bgrev,Int_t size, Option_t *option,Option_t *opt,Text_t *filename) { // keep galice.root for signal and name differently the file for // background when add! otherwise the track info for signal will be lost ! // the condition below will disappear when the geom class will be // initialised for all versions - for the moment it is only for v5 ! Int_t ver = this->IsVersion(); if(ver!=5) return; char *all = strstr(opt,"All"); char *det[3] = {strstr(opt,"SPD"),strstr(opt,"SDD"),strstr(opt,"SSD")}; Int_t nmodules; InitModules(size,nmodules); FillModules(evNumber,bgrev,nmodules,option,filename); AliITSsimulation* sim; AliITSgeom *geom = GetITSgeom(); TRandom *random=new TRandom[9]; random[0].SetSeed(111); random[1].SetSeed(222); random[2].SetSeed(333); random[3].SetSeed(444); random[4].SetSeed(555); random[5].SetSeed(666); random[6].SetSeed(777); random[7].SetSeed(888); random[8].SetSeed(999); Int_t id,module; for (id=0;id<kNTYPES;id++) { if (!all && !det[id]) continue; AliITSDetType *iDetType=DetType(id); sim = (AliITSsimulation*)iDetType->GetSimulationModel(); if (!sim) { Error("HitsToFastPoints","The simulation class was not instantiated!"); exit(1); // or SetDefaultSimulation(); } Int_t first = geom->GetStartDet(id); Int_t last = geom->GetLastDet(id); for(module=first;module<=last;module++) { AliITSmodule *mod = (AliITSmodule *)fITSmodules->At(module); sim->CreateFastRecPoints(mod,module,random); gAlice->TreeR()->Fill(); ResetRecPoints(); } // loop over modules } // loop over detector types ClearModules(); //Int_t nentries=(Int_t)gAlice->TreeR()->GetEntries(); char hname[30]; sprintf(hname,"TreeR%d",evNumber); gAlice->TreeR()->Write(hname,TObject::kOverwrite); // reset tree gAlice->TreeR()->Reset(); delete [] random; } //________________________________________________________________ AliITStrack AliITS::Tracking(AliITStrack &track, AliITStrack *reference,TObjArray *fastpoints, Int_t **vettid, Bool_t flagvert, AliITSRad *rl ) { //Origin A. Badala' and G.S. Pappalardo: e-mail Angela.Badala@ct.infn.it, Giuseppe.S.Pappalardo@ct.infn.it TList *list= new TList(); AliITStrack tr(track); list->AddLast(&tr); Double_t Pt=(tr).GetPt(); //cout << "\n Pt = " << Pt <<"\n"; AliITStracking obj(list, reference, this, fastpoints,TMath::Abs(Pt),vettid, flagvert, rl); list->Delete(); delete list; Int_t itot=-1; TVector VecTotLabref(18); Int_t lay, k; for(lay=5; lay>=0; lay--) { TVector VecLabref(3); VecLabref=(*reference).GetLabTrack(lay); Float_t ClustZ=(*reference).GetZclusterTrack( lay); //modified il 5-3-2001 for(k=0; k<3; k++) { // {itot++; VecTotLabref(itot)=VecLabref(k);} // modified 5-3-2002 Int_t lpp=(Int_t)VecLabref(k); if(lpp>=0) { TParticle *p=(TParticle*) gAlice->Particle(lpp); Int_t pcode=p->GetPdgCode(); if(pcode==11) VecLabref(k)=p->GetFirstMother(); } itot++; VecTotLabref(itot)=VecLabref(k); if(VecLabref(k)==0. && ClustZ == 0.) VecTotLabref(itot) =-3.; } } Long_t labref; Int_t freq; (*reference).Search(VecTotLabref, labref, freq); if(freq < 5) labref=-labref; (*reference).SetLabel(labref); return *reference; } //________________________________________________________________ void AliITS::DoTracking(Int_t evNumber, Int_t min_t, Int_t max_t, TFile *file, Bool_t flagvert) { // ex macro for tracking ITS printf("begin DoTracking - file %p\n",file); const char *pname="75x40_100x60"; Int_t imax=200,jmax=450; AliITSRad *rl = new AliITSRad(imax,jmax); //cout<<" dopo costruttore AliITSRad\n"; getchar(); struct GoodTrack { Int_t lab,code; Float_t px,py,pz,x,y,z,pxg,pyg,pzg,ptg; Bool_t flag; }; gAlice->GetEvent(0); AliTPC *TPC=(AliTPC*)gAlice->GetDetector("TPC"); AliTPCParam *digp = (AliTPCParam*)file->Get(pname); if (digp!=0) TPC->SetParam(digp); GoodTrack gt[7000]; Int_t ngood=0; ifstream in("itsgood_tracks"); cerr<<"Reading itsgood tracks...\n"; while (in>>gt[ngood].lab>>gt[ngood].code >>gt[ngood].px >>gt[ngood].py>>gt[ngood].pz >>gt[ngood].x >>gt[ngood].y >>gt[ngood].z >>gt[ngood].pxg >>gt[ngood].pyg >>gt[ngood].pzg >>gt[ngood].ptg >>gt[ngood].flag) { ngood++; cerr<<ngood<<'\r'; if (ngood==7000) { cerr<<"Too many good tracks !\n"; break; } } if (!in.eof()) cerr<<"Read error (itsgood_tracks) !\n"; // Load tracks TFile *tf=TFile::Open("tpctracks.root"); if (!tf->IsOpen()) {cerr<<"Can't open tpctracks.root !\n"; return ;} TObjArray tracks(200000); TTree *tracktree=(TTree*)tf->Get("TreeT"); TBranch *tbranch=tracktree->GetBranch("tracks"); Int_t nentr=(Int_t)tracktree->GetEntries(); Int_t kk; for (kk=0; kk<nentr; kk++) { AliTPCtrack *iotrack=new AliTPCtrack; tbranch->SetAddress(&iotrack); tracktree->GetEvent(kk); tracks.AddLast(iotrack); } tf->Close(); Int_t nt = tracks.GetEntriesFast(); cerr<<"Number of found tracks "<<nt<<endl; TVector DataOut(9); Int_t kkk=0; Double_t ptg=0.,pxg=0.,pyg=0.,pzg=0.; ////////////////////////////// good tracks definition in TPC //////////////////////////////// ofstream out1 ("AliITSTrag.out"); Int_t i; for (i=0; i<ngood; i++) out1 << gt[i].ptg << "\n"; out1.close(); TVector vec(5); TTree *TR=gAlice->TreeR(); Int_t nent=(Int_t)TR->GetEntries(); TClonesArray *recPoints = RecPoints(); Int_t numbpoints; Int_t totalpoints=0; Int_t *np = new Int_t[nent]; Int_t **vettid = new Int_t* [nent]; Int_t mod; for (mod=0; mod<nent; mod++) { vettid[mod]=0; this->ResetRecPoints(); //gAlice->TreeR()->GetEvent(mod+1); //first entry in TreeR is empty gAlice->TreeR()->GetEvent(mod); //first entry in TreeR is empty numbpoints = recPoints->GetEntries(); totalpoints+=numbpoints; np[mod] = numbpoints; //cout<<" mod = "<<mod<<" numbpoints = "<<numbpoints<<"\n"; getchar(); vettid[mod] = new Int_t[numbpoints]; Int_t ii; for (ii=0;ii<numbpoints; ii++) *(vettid[mod]+ii)=0; } AliTPCtrack *track; if(min_t < 0) {min_t = 0; max_t = nt-1;} /* ///////////////////////////////// Definition of vertex end its error //////////////////////////// ////////////////////////// In the future it will be given by a method /////////////////////////// Double_t Vx=0.; Double_t Vy=0.; Double_t Vz=0.; Float_t sigmavx=0.0050; // 50 microns Float_t sigmavy=0.0050; // 50 microns Float_t sigmavz=0.010; // 100 microns //Vx+=gRandom->Gaus(0,sigmavx); Vy+=gRandom->Gaus(0,sigmavy); Vz+=gRandom->Gaus(0,sigmavz); TVector vertex(3), ervertex(3) vertex(0)=Vx; vertex(1)=Vy; vertex(2)=Vz; ervertex(0)=sigmavx; ervertex(1)=sigmavy; ervertex(2)=sigmavz; ///////////////////////////////////////////////////////////////////////////////////////////////// */ //TDirectory *savedir=gDirectory; TTree tracktree1("TreeT","Tree with ITS tracks"); AliITSiotrack *iotrack=0; tracktree1.Branch("ITStracks","AliITSiotrack",&iotrack,32000,0); ofstream out ("AliITSTra.out"); Int_t j; for (j=min_t; j<=max_t; j++) { track=(AliTPCtrack*)tracks.UncheckedAt(j); Int_t flaglab=0; if (!track) continue; ////// elimination of not good tracks //////////// Int_t ilab=TMath::Abs(track->GetLabel()); Int_t iii; for (iii=0;iii<ngood;iii++) { //cout<<" ilab, gt[iii].lab = "<<ilab<<" "<<gt[iii].lab<<"\n"; getchar(); if (ilab==gt[iii].lab) { flaglab=1; ptg=gt[iii].ptg; pxg=gt[iii].pxg; pyg=gt[iii].pyg; pzg=gt[iii].pzg; break; } } //cout<<" j flaglab = " <<j<<" "<<flaglab<<"\n"; getchar(); if (!flaglab) continue; //cout<<" j = " <<j<<"\n"; getchar(); /* ////// old propagation to the end of TPC ////////////// Double_t xk=76.; track->PropagateTo(xk); xk-=0.11; track->PropagateTo(xk,42.7,2.27); //C xk-=2.6; track->PropagateTo(xk,36.2,1.98e-3); //C02 xk-=0.051; track->PropagateTo(xk,42.7,2.27); //C /////////////////////////////////////////////////// */ ////// new propagation to the end of TPC ////////////// Double_t xk=77.415; track->PropagateTo(xk, 28.94, 1.204e-3); //Ne xk -=0.01; track->PropagateTo(xk, 44.77, 1.71); //Tedlar xk -=0.04; track->PropagateTo(xk, 44.86, 1.45); //Kevlar xk -=2.0; track->PropagateTo(xk, 41.28, 0.029); //Nomex xk-=16; track->PropagateTo(xk,36.2,1.98e-3); //C02 xk -=0.01; track->PropagateTo(xk, 24.01, 2.7); //Al xk -=0.01; track->PropagateTo(xk, 44.77, 1.71); //Tedlar xk -=0.04; track->PropagateTo(xk, 44.86, 1.45); //Kevlar xk -=0.5; track->PropagateTo(xk, 41.28, 0.029); //Nomex /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////// AliITStrack trackITS(*track); AliITStrack result(*track); AliITStrack primarytrack(*track); /////////////////////////////////////////////////////////////////////////////////////////////// TVector Vgeant(3); Vgeant=result.GetVertex(); // Definition of Dv and Zv for vertex constraint Double_t sigmaDv=0.0050; Double_t sigmaZv=0.010; //Double_t sigmaDv=0.0015; Double_t sigmaZv=0.0015; Double_t uniform= gRandom->Uniform(); Double_t signdv; if(uniform<=0.5) signdv=-1.; else signdv=1.; Double_t Vr=TMath::Sqrt(Vgeant(0)*Vgeant(0)+ Vgeant(1)*Vgeant(1)); Double_t Dv=gRandom->Gaus(signdv*Vr,(Float_t)sigmaDv); Double_t Zv=gRandom->Gaus(Vgeant(2),(Float_t)sigmaZv); //cout<<" Dv e Zv = "<<Dv<<" "<<Zv<<"\n"; trackITS.SetDv(Dv); trackITS.SetZv(Zv); trackITS.SetsigmaDv(sigmaDv); trackITS.SetsigmaZv(sigmaZv); result.SetDv(Dv); result.SetZv(Zv); result.SetsigmaDv(sigmaDv); result.SetsigmaZv(sigmaZv); primarytrack.SetDv(Dv); primarytrack.SetZv(Zv); primarytrack.SetsigmaDv(sigmaDv); primarytrack.SetsigmaZv(sigmaZv); ///////////////////////////////////////////////////////////////////////////////////////////////// primarytrack.PrimaryTrack(rl); TVector d2=primarytrack.Getd2(); TVector tgl2=primarytrack.Gettgl2(); TVector dtgl=primarytrack.Getdtgl(); trackITS.Setd2(d2); trackITS.Settgl2(tgl2); trackITS.Setdtgl(dtgl); result.Setd2(d2); result.Settgl2(tgl2); result.Setdtgl(dtgl); /* trackITS.SetVertex(vertex); trackITS.SetErrorVertex(ervertex); result.SetVertex(vertex); result.SetErrorVertex(ervertex); */ Tracking(trackITS,&result,recPoints,vettid, flagvert,rl); // cout<<" progressive track number = "<<j<<"\r"; // cout<<j<<"\r"; // cout<<" progressive track number = "<<j<<"\n"; Long_t labITS=result.GetLabel(); // cout << " ITS track label = " << labITS << "\n"; int lab=track->GetLabel(); // cout << " TPC track label = " << lab <<"\n"; //result.GetClusters(); getchar(); //to print the cluster matrix //propagation to vertex Double_t rbeam=3.; result.Propagation(rbeam); TMatrix *cov; cov=&result.GetCMatrix(); Double_t pt=TMath::Abs(result.GetPt()); Double_t Dr=result.GetD(); Double_t Z=result.GetZ(); Double_t tgl=result.GetTgl(); Double_t C=result.GetC(); Double_t Cy=C/2.; Double_t Dz=Z-(tgl/Cy)*TMath::ASin(result.arga(rbeam)); Dz-=Vgeant(2); // cout<<" Dr e dz alla fine = "<<Dr<<" "<<Dz<<"\n"; getchar(); Double_t phi=result.Getphi(); Double_t phivertex = phi - TMath::ASin(result.argA(rbeam)); Double_t duepi=2.*TMath::Pi(); if(phivertex>duepi) phivertex-=duepi; if(phivertex<0.) phivertex+=duepi; Double_t Dtot=TMath::Sqrt(Dr*Dr+Dz*Dz); ////////////////////////////////////////////////////////////////////////////////////////// Int_t NumofCluster, idmodule,idpoint; NumofCluster=result.GetNumClust(); if(NumofCluster >=5) { AliITSiotrack outtrack; iotrack=&outtrack; iotrack->SetStatePhi(phi); iotrack->SetStateZ(Z); iotrack->SetStateD(Dr); iotrack->SetStateTgl(tgl); iotrack->SetStateC(C); Double_t radius=result.Getrtrack(); iotrack->SetRadius(radius); Int_t charge; if(C>0.) charge=-1; else charge=1; iotrack->SetCharge(charge); iotrack->SetCovMatrix(cov); Double_t px=pt*TMath::Cos(phi); Double_t py=pt*TMath::Sin(phi); Double_t pz=pt*tgl; Double_t xtrack=Dr*TMath::Sin(phi); Double_t ytrack=Dr*TMath::Cos(phi); Double_t ztrack=Dz+Vgeant(2); iotrack->SetPx(px); iotrack->SetPy(py); iotrack->SetPz(pz); iotrack->SetX(xtrack); iotrack->SetY(ytrack); iotrack->SetZ(ztrack); iotrack->SetLabel(labITS); Int_t il; for(il=0;il<6; il++){ iotrack->SetIdPoint(il,result.GetIdPoint(il)); iotrack->SetIdModule(il,result.GetIdModule(il)); } tracktree1.Fill(); //cout<<" labITS = "<<labITS<<"\n"; //cout<<" phi z Dr tgl C = "<<phi<<" "<<Z<<" "<<Dr<<" "<<tgl<<" "<<C<<"\n"; getchar(); DataOut(kkk) = ptg; kkk++; DataOut(kkk)=labITS; kkk++; DataOut(kkk)=lab; kkk++; for (il=0;il<6;il++) { idpoint=result.GetIdPoint(il); idmodule=result.GetIdModule(il); *(vettid[idmodule]+idpoint)=1; iotrack->SetIdPoint(il,idpoint); iotrack->SetIdModule(il,idmodule); } // cout<<" +++++++++++++ pt e ptg = "<<pt<<" "<<ptg<<" ++++++++++\n"; Double_t difpt= (pt-ptg)/ptg*100.; DataOut(kkk)=difpt; kkk++; Double_t lambdag=TMath::ATan(pzg/ptg); Double_t lam=TMath::ATan(tgl); Double_t diflam = (lam - lambdag)*1000.; DataOut(kkk) = diflam; kkk++; Double_t phig=TMath::ATan(pyg/pxg); Double_t phi=phivertex; Double_t difphi = (phi - phig)*1000.; DataOut(kkk)=difphi; kkk++; DataOut(kkk)=Dtot*1.e4; kkk++; DataOut(kkk)=Dr*1.e4; kkk++; DataOut(kkk)=Dz*1.e4; kkk++; Int_t r; for (r=0; r<9; r++) { out<<DataOut(r)<<" ";} out<<"\n"; kkk=0; } // end if on NumofCluster //gObjectTable->Print(); // stampa memoria } // end for (int j=min_t; j<=max_t; j++) out.close(); static Bool_t first=kTRUE; static TFile *tfile; if(first) { tfile=new TFile("itstracks.root","RECREATE"); //cout<<"I have opened itstracks.root file "<<endl; } first=kFALSE; tfile->cd(); tfile->ls(); char hname[30]; sprintf(hname,"TreeT%d",evNumber); tracktree1.Write(hname); TTree *fAli=gAlice->TreeK(); TFile *fileAli=0; if (fAli) fileAli =fAli->GetCurrentFile(); fileAli->cd(); //////////////////////////////////////////////////////////////////////////////////////////////// printf("delete vectors\n"); if(np) delete [] np; if(vettid) delete [] vettid; } Some vector dimensions increased to cope with full events /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.37 2001/03/07 12:36:35 barbera A change added in the tracking part to manage delta rays Revision 1.36 2001/03/02 19:44:11 barbera modified to taking into account new version tracking v1 Revision 1.35 2001/02/28 18:16:46 mariana Make the code compatible with the new AliRun Revision 1.34 2001/02/11 15:51:39 mariana Set protection in MakeBranch Revision 1.33 2001/02/10 22:26:39 mariana Move the initialization of the containers for raw clusters in MakeTreeC() Revision 1.32 2001/02/08 23:55:31 nilsen Removed fMajor/MinorVersion variables in favor of variables in derived classes. Set arrays char *det[3] = {"SPD","SDD","SSD"} as const. Revision 1.31 2001/02/02 23:57:28 nilsen Added include file that are no londer included in AliITSgeom.h Revision 1.30 2001/01/30 09:23:13 hristov Streamers removed (R.Brun) Revision 1.29 2001/01/26 20:01:09 hristov Major upgrade of AliRoot code Revision 1.28 2000/12/18 14:02:00 barbera new version of the ITS tracking to take into account the new TPC track parametrization Revision 1.27 2000/12/08 13:49:27 barbera Hidden declaration in a for loop removed to be compliant with HP-UX compiler Revision 1.26 2000/11/27 13:12:13 barbera New version containing the files for tracking Revision 1.25 2000/11/12 22:38:05 barbera Added header file for the SPD Bari model Revision 1.24 2000/10/09 22:18:12 barbera Bug fixes from MAriana to le AliITStest.C run correctly Revision 1.23 2000/10/05 20:47:42 nilsen fixed dependencies of include files. Tryed but failed to get a root automaticly generates streamer function to work. Modified SetDefaults. Revision 1.9.2.15 2000/10/04 16:56:40 nilsen Needed to include stdlib.h ======= Revision 1.22 2000/10/04 19:45:52 barbera Corrected by F. Carminati for v3.04 Revision 1.21 2000/10/02 21:28:08 fca Removal of useless dependecies via forward declarations Revision 1.20 2000/10/02 16:31:39 barbera General code clean-up Revision 1.9.2.14 2000/10/02 15:43:51 barbera General code clean-up (e.g., printf -> cout) Revision 1.19 2000/09/22 12:13:25 nilsen Patches and updates for fixes to this and other routines. Revision 1.18 2000/07/12 05:32:20 fca Correcting several syntax problem with static members Revision 1.17 2000/07/10 16:07:18 fca Release version of ITS code Revision 1.9.2.3 2000/02/02 13:42:09 barbera fixed AliITS.cxx for new AliRun structure. Added ITS hits list to list of hits which will have their track numbers updated Revision 1.9.2.2 2000/01/23 03:03:13 nilsen //fixed FillModule. Removed fi(fabs(xl)<dx.... Revision 1.9.2.1 2000/01/12 19:03:32 nilsen This is the version of the files after the merging done in December 1999. See the ReadMe110100.txt file for details Revision 1.9 1999/11/14 14:33:25 fca Correct problems with distructors and pointers, thanks to I.Hrivnacova Revision 1.8 1999/09/29 09:24:19 fca Introduction of the Copyright and cvs Log */ /////////////////////////////////////////////////////////////////////////////// // // An overview of the basic philosophy of the ITS code development // and analysis is show in the figure below. //Begin_Html /* <img src="picts/ITS/ITS_Analysis_schema.gif"> </pre> <br clear=left> <font size=+2 color=red> <p>Roberto Barbera is in charge of the ITS Offline code (1999). <a href="mailto:roberto.barbera@ct.infn.it">Roberto Barbera</a>. </font> <pre> */ //End_Html // // AliITS. Inner Traking System base class. // This class contains the base procedures for the Inner Tracking System // //Begin_Html /* <img src="picts/ITS/AliITS_Class_Diagram.gif"> </pre> <br clear=left> <font size=+2 color=red> <p>This show the class diagram of the different elements that are part of the AliITS class. </font> <pre> */ //End_Html // // Version: 0 // Written by Rene Brun, Federico Carminati, and Roberto Barbera // // Version: 1 // Modified and documented by Bjorn S. Nilsen // July 11 1999 // // Version: 2 // Modified and documented by A. Bologna // October 18 1999 // // AliITS is the general base class for the ITS. Also see AliDetector for // futher information. // /////////////////////////////////////////////////////////////////////////////// #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include <stdlib.h> #include <TMath.h> #include <TRandom.h> #include <TBranch.h> #include <TVector.h> #include <TClonesArray.h> #include <TROOT.h> #include <TObjectTable.h> #include <TFile.h> #include <TTree.h> #include <TString.h> #include <TParticle.h> #include "AliRun.h" #include "AliITS.h" #include "AliITSMap.h" #include "AliITSDetType.h" #include "AliITSClusterFinder.h" //#include "AliITSsimulation.h" #include "AliITSsimulationSPD.h" #include "AliITSsimulationSDD.h" #include "AliITSsimulationSSD.h" #include "AliITSresponse.h" #include "AliITSsegmentationSPD.h" #include "AliITSresponseSPD.h" #include "AliITSresponseSPDbari.h" #include "AliITSsegmentationSDD.h" #include "AliITSresponseSDD.h" #include "AliITSsegmentationSSD.h" #include "AliITSresponseSSD.h" #include "AliITShit.h" #include "AliITSgeom.h" #include "AliITSdigit.h" #include "AliITSmodule.h" #include "AliITSRecPoint.h" #include "AliITSRawCluster.h" #include "AliMC.h" #include "stdlib.h" #include "AliITStrack.h" #include "AliITSiotrack.h" #include "AliITStracking.h" #include "AliITSRad.h" #include "../TPC/AliTPC.h" #include "../TPC/AliTPCParam.h" ClassImp(AliITS) //_____________________________________________________________________________ AliITS::AliITS() : AliDetector() { // // Default initialiser for ITS // The default constructor of the AliITS class. In addition to // creating the AliITS class it zeros the variables fIshunt (a member // of AliDetector class), fEuclidOut, and fIdN, and zeros the pointers // fITSpoints, fIdSens, and fIdName. The AliDetector default constructor // is also called. // fIshunt = 0; fEuclidOut = 0; fNDetTypes = kNTYPES; fIdN = 0; fIdName = 0; fIdSens = 0; fITSmodules = 0; // fDetTypes = 0; // fDtype = 0; fNdtype = 0; fCtype = 0; fNctype = 0; fRecPoints = 0; fNRecPoints = 0; fTreeC = 0; // fITSgeom=0; } //_____________________________________________________________________________ AliITS::AliITS(const char *name, const char *title):AliDetector(name,title){ // // Default initialiser for ITS // The constructor of the AliITS class. In addition to creating the // AliITS class, it allocates memory for the TClonesArrays fHits and // fDigits, and for the TObjArray fITSpoints. It also zeros the variables // fIshunt (a member of AliDetector class), fEuclidOut, and fIdN, and zeros // the pointers fIdSens and fIdName. To help in displaying hits via the ROOT // macro display.C AliITS also sets the marker color to red. The variables // passes with this constructor, const char *name and *title, are used by // the constructor of AliDetector class. See AliDetector class for a // description of these parameters and its constructor functions. // fHits = new TClonesArray("AliITShit", 1560); gAlice->AddHitList(fHits); fNDetTypes = kNTYPES; fNdtype = new Int_t[kNTYPES]; fDtype = new TObjArray(kNTYPES); fNctype = new Int_t[kNTYPES]; fCtype = new TObjArray(kNTYPES); fRecPoints = 0; fNRecPoints = 0; fTreeC = 0; fITSmodules = 0; fIshunt = 0; fEuclidOut = 0; fIdN = 0; fIdName = 0; fIdSens = 0; fDetTypes = new TObjArray(kNTYPES); Int_t i; for(i=0;i<kNTYPES;i++) { (*fDetTypes)[i]=new AliITSDetType(); fNdtype[i]=0; fNctype[i]=0; } // SetMarkerColor(kRed); fITSgeom=0; } //___________________________________________________________________________ AliITS::AliITS(AliITS &source){ // copy constructor if(this==&source) return; Error("AliITS::Copy constructor", "You are not allowed to make a copy of the AliITS"); exit(1); } //____________________________________________________________________________ AliITS& AliITS::operator=(AliITS &source){ // assignment operator if(this==&source) return *this; Error("AliITS::operator=", "You are not allowed to make a copy of the AliITS"); exit(1); return *this; //fake return } //____________________________________________________________________________ void AliITS::ClearModules(){ //clear the modules TObjArray if(fITSmodules) fITSmodules->Delete(); } //_____________________________________________________________________________ AliITS::~AliITS(){ // // Default distructor for ITS // The default destructor of the AliITS class. In addition to deleting // the AliITS class it deletes the memory pointed to by the fHits, fDigits, // fIdSens, fIdName, and fITSpoints. // delete fHits; delete fDigits; delete fRecPoints; // delete fIdName; // TObjArray of TObjStrings if(fIdName!=0) delete[] fIdName; // Array of TStrings if(fIdSens!=0) delete[] fIdSens; if(fITSmodules!=0) { this->ClearModules(); delete fITSmodules; }// end if fITSmodules!=0 // if(fDtype) { fDtype->Delete(); delete fDtype; } delete [] fNdtype; if (fCtype) { fCtype->Delete(); delete fCtype; } delete [] fNctype; // if (fDetTypes) { fDetTypes->Delete(); delete fDetTypes; } if (fTreeC) delete fTreeC; if (fITSgeom) delete fITSgeom; } //___________________________________________ AliITSDetType* AliITS::DetType(Int_t id) { //return pointer to id detector type return ((AliITSDetType*) (*fDetTypes)[id]); } //___________________________________________ void AliITS::SetClasses(Int_t id, const char *digit, const char *cluster) { //set the digit and cluster classes to be used for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->ClassNames(digit,cluster); } //___________________________________________ void AliITS::SetResponseModel(Int_t id, AliITSresponse *response) { //set the response model for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->ResponseModel(response); } //___________________________________________ void AliITS::SetSegmentationModel(Int_t id, AliITSsegmentation *seg) { //set the segmentation model for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->SegmentationModel(seg); } //___________________________________________ void AliITS::SetSimulationModel(Int_t id, AliITSsimulation *sim) { //set the simulation model for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->SimulationModel(sim); } //___________________________________________ void AliITS::SetReconstructionModel(Int_t id, AliITSClusterFinder *reconst) { //set the cluster finder model for the id detector type ((AliITSDetType*) (*fDetTypes)[id])->ReconstructionModel(reconst); } //_____________________________________________________________________________ void AliITS::AddHit(Int_t track, Int_t *vol, Float_t *hits){ // // Add an ITS hit // The function to add information to the AliITShit class. See the // AliITShit class for a full description. This function allocates the // necessary new space for the hit information and passes the variable // track, and the pointers *vol and *hits to the AliITShit constructor // function. // TClonesArray &lhits = *fHits; new(lhits[fNhits++]) AliITShit(fIshunt,track,vol,hits); } //_____________________________________________________________________________ void AliITS::AddRealDigit(Int_t id, Int_t *digits) { // add a real digit - as coming from data TClonesArray &ldigits = *((TClonesArray*)(*fDtype)[id]); new(ldigits[fNdtype[id]++]) AliITSdigit(digits); } //_____________________________________________________________________________ void AliITS::AddSimDigit(Int_t id, AliITSdigit *d) { // add a simulated digit TClonesArray &ldigits = *((TClonesArray*)(*fDtype)[id]); switch(id) { case 0: new(ldigits[fNdtype[id]++]) AliITSdigitSPD(*((AliITSdigitSPD*)d)); break; case 1: new(ldigits[fNdtype[id]++]) AliITSdigitSDD(*((AliITSdigitSDD*)d)); break; case 2: new(ldigits[fNdtype[id]++]) AliITSdigitSSD(*((AliITSdigitSSD*)d)); break; } } //_____________________________________________________________________________ void AliITS::AddSimDigit(Int_t id,Float_t phys,Int_t *digits,Int_t *tracks,Int_t *hits,Float_t *charges){ // add a simulated digit to the list TClonesArray &ldigits = *((TClonesArray*)(*fDtype)[id]); switch(id) { case 0: new(ldigits[fNdtype[id]++]) AliITSdigitSPD(digits,tracks,hits); break; case 1: new(ldigits[fNdtype[id]++]) AliITSdigitSDD(phys,digits,tracks,hits,charges); break; case 2: new(ldigits[fNdtype[id]++]) AliITSdigitSSD(digits,tracks,hits); break; } } //_____________________________________________________________________________ void AliITS::AddCluster(Int_t id, AliITSRawCluster *c) { // add a cluster to the list TClonesArray &lcl = *((TClonesArray*)(*fCtype)[id]); switch(id) { case 0: new(lcl[fNctype[id]++]) AliITSRawClusterSPD(*((AliITSRawClusterSPD*)c)); break; case 1: new(lcl[fNctype[id]++]) AliITSRawClusterSDD(*((AliITSRawClusterSDD*)c)); break; case 2: new(lcl[fNctype[id]++]) AliITSRawClusterSSD(*((AliITSRawClusterSSD*)c)); break; } } //_____________________________________________________________________________ void AliITS::AddRecPoint(const AliITSRecPoint &r) { // // Add a reconstructed space point to the list // TClonesArray &lrecp = *fRecPoints; new(lrecp[fNRecPoints++]) AliITSRecPoint(r); } //____________________________________________ void AliITS::ResetDigits() { // // Reset number of digits and the digits array for the ITS detector // if (!fDtype) return; Int_t i; for (i=0;i<kNTYPES;i++ ) { if ((*fDtype)[i]) ((TClonesArray*)(*fDtype)[i])->Clear(); if (fNdtype) fNdtype[i]=0; } } //____________________________________________ void AliITS::ResetDigits(Int_t i) { // // Reset number of digits and the digits array for this branch // if ((*fDtype)[i]) ((TClonesArray*)(*fDtype)[i])->Clear(); if (fNdtype) fNdtype[i]=0; } //____________________________________________ void AliITS::ResetClusters() { // // Reset number of clusters and the clusters array for ITS // Int_t i; for (i=0;i<kNTYPES;i++ ) { if ((*fCtype)[i]) ((TClonesArray*)(*fCtype)[i])->Clear(); if (fNctype) fNctype[i]=0; } } //____________________________________________ void AliITS::ResetClusters(Int_t i) { // // Reset number of clusters and the clusters array for this branch // if ((*fCtype)[i]) ((TClonesArray*)(*fCtype)[i])->Clear(); if (fNctype) fNctype[i]=0; } //____________________________________________ void AliITS::ResetRecPoints() { // // Reset number of rec points and the rec points array // if (fRecPoints) fRecPoints->Clear(); fNRecPoints = 0; } //_____________________________________________________________________________ Int_t AliITS::DistancetoPrimitive(Int_t , Int_t ){ // // Distance from mouse to ITS on the screen. Dummy routine // A dummy routine used by the ROOT macro display.C to allow for the // use of the mouse (pointing device) in the macro. In general this should // never be called. If it is it returns the number 9999 for any value of // x and y. // return 9999; } //_____________________________________________________________________________ void AliITS::Init(){ // // Initialise ITS after it has been built // This routine initializes the AliITS class. It is intended to be called // from the Init function in AliITSv?. Besides displaying a banner // indicating that it has been called it initializes the array fIdSens // and sets the default segmentation, response, digit and raw cluster classes // Therefore it should be called after a call to CreateGeometry. // Int_t i; // SetDefaults(); // Array of TStrings for(i=0;i<fIdN;i++) fIdSens[i] = gMC->VolId(fIdName[i]); // } //_____________________________________________________________________________ void AliITS::SetDefaults() { // sets the default segmentation, response, digit and raw cluster classes printf("SetDefaults\n"); AliITSDetType *iDetType; //SPD iDetType=DetType(0); if (!iDetType->GetSegmentationModel()) { AliITSsegmentationSPD *seg0=new AliITSsegmentationSPD(fITSgeom); SetSegmentationModel(0,seg0); } if (!iDetType->GetResponseModel()) { SetResponseModel(0,new AliITSresponseSPD()); } // set digit and raw cluster classes to be used const char *kData0=(iDetType->GetResponseModel())->DataType(); if (strstr(kData0,"real")) { iDetType->ClassNames("AliITSdigit","AliITSRawClusterSPD"); } else iDetType->ClassNames("AliITSdigitSPD","AliITSRawClusterSPD"); // SDD // iDetType=DetType(1); if (!iDetType->GetResponseModel()) { SetResponseModel(1,new AliITSresponseSDD()); } AliITSresponse *resp1=iDetType->GetResponseModel(); if (!iDetType->GetSegmentationModel()) { AliITSsegmentationSDD *seg1=new AliITSsegmentationSDD(fITSgeom,resp1); SetSegmentationModel(1,seg1); } const char *kData1=(iDetType->GetResponseModel())->DataType(); const char *kopt=iDetType->GetResponseModel()->ZeroSuppOption(); if ((!strstr(kopt,"2D")) && (!strstr(kopt,"1D")) || strstr(kData1,"real") ) { iDetType->ClassNames("AliITSdigit","AliITSRawClusterSDD"); } else iDetType->ClassNames("AliITSdigitSDD","AliITSRawClusterSDD"); // SSD iDetType=DetType(2); if (!iDetType->GetSegmentationModel()) { AliITSsegmentationSSD *seg2=new AliITSsegmentationSSD(fITSgeom); SetSegmentationModel(2,seg2); } if (!iDetType->GetResponseModel()) { SetResponseModel(2,new AliITSresponseSSD()); } const char *kData2=(iDetType->GetResponseModel())->DataType(); if (strstr(kData2,"real")) { iDetType->ClassNames("AliITSdigit","AliITSRawClusterSSD"); } else iDetType->ClassNames("AliITSdigitSSD","AliITSRawClusterSSD"); if (kNTYPES>3) { Warning("SetDefaults","Only the three basic detector types are initialised!"); } } //_____________________________________________________________________________ void AliITS::SetDefaultSimulation() { // to be written } //_____________________________________________________________________________ void AliITS::SetDefaultClusterFinders() { // to be written } //_____________________________________________________________________________ void AliITS::MakeTreeC(Option_t *option) { // create a separate tree to store the clusters cout << "AliITS::MakeTreeC" << endl; char *optC = strstr(option,"C"); if (optC && !fTreeC) fTreeC = new TTree("TC","Clusters in ITS"); else return; Int_t buffersize = 4000; char branchname[30]; const char *det[3] = {"SPD","SDD","SSD"}; char digclass[40]; char clclass[40]; // one branch for Clusters per type of detector Int_t i; for (i=0; i<kNTYPES ;i++) { AliITSDetType *iDetType=DetType(i); iDetType->GetClassNames(digclass,clclass); // clusters (*fCtype)[i] = new TClonesArray(clclass,10000); if (kNTYPES==3) sprintf(branchname,"%sClusters%s",GetName(),det[i]); else sprintf(branchname,"%sClusters%d",GetName(),i+1); if (fCtype && fTreeC) { TreeC()->Branch(branchname,&((*fCtype)[i]), buffersize); cout << "Making Branch " << branchname; cout << " for Clusters of detector type " << i+1 << endl; } } } //_____________________________________________________________________________ void AliITS::GetTreeC(Int_t event) { cout << "AliITS::GetTreeC" << endl; // get the clusters tree for this event and set the branch address char treeName[20]; char branchname[30]; const char *det[3] = {"SPD","SDD","SSD"}; ResetClusters(); if (fTreeC) { delete fTreeC; } sprintf(treeName,"TreeC%d",event); fTreeC = (TTree*)gDirectory->Get(treeName); TBranch *branch; if (fTreeC) { Int_t i; for (i=0; i<kNTYPES; i++) { if (kNTYPES==3) sprintf(branchname,"%sClusters%s",GetName(),det[i]); else sprintf(branchname,"%sClusters%d",GetName(),i+1); if (fCtype) { branch = fTreeC->GetBranch(branchname); if (branch) branch->SetAddress(&((*fCtype)[i])); } } } else { Error("AliITS::GetTreeC", "cannot find Clusters Tree for event:%d\n",event); } } //_____________________________________________________________________________ void AliITS::MakeBranch(Option_t* option, char *file) { // // Creates Tree branches for the ITS. // // Int_t buffersize = 4000; char branchname[30]; sprintf(branchname,"%s",GetName()); AliDetector::MakeBranch(option,file); char *cD = strstr(option,"D"); char *cR = strstr(option,"R"); if (cD) { // // one branch for digits per type of detector // const char *det[3] = {"SPD","SDD","SSD"}; char digclass[40]; char clclass[40]; Int_t i; for (i=0; i<kNTYPES ;i++) { AliITSDetType *iDetType=DetType(i); iDetType->GetClassNames(digclass,clclass); // digits if(!((*fDtype)[i])) (*fDtype)[i] = new TClonesArray(digclass,10000); else ResetDigits(i); } for (i=0; i<kNTYPES ;i++) { if (kNTYPES==3) sprintf(branchname,"%sDigits%s",GetName(),det[i]); else sprintf(branchname,"%sDigits%d",GetName(),i+1); if (fDtype && gAlice->TreeD()) { gAlice->MakeBranchInTree(gAlice->TreeD(), branchname, &((*fDtype)[i]), buffersize, file); cout << "Making Branch " << branchname; cout << " for digits of type "<< i+1 << endl; } } } if (cR) { // // only one branch for rec points for all detector types // sprintf(branchname,"%sRecPoints",GetName()); if(!fRecPoints) fRecPoints=new TClonesArray("AliITSRecPoint",10000); if (fRecPoints && gAlice->TreeR()) { gAlice->MakeBranchInTree(gAlice->TreeR(), branchname, &fRecPoints, buffersize, file) ; cout << "Making Branch " << branchname; cout << " for reconstructed space points" << endl; } } } //___________________________________________ void AliITS::SetTreeAddress() { // Set branch address for the Trees. char branchname[30]; AliDetector::SetTreeAddress(); const char *det[3] = {"SPD","SDD","SSD"}; TBranch *branch; TTree *treeD = gAlice->TreeD(); TTree *treeR = gAlice->TreeR(); Int_t i; if (treeD) { for (i=0; i<kNTYPES; i++) { if (kNTYPES==3) sprintf(branchname,"%sDigits%s",GetName(),det[i]); else sprintf(branchname,"%sDigits%d",GetName(),i+1); if (fDtype) { branch = treeD->GetBranch(branchname); if (branch) branch->SetAddress(&((*fDtype)[i])); } } } if (treeR) { sprintf(branchname,"%sRecPoints",GetName()); branch = treeR->GetBranch(branchname); if (branch) branch->SetAddress(&fRecPoints); } } //____________________________________________________________________________ void AliITS::InitModules(Int_t size,Int_t &nmodules){ //initialize the modules array if(fITSmodules){ fITSmodules->Delete(); delete fITSmodules; } Int_t nl,indexMAX,index; if(size<=0){ // default to using data stored in AliITSgeom if(fITSgeom==0) { Error("AliITS::InitModules", "in AliITS::InitModule fITSgeom not defined\n"); return; } // end if fITSgeom==0 nl = fITSgeom->GetNlayers(); indexMAX = fITSgeom->GetModuleIndex(nl,fITSgeom->GetNladders(nl), fITSgeom->GetNdetectors(nl))+1; nmodules = indexMAX; fITSmodules = new TObjArray(indexMAX); for(index=0;index<indexMAX;index++){ fITSmodules->AddAt( new AliITSmodule(index),index); } // end for index }else{ fITSmodules = new TObjArray(size); for(index=0;index<size;index++) { fITSmodules->AddAt( new AliITSmodule(index),index); } nmodules = size; } // end i size<=0 } //____________________________________________________________________________ void AliITS::FillModules(Int_t evnt,Int_t bgrev,Int_t nmodules,Option_t *option,Text_t *filename){ // fill the modules with the sorted by module hits; add hits from background // if option=Add static TTree *trH1; //Tree with background hits static TClonesArray *fHits2; //List of hits for one track only static Bool_t first=kTRUE; static TFile *file; char *addBgr = strstr(option,"Add"); if (addBgr ) { if(first) { cout<<"filename "<<filename<<endl; file=new TFile(filename); cout<<"I have opened "<<filename<<" file "<<endl; fHits2 = new TClonesArray("AliITShit",1000 ); } first=kFALSE; file->cd(); file->ls(); // Get Hits Tree header from file if(fHits2) fHits2->Clear(); if(trH1) delete trH1; trH1=0; char treeName[20]; sprintf(treeName,"TreeH%d",bgrev); trH1 = (TTree*)gDirectory->Get(treeName); //printf("TrH1 %p of treename %s for event %d \n",trH1,treeName,bgrev); if (!trH1) { Error("AliITS::FillModules", "cannot find Hits Tree for event:%d\n",bgrev); } // Set branch addresses TBranch *branch; char branchname[20]; sprintf(branchname,"%s",GetName()); if (trH1 && fHits2) { branch = trH1->GetBranch(branchname); if (branch) branch->SetAddress(&fHits2); } // test //Int_t ntracks1 =(Int_t)TrH1->GetEntries(); //printf("background - ntracks1 - %d\n",ntracks1); } //Int_t npart = gAlice->GetEvent(evnt); //if(npart<=0) return; TClonesArray *itsHits = this->Hits(); Int_t lay,lad,det,index; AliITShit *itsHit=0; AliITSmodule *mod=0; TTree *iTH = gAlice->TreeH(); Int_t ntracks =(Int_t) iTH->GetEntries(); Int_t t,h; for(t=0; t<ntracks; t++){ gAlice->ResetHits(); iTH->GetEvent(t); Int_t nhits = itsHits->GetEntriesFast(); //printf("nhits %d\n",nhits); if (!nhits) continue; for(h=0; h<nhits; h++){ itsHit = (AliITShit *)itsHits->UncheckedAt(h); itsHit->GetDetectorID(lay,lad,det); // temporarily index=det-1 !!! if(fITSgeom) index = fITSgeom->GetModuleIndex(lay,lad,det); else index=det-1; // mod = this->GetModule(index); mod->AddHit(itsHit,t,h); } // end loop over hits } // end loop over tracks // open the file with background if (addBgr ) { Int_t track,i; ntracks =(Int_t)trH1->GetEntries(); //printf("background - ntracks1 %d\n",ntracks); //printf("background - Start loop over tracks \n"); // Loop over tracks for (track=0; track<ntracks; track++) { if (fHits2) fHits2->Clear(); trH1->GetEvent(track); // Loop over hits for(i=0;i<fHits2->GetEntriesFast();++i) { itsHit=(AliITShit*) (*fHits2)[i]; itsHit->GetDetectorID(lay,lad,det); // temporarily index=det-1 !!! if(fITSgeom) index = fITSgeom->GetModuleIndex(lay,lad,det); else index=det-1; // mod = this->GetModule(index); mod->AddHit(itsHit,track,i); } // end loop over hits } // end loop over tracks TTree *fAli=gAlice->TreeK(); TFile *fileAli=0; if (fAli) fileAli =fAli->GetCurrentFile(); fileAli->cd(); } // end if add //gObjectTable->Print(); } //____________________________________________________________________________ void AliITS::SDigits2Digits() { AliITSgeom *geom = GetITSgeom(); // SPD AliITSDetType *iDetType; iDetType=DetType(0); AliITSsegmentationSPD *seg0=(AliITSsegmentationSPD*)iDetType->GetSegmentationModel(); AliITSresponseSPD *res0 = (AliITSresponseSPD*)iDetType->GetResponseModel(); AliITSsimulationSPD *sim0=new AliITSsimulationSPD(seg0,res0); SetSimulationModel(0,sim0); // test // printf("SPD dimensions %f %f \n",seg0->Dx(),seg0->Dz()); // printf("SPD npixels %d %d \n",seg0->Npz(),seg0->Npx()); // printf("SPD pitches %d %d \n",seg0->Dpz(0),seg0->Dpx(0)); // end test // // SDD //Set response functions Float_t baseline = 10.; Float_t noise = 1.75; // SDD compression param: 2 fDecrease, 2fTmin, 2fTmax or disable, 2 fTolerance iDetType=DetType(1); AliITSresponseSDD *res1 = (AliITSresponseSDD*)iDetType->GetResponseModel(); if (!res1) { res1=new AliITSresponseSDD(); SetResponseModel(1,res1); } res1->SetMagicValue(900.); Float_t maxadc = res1->MaxAdc(); Float_t topValue = res1->MagicValue(); Float_t norm = maxadc/topValue; Float_t fCutAmp = baseline + 2.*noise; fCutAmp *= norm; Int_t cp[8]={0,0,(int)fCutAmp,(int)fCutAmp,0,0,0,0}; //1D //res1->SetZeroSupp("2D"); res1->SetZeroSupp("1D"); res1->SetNoiseParam(noise,baseline); res1->SetDo10to8(kTRUE); res1->SetCompressParam(cp); res1->SetMinVal(4); res1->SetDiffCoeff(3.6,40.); //res1->SetMagicValue(96.95); AliITSsegmentationSDD *seg1=(AliITSsegmentationSDD*)iDetType->GetSegmentationModel(); if (!seg1) { seg1 = new AliITSsegmentationSDD(geom,res1); SetSegmentationModel(1,seg1); } AliITSsimulationSDD *sim1=new AliITSsimulationSDD(seg1,res1); sim1->SetDoFFT(1); sim1->SetCheckNoise(kFALSE); SetSimulationModel(1,sim1); // SSD iDetType=DetType(2); AliITSsegmentationSSD *seg2=(AliITSsegmentationSSD*)iDetType->GetSegmentationModel(); AliITSresponseSSD *res2 = (AliITSresponseSSD*)iDetType->GetResponseModel(); res2->SetSigmaSpread(3.,2.); AliITSsimulationSSD *sim2=new AliITSsimulationSSD(seg2,res2); SetSimulationModel(2,sim2); cerr<<"Digitizing ITS...\n"; TStopwatch timer; timer.Start(); HitsToDigits(0,0,-1," ","All"," "); timer.Stop(); timer.Print(); delete sim0; delete sim1; delete sim2; } //____________________________________________________________________________ void AliITS::HitsToDigits(Int_t evNumber,Int_t bgrev,Int_t size, Option_t *option, Option_t *opt,Text_t *filename) { // keep galice.root for signal and name differently the file for // background when add! otherwise the track info for signal will be lost ! // the condition below will disappear when the geom class will be // initialised for all versions - for the moment it is only for v5 ! // 7 is the SDD beam test version Int_t ver = this->IsVersion(); if(ver!=5 && ver!=7) return; char *all = strstr(opt,"All"); char *det[3] = {strstr(opt,"SPD"),strstr(opt,"SDD"),strstr(opt,"SSD")}; Int_t nmodules; InitModules(size,nmodules); FillModules(evNumber,bgrev,nmodules,option,filename); //TBranch *branch; AliITSsimulation* sim; //TObjArray *branches=gAlice->TreeD()->GetListOfBranches(); AliITSgeom *geom = GetITSgeom(); Int_t id,module; Int_t first,last; for (id=0;id<kNTYPES;id++) { if (!all && !det[id]) continue; //branch = (TBranch*)branches->UncheckedAt(id); AliITSDetType *iDetType=DetType(id); sim = (AliITSsimulation*)iDetType->GetSimulationModel(); if (!sim) { Error("HitsToDigits","The simulation class was not instantiated!"); exit(1); // or SetDefaultSimulation(); } if(geom) { first = geom->GetStartDet(id); last = geom->GetLastDet(id); } else first=last=0; cout << "det type " << id << " first, last "<< first << last << endl; for(module=first;module<=last;module++) { AliITSmodule *mod = (AliITSmodule *)fITSmodules->At(module); sim->DigitiseModule(mod,module,evNumber); // fills all branches - wasted disk space gAlice->TreeD()->Fill(); ResetDigits(); // try and fill only the branch //branch->Fill(); //ResetDigits(id); } // loop over modules } // loop over detector types ClearModules(); Int_t nentries=(Int_t)gAlice->TreeD()->GetEntries(); cout << "nentries in TreeD" << nentries << endl; char hname[30]; sprintf(hname,"TreeD%d",evNumber); gAlice->TreeD()->Write(hname,TObject::kOverwrite); // reset tree gAlice->TreeD()->Reset(); } //____________________________________________________________________________ void AliITS::DigitsToRecPoints(Int_t evNumber,Int_t lastentry,Option_t *opt) { // cluster finding and reconstruction of space points // the condition below will disappear when the geom class will be // initialised for all versions - for the moment it is only for v5 ! // 7 is the SDD beam test version Int_t ver = this->IsVersion(); if(ver!=5) return; char *all = strstr(opt,"All"); char *det[3] = {strstr(opt,"SPD"),strstr(opt,"SDD"),strstr(opt,"SSD")}; static Bool_t first=kTRUE; if (!TreeC() && first) { MakeTreeC("C"); first=kFALSE; } TTree *treeC=TreeC(); //TBranch *branch; AliITSClusterFinder* rec; //TObjArray *branches=gAlice->TreeR()->GetListOfBranches(); AliITSgeom *geom = GetITSgeom(); Int_t id,module; for (id=0;id<kNTYPES;id++) { if (!all && !det[id]) continue; //branch = (TBranch*)branches->UncheckedAt(id); AliITSDetType *iDetType=DetType(id); rec = (AliITSClusterFinder*)iDetType->GetReconstructionModel(); if (!rec) { Error("DigitsToRecPoints","The cluster finder class was not instantiated!"); exit(1); // or SetDefaultClusterFinders(); } TClonesArray *itsDigits = this->DigitsAddress(id); Int_t first,last; if(geom) { first = geom->GetStartDet(id); last = geom->GetLastDet(id); } else first=last=0; //printf("first last %d %d\n",first,last); for(module=first;module<=last;module++) { this->ResetDigits(); if (all) gAlice->TreeD()->GetEvent(lastentry+module); else gAlice->TreeD()->GetEvent(lastentry+(module-first)); Int_t ndigits = itsDigits->GetEntriesFast(); if (ndigits) rec->FindRawClusters(); gAlice->TreeR()->Fill(); ResetRecPoints(); treeC->Fill(); ResetClusters(); // try and fill only the branch //branch->Fill(); //ResetRecPoints(id); } // loop over modules } // loop over detector types Int_t nentries=(Int_t)gAlice->TreeR()->GetEntries(); Int_t ncentries=(Int_t)treeC->GetEntries(); cout << " nentries ncentries " << nentries << ncentries << endl; char hname[30]; sprintf(hname,"TreeR%d",evNumber); gAlice->TreeR()->Write(hname,TObject::kOverwrite); // reset tree gAlice->TreeR()->Reset(); sprintf(hname,"TreeC%d",evNumber); treeC->Write(hname,TObject::kOverwrite); treeC->Reset(); } //____________________________________________________________________________ void AliITS::HitsToFastRecPoints(Int_t evNumber,Int_t bgrev,Int_t size, Option_t *option,Option_t *opt,Text_t *filename) { // keep galice.root for signal and name differently the file for // background when add! otherwise the track info for signal will be lost ! // the condition below will disappear when the geom class will be // initialised for all versions - for the moment it is only for v5 ! Int_t ver = this->IsVersion(); if(ver!=5) return; char *all = strstr(opt,"All"); char *det[3] = {strstr(opt,"SPD"),strstr(opt,"SDD"),strstr(opt,"SSD")}; Int_t nmodules; InitModules(size,nmodules); FillModules(evNumber,bgrev,nmodules,option,filename); AliITSsimulation* sim; AliITSgeom *geom = GetITSgeom(); TRandom *random=new TRandom[9]; random[0].SetSeed(111); random[1].SetSeed(222); random[2].SetSeed(333); random[3].SetSeed(444); random[4].SetSeed(555); random[5].SetSeed(666); random[6].SetSeed(777); random[7].SetSeed(888); random[8].SetSeed(999); Int_t id,module; for (id=0;id<kNTYPES;id++) { if (!all && !det[id]) continue; AliITSDetType *iDetType=DetType(id); sim = (AliITSsimulation*)iDetType->GetSimulationModel(); if (!sim) { Error("HitsToFastPoints","The simulation class was not instantiated!"); exit(1); // or SetDefaultSimulation(); } Int_t first = geom->GetStartDet(id); Int_t last = geom->GetLastDet(id); for(module=first;module<=last;module++) { AliITSmodule *mod = (AliITSmodule *)fITSmodules->At(module); sim->CreateFastRecPoints(mod,module,random); gAlice->TreeR()->Fill(); ResetRecPoints(); } // loop over modules } // loop over detector types ClearModules(); //Int_t nentries=(Int_t)gAlice->TreeR()->GetEntries(); char hname[30]; sprintf(hname,"TreeR%d",evNumber); gAlice->TreeR()->Write(hname,TObject::kOverwrite); // reset tree gAlice->TreeR()->Reset(); delete [] random; } //________________________________________________________________ AliITStrack AliITS::Tracking(AliITStrack &track, AliITStrack *reference,TObjArray *fastpoints, Int_t **vettid, Bool_t flagvert, AliITSRad *rl ) { //Origin A. Badala' and G.S. Pappalardo: e-mail Angela.Badala@ct.infn.it, Giuseppe.S.Pappalardo@ct.infn.it TList *list= new TList(); AliITStrack tr(track); list->AddLast(&tr); Double_t Pt=(tr).GetPt(); //cout << "\n Pt = " << Pt <<"\n"; AliITStracking obj(list, reference, this, fastpoints,TMath::Abs(Pt),vettid, flagvert, rl); list->Delete(); delete list; Int_t itot=-1; TVector VecTotLabref(18); Int_t lay, k; for(lay=5; lay>=0; lay--) { TVector VecLabref(3); VecLabref=(*reference).GetLabTrack(lay); Float_t ClustZ=(*reference).GetZclusterTrack( lay); //modified il 5-3-2001 for(k=0; k<3; k++) { // {itot++; VecTotLabref(itot)=VecLabref(k);} // modified 5-3-2002 Int_t lpp=(Int_t)VecLabref(k); if(lpp>=0) { TParticle *p=(TParticle*) gAlice->Particle(lpp); Int_t pcode=p->GetPdgCode(); if(pcode==11) VecLabref(k)=p->GetFirstMother(); } itot++; VecTotLabref(itot)=VecLabref(k); if(VecLabref(k)==0. && ClustZ == 0.) VecTotLabref(itot) =-3.; } } Long_t labref; Int_t freq; (*reference).Search(VecTotLabref, labref, freq); if(freq < 5) labref=-labref; (*reference).SetLabel(labref); return *reference; } //________________________________________________________________ void AliITS::DoTracking(Int_t evNumber, Int_t min_t, Int_t max_t, TFile *file, Bool_t flagvert) { // ex macro for tracking ITS printf("begin DoTracking - file %p\n",file); const char *pname="75x40_100x60"; Int_t imax=200,jmax=450; AliITSRad *rl = new AliITSRad(imax,jmax); //cout<<" dopo costruttore AliITSRad\n"; getchar(); struct GoodTrack { Int_t lab,code; Float_t px,py,pz,x,y,z,pxg,pyg,pzg,ptg; Bool_t flag; }; gAlice->GetEvent(0); AliTPC *TPC=(AliTPC*)gAlice->GetDetector("TPC"); AliTPCParam *digp = (AliTPCParam*)file->Get(pname); if (digp!=0) TPC->SetParam(digp); GoodTrack gt[15000]; Int_t ngood=0; ifstream in("itsgood_tracks"); cerr<<"Reading itsgood tracks...\n"; while (in>>gt[ngood].lab>>gt[ngood].code >>gt[ngood].px >>gt[ngood].py>>gt[ngood].pz >>gt[ngood].x >>gt[ngood].y >>gt[ngood].z >>gt[ngood].pxg >>gt[ngood].pyg >>gt[ngood].pzg >>gt[ngood].ptg >>gt[ngood].flag) { ngood++; cerr<<ngood<<'\r'; if (ngood==15000) { cerr<<"Too many good tracks !\n"; break; } } if (!in.eof()) cerr<<"Read error (itsgood_tracks) !\n"; // Load tracks TFile *tf=TFile::Open("tpctracks.root"); if (!tf->IsOpen()) {cerr<<"Can't open tpctracks.root !\n"; return ;} TObjArray tracks(200000); TTree *tracktree=(TTree*)tf->Get("TreeT"); TBranch *tbranch=tracktree->GetBranch("tracks"); Int_t nentr=(Int_t)tracktree->GetEntries(); Int_t kk; for (kk=0; kk<nentr; kk++) { AliTPCtrack *iotrack=new AliTPCtrack; tbranch->SetAddress(&iotrack); tracktree->GetEvent(kk); tracks.AddLast(iotrack); } tf->Close(); Int_t nt = tracks.GetEntriesFast(); cerr<<"Number of found tracks "<<nt<<endl; TVector DataOut(9); Int_t kkk=0; Double_t ptg=0.,pxg=0.,pyg=0.,pzg=0.; ////////////////////////////// good tracks definition in TPC //////////////////////////////// ofstream out1 ("AliITSTrag.out"); Int_t i; for (i=0; i<ngood; i++) out1 << gt[i].ptg << "\n"; out1.close(); TVector vec(5); TTree *TR=gAlice->TreeR(); Int_t nent=(Int_t)TR->GetEntries(); TClonesArray *recPoints = RecPoints(); Int_t numbpoints; Int_t totalpoints=0; Int_t *np = new Int_t[nent]; Int_t **vettid = new Int_t* [nent]; Int_t mod; for (mod=0; mod<nent; mod++) { vettid[mod]=0; this->ResetRecPoints(); //gAlice->TreeR()->GetEvent(mod+1); //first entry in TreeR is empty gAlice->TreeR()->GetEvent(mod); //first entry in TreeR is empty numbpoints = recPoints->GetEntries(); totalpoints+=numbpoints; np[mod] = numbpoints; //cout<<" mod = "<<mod<<" numbpoints = "<<numbpoints<<"\n"; getchar(); vettid[mod] = new Int_t[numbpoints]; Int_t ii; for (ii=0;ii<numbpoints; ii++) *(vettid[mod]+ii)=0; } AliTPCtrack *track; if(min_t < 0) {min_t = 0; max_t = nt-1;} /* ///////////////////////////////// Definition of vertex end its error //////////////////////////// ////////////////////////// In the future it will be given by a method /////////////////////////// Double_t Vx=0.; Double_t Vy=0.; Double_t Vz=0.; Float_t sigmavx=0.0050; // 50 microns Float_t sigmavy=0.0050; // 50 microns Float_t sigmavz=0.010; // 100 microns //Vx+=gRandom->Gaus(0,sigmavx); Vy+=gRandom->Gaus(0,sigmavy); Vz+=gRandom->Gaus(0,sigmavz); TVector vertex(3), ervertex(3) vertex(0)=Vx; vertex(1)=Vy; vertex(2)=Vz; ervertex(0)=sigmavx; ervertex(1)=sigmavy; ervertex(2)=sigmavz; ///////////////////////////////////////////////////////////////////////////////////////////////// */ //TDirectory *savedir=gDirectory; TTree tracktree1("TreeT","Tree with ITS tracks"); AliITSiotrack *iotrack=0; tracktree1.Branch("ITStracks","AliITSiotrack",&iotrack,32000,0); ofstream out ("AliITSTra.out"); Int_t j; for (j=min_t; j<=max_t; j++) { track=(AliTPCtrack*)tracks.UncheckedAt(j); Int_t flaglab=0; if (!track) continue; ////// elimination of not good tracks //////////// Int_t ilab=TMath::Abs(track->GetLabel()); Int_t iii; for (iii=0;iii<ngood;iii++) { //cout<<" ilab, gt[iii].lab = "<<ilab<<" "<<gt[iii].lab<<"\n"; getchar(); if (ilab==gt[iii].lab) { flaglab=1; ptg=gt[iii].ptg; pxg=gt[iii].pxg; pyg=gt[iii].pyg; pzg=gt[iii].pzg; break; } } //cout<<" j flaglab = " <<j<<" "<<flaglab<<"\n"; getchar(); if (!flaglab) continue; //cout<<" j = " <<j<<"\n"; getchar(); /* ////// old propagation to the end of TPC ////////////// Double_t xk=76.; track->PropagateTo(xk); xk-=0.11; track->PropagateTo(xk,42.7,2.27); //C xk-=2.6; track->PropagateTo(xk,36.2,1.98e-3); //C02 xk-=0.051; track->PropagateTo(xk,42.7,2.27); //C /////////////////////////////////////////////////// */ ////// new propagation to the end of TPC ////////////// Double_t xk=77.415; track->PropagateTo(xk, 28.94, 1.204e-3); //Ne xk -=0.01; track->PropagateTo(xk, 44.77, 1.71); //Tedlar xk -=0.04; track->PropagateTo(xk, 44.86, 1.45); //Kevlar xk -=2.0; track->PropagateTo(xk, 41.28, 0.029); //Nomex xk-=16; track->PropagateTo(xk,36.2,1.98e-3); //C02 xk -=0.01; track->PropagateTo(xk, 24.01, 2.7); //Al xk -=0.01; track->PropagateTo(xk, 44.77, 1.71); //Tedlar xk -=0.04; track->PropagateTo(xk, 44.86, 1.45); //Kevlar xk -=0.5; track->PropagateTo(xk, 41.28, 0.029); //Nomex /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////// AliITStrack trackITS(*track); AliITStrack result(*track); AliITStrack primarytrack(*track); /////////////////////////////////////////////////////////////////////////////////////////////// TVector Vgeant(3); Vgeant=result.GetVertex(); // Definition of Dv and Zv for vertex constraint Double_t sigmaDv=0.0050; Double_t sigmaZv=0.010; //Double_t sigmaDv=0.0015; Double_t sigmaZv=0.0015; Double_t uniform= gRandom->Uniform(); Double_t signdv; if(uniform<=0.5) signdv=-1.; else signdv=1.; Double_t Vr=TMath::Sqrt(Vgeant(0)*Vgeant(0)+ Vgeant(1)*Vgeant(1)); Double_t Dv=gRandom->Gaus(signdv*Vr,(Float_t)sigmaDv); Double_t Zv=gRandom->Gaus(Vgeant(2),(Float_t)sigmaZv); //cout<<" Dv e Zv = "<<Dv<<" "<<Zv<<"\n"; trackITS.SetDv(Dv); trackITS.SetZv(Zv); trackITS.SetsigmaDv(sigmaDv); trackITS.SetsigmaZv(sigmaZv); result.SetDv(Dv); result.SetZv(Zv); result.SetsigmaDv(sigmaDv); result.SetsigmaZv(sigmaZv); primarytrack.SetDv(Dv); primarytrack.SetZv(Zv); primarytrack.SetsigmaDv(sigmaDv); primarytrack.SetsigmaZv(sigmaZv); ///////////////////////////////////////////////////////////////////////////////////////////////// primarytrack.PrimaryTrack(rl); TVector d2=primarytrack.Getd2(); TVector tgl2=primarytrack.Gettgl2(); TVector dtgl=primarytrack.Getdtgl(); trackITS.Setd2(d2); trackITS.Settgl2(tgl2); trackITS.Setdtgl(dtgl); result.Setd2(d2); result.Settgl2(tgl2); result.Setdtgl(dtgl); /* trackITS.SetVertex(vertex); trackITS.SetErrorVertex(ervertex); result.SetVertex(vertex); result.SetErrorVertex(ervertex); */ Tracking(trackITS,&result,recPoints,vettid, flagvert,rl); // cout<<" progressive track number = "<<j<<"\r"; // cout<<j<<"\r"; // cout<<" progressive track number = "<<j<<"\n"; Long_t labITS=result.GetLabel(); // cout << " ITS track label = " << labITS << "\n"; int lab=track->GetLabel(); // cout << " TPC track label = " << lab <<"\n"; //result.GetClusters(); getchar(); //to print the cluster matrix //propagation to vertex Double_t rbeam=3.; result.Propagation(rbeam); TMatrix *cov; cov=&result.GetCMatrix(); Double_t pt=TMath::Abs(result.GetPt()); Double_t Dr=result.GetD(); Double_t Z=result.GetZ(); Double_t tgl=result.GetTgl(); Double_t C=result.GetC(); Double_t Cy=C/2.; Double_t Dz=Z-(tgl/Cy)*TMath::ASin(result.arga(rbeam)); Dz-=Vgeant(2); // cout<<" Dr e dz alla fine = "<<Dr<<" "<<Dz<<"\n"; getchar(); Double_t phi=result.Getphi(); Double_t phivertex = phi - TMath::ASin(result.argA(rbeam)); Double_t duepi=2.*TMath::Pi(); if(phivertex>duepi) phivertex-=duepi; if(phivertex<0.) phivertex+=duepi; Double_t Dtot=TMath::Sqrt(Dr*Dr+Dz*Dz); ////////////////////////////////////////////////////////////////////////////////////////// Int_t NumofCluster, idmodule,idpoint; NumofCluster=result.GetNumClust(); if(NumofCluster >=5) { AliITSiotrack outtrack; iotrack=&outtrack; iotrack->SetStatePhi(phi); iotrack->SetStateZ(Z); iotrack->SetStateD(Dr); iotrack->SetStateTgl(tgl); iotrack->SetStateC(C); Double_t radius=result.Getrtrack(); iotrack->SetRadius(radius); Int_t charge; if(C>0.) charge=-1; else charge=1; iotrack->SetCharge(charge); iotrack->SetCovMatrix(cov); Double_t px=pt*TMath::Cos(phi); Double_t py=pt*TMath::Sin(phi); Double_t pz=pt*tgl; Double_t xtrack=Dr*TMath::Sin(phi); Double_t ytrack=Dr*TMath::Cos(phi); Double_t ztrack=Dz+Vgeant(2); iotrack->SetPx(px); iotrack->SetPy(py); iotrack->SetPz(pz); iotrack->SetX(xtrack); iotrack->SetY(ytrack); iotrack->SetZ(ztrack); iotrack->SetLabel(labITS); Int_t il; for(il=0;il<6; il++){ iotrack->SetIdPoint(il,result.GetIdPoint(il)); iotrack->SetIdModule(il,result.GetIdModule(il)); } tracktree1.Fill(); //cout<<" labITS = "<<labITS<<"\n"; //cout<<" phi z Dr tgl C = "<<phi<<" "<<Z<<" "<<Dr<<" "<<tgl<<" "<<C<<"\n"; getchar(); DataOut(kkk) = ptg; kkk++; DataOut(kkk)=labITS; kkk++; DataOut(kkk)=lab; kkk++; for (il=0;il<6;il++) { idpoint=result.GetIdPoint(il); idmodule=result.GetIdModule(il); *(vettid[idmodule]+idpoint)=1; iotrack->SetIdPoint(il,idpoint); iotrack->SetIdModule(il,idmodule); } // cout<<" +++++++++++++ pt e ptg = "<<pt<<" "<<ptg<<" ++++++++++\n"; Double_t difpt= (pt-ptg)/ptg*100.; DataOut(kkk)=difpt; kkk++; Double_t lambdag=TMath::ATan(pzg/ptg); Double_t lam=TMath::ATan(tgl); Double_t diflam = (lam - lambdag)*1000.; DataOut(kkk) = diflam; kkk++; Double_t phig=TMath::ATan(pyg/pxg); Double_t phi=phivertex; Double_t difphi = (phi - phig)*1000.; DataOut(kkk)=difphi; kkk++; DataOut(kkk)=Dtot*1.e4; kkk++; DataOut(kkk)=Dr*1.e4; kkk++; DataOut(kkk)=Dz*1.e4; kkk++; Int_t r; for (r=0; r<9; r++) { out<<DataOut(r)<<" ";} out<<"\n"; kkk=0; } // end if on NumofCluster //gObjectTable->Print(); // stampa memoria } // end for (int j=min_t; j<=max_t; j++) out.close(); static Bool_t first=kTRUE; static TFile *tfile; if(first) { tfile=new TFile("itstracks.root","RECREATE"); //cout<<"I have opened itstracks.root file "<<endl; } first=kFALSE; tfile->cd(); tfile->ls(); char hname[30]; sprintf(hname,"TreeT%d",evNumber); tracktree1.Write(hname); TTree *fAli=gAlice->TreeK(); TFile *fileAli=0; if (fAli) fileAli =fAli->GetCurrentFile(); fileAli->cd(); //////////////////////////////////////////////////////////////////////////////////////////////// printf("delete vectors\n"); if(np) delete [] np; if(vettid) delete [] vettid; }
// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace iox { namespace concurrent { template <class ValueType, uint32_t CapacityValue> SoFi<ValueType, CapacityValue>::SoFi() noexcept { } template <class ValueType, uint32_t CapacityValue> uint64_t SoFi<ValueType, CapacityValue>::capacity() const noexcept { return m_size - INTERNAL_SIZE_ADD_ON; } template <class ValueType, uint32_t CapacityValue> uint64_t SoFi<ValueType, CapacityValue>::size() const noexcept { uint64_t readPosition; uint64_t writePosition; do { readPosition = m_readPosition.load(std::memory_order_relaxed); writePosition = m_writePosition.load(std::memory_order_relaxed); } while (m_writePosition.load(std::memory_order_relaxed) != writePosition || m_readPosition.load(std::memory_order_relaxed) != readPosition); return writePosition - readPosition; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::resize(const uint32_t newSize) noexcept { uint64_t newInternalSize = newSize + INTERNAL_SIZE_ADD_ON; if (empty() && (newInternalSize <= INTERNAL_SOFI_SIZE)) { m_size = newInternalSize; m_readPosition.store(0u, std::memory_order_release); m_writePosition.store(0u, std::memory_order_release); return true; } return false; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::empty() const noexcept { uint64_t currentReadPosition; bool isEmpty; do { /// @todo read before write since the writer increments the aba counter!!! /// @todo write doc with example!!! currentReadPosition = m_readPosition.load(std::memory_order_acquire); uint64_t currentWritePosition = m_writePosition.load(std::memory_order_acquire); isEmpty = (currentWritePosition == currentReadPosition); // we need compare without exchange } while (!(currentReadPosition == m_readPosition.load(std::memory_order_acquire))); return isEmpty; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::pop(ValueType& valueOut) noexcept { return popIf(valueOut, [](ValueType) { return true; }); } template <class ValueType, uint32_t CapacityValue> template <typename Verificator_T> inline bool SoFi<ValueType, CapacityValue>::popIf(ValueType& valueOut, const Verificator_T& verificator) noexcept { uint64_t currentReadPosition = m_readPosition.load(std::memory_order_acquire); uint64_t nextReadPosition; bool popWasSuccessful{true}; do { if (currentReadPosition == m_writePosition.load(std::memory_order_acquire)) { nextReadPosition = currentReadPosition; popWasSuccessful = false; } else { // we use memcpy here, since the copy assignment is not thread safe in general (we might have an overflow in // the push thread and invalidates the object while the copy is running and therefore works on an // invalid object); memcpy is also not thread safe, but we discard the object anyway and read it // again if its overwritten in between; this is only relevant for types larger than pointer size // assign the user data std::memcpy(&valueOut, &m_data[static_cast<int32_t>(currentReadPosition) % m_size], sizeof(ValueType)); /// @brief first we need to peak valueOut if it is fitting the condition and then we have to verify /// if valueOut is not am invalid object, this could be the case if the read position has /// changed if (m_readPosition.load(std::memory_order_relaxed) == currentReadPosition && verificator(valueOut) == false) { popWasSuccessful = false; } else { nextReadPosition = currentReadPosition + 1U; popWasSuccessful = true; } } // compare and swap // if(m_readPosition == currentReadPosition) // m_readPosition = l_next_aba_read_pos // else // currentReadPosition = m_readPosition // Assign m_aba_read_p to next readable location } while (!m_readPosition.compare_exchange_weak( currentReadPosition, nextReadPosition, std::memory_order_acq_rel, std::memory_order_acquire)); return popWasSuccessful; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::push(const ValueType& valueOut, ValueType& f_paramOut_r) noexcept { constexpr bool OVERFLOW{false}; uint64_t currentWritePosition = m_writePosition.load(std::memory_order_relaxed); uint64_t nextWritePosition = currentWritePosition + 1U; m_data[static_cast<int32_t>(currentWritePosition) % m_size] = valueOut; m_writePosition.store(nextWritePosition, std::memory_order_release); uint64_t currentReadPosition = m_readPosition.load(std::memory_order_acquire); // check if there is a free position for the next push if (nextWritePosition < currentReadPosition + m_size) { return !OVERFLOW; } // this is an overflow situation, which means that the next push has no free position, therefore the oldest value // needs to be passed back to the caller uint64_t nextReadPosition = currentReadPosition + 1U; // we need to update the read position // a) it works, then we need to pass the overflow value back // b) it doesn't work, which means that the pop thread already took the value in the meantime an no further action // is required // memory order success is memory_order_acq_rel // - this is to prevent the reordering of m_writePosition.store(...) after the increment of the m_readPosition // - in case of an overflow, this might result in the pop thread getting one element less than the capacity of // the SoFi if the push thread is suspended in between this two statements // - it's still possible to get more elements than the capacity, but this is an inherent issue with concurrent // queues and cannot be prevented since there can always be a push during a pop operation // - another issue might be that two consecutive pushes (not concurrent) happen on different CPU cores without // synchronization, then the memory also needs to be synchronized for the overflow case // memory order failure is memory_order_relaxed since there is no further synchronization needed if there is no // overflow if (m_readPosition.compare_exchange_strong( currentReadPosition, nextReadPosition, std::memory_order_acq_rel, std::memory_order_relaxed)) { std::memcpy(&f_paramOut_r, &m_data[static_cast<int32_t>(currentReadPosition) % m_size], sizeof(ValueType)); return OVERFLOW; } return !OVERFLOW; } } // namespace concurrent } // namespace iox iox-#32 fix compiler error in sofi.inl:142 error: expected unqualified-id constexpr bool OVERFLOW{false}; ^ /Applications/Xcode_11.4.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/math.h:734:18: note: expanded from macro 'OVERFLOW' ^ Signed-off-by: Prasanna Bhat <e5bee0ecd0115ae065310834f9446360b4c750cd@gmail.com> // Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace iox { namespace concurrent { template <class ValueType, uint32_t CapacityValue> SoFi<ValueType, CapacityValue>::SoFi() noexcept { } template <class ValueType, uint32_t CapacityValue> uint64_t SoFi<ValueType, CapacityValue>::capacity() const noexcept { return m_size - INTERNAL_SIZE_ADD_ON; } template <class ValueType, uint32_t CapacityValue> uint64_t SoFi<ValueType, CapacityValue>::size() const noexcept { uint64_t readPosition; uint64_t writePosition; do { readPosition = m_readPosition.load(std::memory_order_relaxed); writePosition = m_writePosition.load(std::memory_order_relaxed); } while (m_writePosition.load(std::memory_order_relaxed) != writePosition || m_readPosition.load(std::memory_order_relaxed) != readPosition); return writePosition - readPosition; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::resize(const uint32_t newSize) noexcept { uint64_t newInternalSize = newSize + INTERNAL_SIZE_ADD_ON; if (empty() && (newInternalSize <= INTERNAL_SOFI_SIZE)) { m_size = newInternalSize; m_readPosition.store(0u, std::memory_order_release); m_writePosition.store(0u, std::memory_order_release); return true; } return false; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::empty() const noexcept { uint64_t currentReadPosition; bool isEmpty; do { /// @todo read before write since the writer increments the aba counter!!! /// @todo write doc with example!!! currentReadPosition = m_readPosition.load(std::memory_order_acquire); uint64_t currentWritePosition = m_writePosition.load(std::memory_order_acquire); isEmpty = (currentWritePosition == currentReadPosition); // we need compare without exchange } while (!(currentReadPosition == m_readPosition.load(std::memory_order_acquire))); return isEmpty; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::pop(ValueType& valueOut) noexcept { return popIf(valueOut, [](ValueType) { return true; }); } template <class ValueType, uint32_t CapacityValue> template <typename Verificator_T> inline bool SoFi<ValueType, CapacityValue>::popIf(ValueType& valueOut, const Verificator_T& verificator) noexcept { uint64_t currentReadPosition = m_readPosition.load(std::memory_order_acquire); uint64_t nextReadPosition; bool popWasSuccessful{true}; do { if (currentReadPosition == m_writePosition.load(std::memory_order_acquire)) { nextReadPosition = currentReadPosition; popWasSuccessful = false; } else { // we use memcpy here, since the copy assignment is not thread safe in general (we might have an overflow in // the push thread and invalidates the object while the copy is running and therefore works on an // invalid object); memcpy is also not thread safe, but we discard the object anyway and read it // again if its overwritten in between; this is only relevant for types larger than pointer size // assign the user data std::memcpy(&valueOut, &m_data[static_cast<int32_t>(currentReadPosition) % m_size], sizeof(ValueType)); /// @brief first we need to peak valueOut if it is fitting the condition and then we have to verify /// if valueOut is not am invalid object, this could be the case if the read position has /// changed if (m_readPosition.load(std::memory_order_relaxed) == currentReadPosition && verificator(valueOut) == false) { popWasSuccessful = false; } else { nextReadPosition = currentReadPosition + 1U; popWasSuccessful = true; } } // compare and swap // if(m_readPosition == currentReadPosition) // m_readPosition = l_next_aba_read_pos // else // currentReadPosition = m_readPosition // Assign m_aba_read_p to next readable location } while (!m_readPosition.compare_exchange_weak( currentReadPosition, nextReadPosition, std::memory_order_acq_rel, std::memory_order_acquire)); return popWasSuccessful; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::push(const ValueType& valueOut, ValueType& f_paramOut_r) noexcept { constexpr bool SOFI_OVERFLOW{false}; uint64_t currentWritePosition = m_writePosition.load(std::memory_order_relaxed); uint64_t nextWritePosition = currentWritePosition + 1U; m_data[static_cast<int32_t>(currentWritePosition) % m_size] = valueOut; m_writePosition.store(nextWritePosition, std::memory_order_release); uint64_t currentReadPosition = m_readPosition.load(std::memory_order_acquire); // check if there is a free position for the next push if (nextWritePosition < currentReadPosition + m_size) { return !SOFI_OVERFLOW; } // this is an overflow situation, which means that the next push has no free position, therefore the oldest value // needs to be passed back to the caller uint64_t nextReadPosition = currentReadPosition + 1U; // we need to update the read position // a) it works, then we need to pass the overflow value back // b) it doesn't work, which means that the pop thread already took the value in the meantime an no further action // is required // memory order success is memory_order_acq_rel // - this is to prevent the reordering of m_writePosition.store(...) after the increment of the m_readPosition // - in case of an overflow, this might result in the pop thread getting one element less than the capacity of // the SoFi if the push thread is suspended in between this two statements // - it's still possible to get more elements than the capacity, but this is an inherent issue with concurrent // queues and cannot be prevented since there can always be a push during a pop operation // - another issue might be that two consecutive pushes (not concurrent) happen on different CPU cores without // synchronization, then the memory also needs to be synchronized for the overflow case // memory order failure is memory_order_relaxed since there is no further synchronization needed if there is no // overflow if (m_readPosition.compare_exchange_strong( currentReadPosition, nextReadPosition, std::memory_order_acq_rel, std::memory_order_relaxed)) { std::memcpy(&f_paramOut_r, &m_data[static_cast<int32_t>(currentReadPosition) % m_size], sizeof(ValueType)); return SOFI_OVERFLOW; } return !SOFI_OVERFLOW; } } // namespace concurrent } // namespace iox
#include <algorithm> #include <iostream> #include <vector> using namespace std; struct point { float x; float y; point(float xIn, float yIn) : x(xIn), y(yIn) { } }; // The z-value of the cross product of segments // (a, b) and (a, c). Positive means c is ccw // from (a, b), negative cw. Zero means its collinear. float ccw(const point& a, const point& b, const point& c) { return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); } // Returns true if a is lexicographically before b. bool isLeftOf(const point& a, const point& b) { return (a.x < b.x || (a.x == b.x && a.y < b.y)); } // Used to sort points in ccw order about a pivot. struct ccwSorter { const point& pivot; ccwSorter(const point& inPivot) : pivot(inPivot) { } bool operator()(const point& a, const point& b) { return ccw(pivot, a, b) < 0; } }; // The length of segment (a, b). float len(const point& a, const point& b) { return sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y)); } // The unsigned distance of p from segment (a, b). float dist(const point& a, const point& b, const point& p) { return fabs((b.x - a.x) * (a.y - p.y) - (b.y - a.y) * (a.x - p.x)) / len(a, b); } // Returns the index of the farthest point from segment (a, b). size_t getFarthest(const point& a, const point& b, const vector<point>& v) { size_t idxMax = 0; float distMax = dist(a, b, v[idxMax]); for (size_t i = 1; i < v.size(); ++i) { float distCurr = dist(a, b, v[i]); if (distCurr > distMax) { idxMax = i; distMax = distCurr; } } return idxMax; } // The gift-wrapping algorithm for convex hull. // https://en.wikipedia.org/wiki/Gift_wrapping_algorithm vector<point> giftWrapping(const vector<point>& v) { // Start with the leftmost point. size_t startIdx = min_element(v.begin(), v.end(), isLeftOf) - v.begin(); size_t hIdx = startIdx; vector<point> hull; do { // Add our current point to the hull. hull.push_back(v[hIdx]); // Find the index of the input point that is farthest // ccw from our last hull point. ccwSorter isCcw(v[hIdx]); size_t endIdx = 0; for (size_t i = 1; i < v.size(); ++i) { if ((endIdx == hIdx) || isCcw(v[endIdx], v[i])) { endIdx = i; } } // Make that our new hIdx = endIdx; } while (hIdx != startIdx); return hull; } // The Graham scan algorithm for convex hull. // https://en.wikipedia.org/wiki/Graham_scan vector<point> GrahamScan(vector<point> v) { // Put our leftmost point at index 0 swap(v[0], *min_element(v.begin(), v.end(), isLeftOf)); // Sort the rest of the points in counter-clockwise order // from our leftmost point. sort(v.begin() + 1, v.end(), ccwSorter(v[0])); // Add our first three points to the hull. vector<point> hull; auto it = v.begin(); hull.push_back(*it++); hull.push_back(*it++); hull.push_back(*it++); while (it != v.end()) { // Pop off any points that make a convex angle with *it while (ccw(*(hull.rbegin() + 1), *(hull.rbegin()), *it) >= 0) { hull.pop_back(); } hull.push_back(*it++); } return hull; } // The monotone chain algorithm for convex hull. vector<point> monotoneChain(vector<point> v) { // Sort out points in lexicographic order. sort(v.begin(), v.end(), isLeftOf); // Find the lower half of the convex hull. vector<point> lower; for (auto it = v.begin(); it != v.end(); ++it) { // Pop off any points that make a convex angle with *it while (lower.size() >= 2 && ccw(*(lower.rbegin() + 1), *(lower.rbegin()), *it) >= 0) { lower.pop_back(); } lower.push_back(*it); } // Find the upper half of the convex hull. vector<point> upper; for (auto it = v.rbegin(); it != v.rend(); ++it) { // Pop off any points that make a convex angle with *it while (upper.size() >= 2 && ccw(*(upper.rbegin() + 1), *(upper.rbegin()), *it) >= 0) { upper.pop_back(); } upper.push_back(*it); } vector<point> hull; hull.insert(hull.end(), lower.begin(), lower.end()); hull.insert(hull.end(), upper.begin() + 1, upper.end() - 1); return hull; } // Recursive call of the quickhull algorithm. void quickHull(const vector<point>& v, const point& a, const point& b, vector<point>& hull) { if (v.empty()) { return; } point f = v[getFarthest(a, b, v)]; // Collect points to the left of segment (a, f) vector<point> left; for (auto p : v) { if (ccw(a, f, p) > 0) { left.push_back(p); } } quickHull(left, a, f, hull); // Add f to the hull hull.push_back(f); // Collect points to the left of segment (f, b) vector<point> right; for (auto p : v) { if (ccw(f, b, p) > 0) { right.push_back(p); } } quickHull(right, f, b, hull); } // QuickHull algorithm. // https://en.wikipedia.org/wiki/QuickHull vector<point> quickHull(const vector<point>& v) { vector<point> hull; // Start with the leftmost and rightmost points. point a = *min_element(v.begin(), v.end(), isLeftOf); point b = *max_element(v.begin(), v.end(), isLeftOf); // Split the points on either side of segment (a, b) vector<point> left, right; for (auto p : v) { ccw(a, b, p) > 0 ? left.push_back(p) : right.push_back(p); } // Be careful to add points to the hull // in the correct order. Add our leftmost point. hull.push_back(a); // Add hull points from the left (top) quickHull(left, a, b, hull); // Add our rightmost point hull.push_back(b); // Add hull points from the right (bottom) quickHull(right, b, a, hull); return hull; } vector<point> getPoints() { vector<point> v; const float lo = -100.0; const float hi = 100.0; for (int i = 0; i < 100; ++i) { float x = lo + static_cast<float>( rand()) / static_cast<float>(RAND_MAX / (hi - lo)); float y = lo + static_cast<float>( rand()) / static_cast<float>(RAND_MAX / (hi - lo)); v.push_back(point(x, y)); } return v; } void print(const vector<point>& v) { for (auto p : v) { cout << p.x << ", " << p.y << endl; } } int main() { vector<point> v = getPoints(); vector<point> h = quickHull(v); cout << "quickHull point count: " << h.size() << endl; print(h); h = giftWrapping(v); cout << endl << "giftWrapping point count: " << h.size() << endl; print(h); h = monotoneChain(v); cout << endl << "monotoneChain point count: " << h.size() << endl; print(h); h = GrahamScan(v); cout << endl << "GrahamScan point count: " << h.size() << endl; print(h); return 0; } add comments, fix tabs // Implementations of various convex hull algorithms // using the C++ Standard Library. // For clarity, the implementations do not check for // duplicate or collinear points. #include <algorithm> #include <iostream> #include <vector> using namespace std; struct point { float x; float y; point(float xIn, float yIn) : x(xIn), y(yIn) { } }; // The z-value of the cross product of segments // (a, b) and (a, c). Positive means c is ccw // from (a, b), negative cw. Zero means its collinear. float ccw(const point& a, const point& b, const point& c) { return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); } // Returns true if a is lexicographically before b. bool isLeftOf(const point& a, const point& b) { return (a.x < b.x || (a.x == b.x && a.y < b.y)); } // Used to sort points in ccw order about a pivot. struct ccwSorter { const point& pivot; ccwSorter(const point& inPivot) : pivot(inPivot) { } bool operator()(const point& a, const point& b) { return ccw(pivot, a, b) < 0; } }; // The length of segment (a, b). float len(const point& a, const point& b) { return sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y)); } // The unsigned distance of p from segment (a, b). float dist(const point& a, const point& b, const point& p) { return fabs((b.x - a.x) * (a.y - p.y) - (b.y - a.y) * (a.x - p.x)) / len(a, b); } // Returns the index of the farthest point from segment (a, b). size_t getFarthest(const point& a, const point& b, const vector<point>& v) { size_t idxMax = 0; float distMax = dist(a, b, v[idxMax]); for (size_t i = 1; i < v.size(); ++i) { float distCurr = dist(a, b, v[i]); if (distCurr > distMax) { idxMax = i; distMax = distCurr; } } return idxMax; } // The gift-wrapping algorithm for convex hull. // https://en.wikipedia.org/wiki/Gift_wrapping_algorithm vector<point> giftWrapping(const vector<point>& v) { // Start with the leftmost point. size_t startIdx = min_element(v.begin(), v.end(), isLeftOf) - v.begin(); size_t hIdx = startIdx; vector<point> hull; do { // Add our current point to the hull. hull.push_back(v[hIdx]); // Find the index of the input point that is farthest // ccw from our last hull point. ccwSorter isCcw(v[hIdx]); size_t endIdx = 0; for (size_t i = 1; i < v.size(); ++i) { if ((endIdx == hIdx) || isCcw(v[endIdx], v[i])) { endIdx = i; } } // Make that our new hIdx = endIdx; } while (hIdx != startIdx); return hull; } // The Graham scan algorithm for convex hull. // https://en.wikipedia.org/wiki/Graham_scan vector<point> GrahamScan(vector<point> v) { // Put our leftmost point at index 0 swap(v[0], *min_element(v.begin(), v.end(), isLeftOf)); // Sort the rest of the points in counter-clockwise order // from our leftmost point. sort(v.begin() + 1, v.end(), ccwSorter(v[0])); // Add our first three points to the hull. vector<point> hull; auto it = v.begin(); hull.push_back(*it++); hull.push_back(*it++); hull.push_back(*it++); while (it != v.end()) { // Pop off any points that make a convex angle with *it while (ccw(*(hull.rbegin() + 1), *(hull.rbegin()), *it) >= 0) { hull.pop_back(); } hull.push_back(*it++); } return hull; } // The monotone chain algorithm for convex hull. vector<point> monotoneChain(vector<point> v) { // Sort out points in lexicographic order. sort(v.begin(), v.end(), isLeftOf); // Find the lower half of the convex hull. vector<point> lower; for (auto it = v.begin(); it != v.end(); ++it) { // Pop off any points that make a convex angle with *it while (lower.size() >= 2 && ccw(*(lower.rbegin() + 1), *(lower.rbegin()), *it) >= 0) { lower.pop_back(); } lower.push_back(*it); } // Find the upper half of the convex hull. vector<point> upper; for (auto it = v.rbegin(); it != v.rend(); ++it) { // Pop off any points that make a convex angle with *it while (upper.size() >= 2 && ccw(*(upper.rbegin() + 1), *(upper.rbegin()), *it) >= 0) { upper.pop_back(); } upper.push_back(*it); } vector<point> hull; hull.insert(hull.end(), lower.begin(), lower.end()); hull.insert(hull.end(), upper.begin() + 1, upper.end() - 1); return hull; } // Recursive call of the quickhull algorithm. void quickHull(const vector<point>& v, const point& a, const point& b, vector<point>& hull) { if (v.empty()) { return; } point f = v[getFarthest(a, b, v)]; // Collect points to the left of segment (a, f) vector<point> left; for (auto p : v) { if (ccw(a, f, p) > 0) { left.push_back(p); } } quickHull(left, a, f, hull); // Add f to the hull hull.push_back(f); // Collect points to the left of segment (f, b) vector<point> right; for (auto p : v) { if (ccw(f, b, p) > 0) { right.push_back(p); } } quickHull(right, f, b, hull); } // QuickHull algorithm. // https://en.wikipedia.org/wiki/QuickHull vector<point> quickHull(const vector<point>& v) { vector<point> hull; // Start with the leftmost and rightmost points. point a = *min_element(v.begin(), v.end(), isLeftOf); point b = *max_element(v.begin(), v.end(), isLeftOf); // Split the points on either side of segment (a, b) vector<point> left, right; for (auto p : v) { ccw(a, b, p) > 0 ? left.push_back(p) : right.push_back(p); } // Be careful to add points to the hull // in the correct order. Add our leftmost point. hull.push_back(a); // Add hull points from the left (top) quickHull(left, a, b, hull); // Add our rightmost point hull.push_back(b); // Add hull points from the right (bottom) quickHull(right, b, a, hull); return hull; } vector<point> getPoints() { vector<point> v; const float lo = -100.0; const float hi = 100.0; for (int i = 0; i < 100; ++i) { float x = lo + static_cast<float>( rand()) / static_cast<float>(RAND_MAX / (hi - lo)); float y = lo + static_cast<float>( rand()) / static_cast<float>(RAND_MAX / (hi - lo)); v.push_back(point(x, y)); } return v; } void print(const vector<point>& v) { for (auto p : v) { cout << p.x << ", " << p.y << endl; } } int main() { vector<point> v = getPoints(); vector<point> h = quickHull(v); cout << "quickHull point count: " << h.size() << endl; print(h); h = giftWrapping(v); cout << endl << "giftWrapping point count: " << h.size() << endl; print(h); h = monotoneChain(v); cout << endl << "monotoneChain point count: " << h.size() << endl; print(h); h = GrahamScan(v); cout << endl << "GrahamScan point count: " << h.size() << endl; print(h); return 0; }
/* * Copyright (c) 2013 New Designs Unlimited, LLC * Opensource Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenAlpr. * * OpenAlpr is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utility.h" #include <omp.h> Rect expandRect(Rect original, int expandXPixels, int expandYPixels, int maxX, int maxY) { Rect expandedRegion = Rect(original); float halfX = round((float) expandXPixels / 2.0); float halfY = round((float) expandYPixels / 2.0); expandedRegion.x = expandedRegion.x - halfX; expandedRegion.width = expandedRegion.width + expandXPixels; expandedRegion.y = expandedRegion.y - halfY; expandedRegion.height = expandedRegion.height + expandYPixels; if (expandedRegion.x < 0) expandedRegion.x = 0; if (expandedRegion.y < 0) expandedRegion.y = 0; if (expandedRegion.x + expandedRegion.width > maxX) expandedRegion.width = maxX - expandedRegion.x; if (expandedRegion.y + expandedRegion.height > maxY) expandedRegion.height = maxY - expandedRegion.y; return expandedRegion; } Mat drawImageDashboard(vector<Mat> images, int imageType, int numColumns) { int numRows = ceil((float) images.size() / (float) numColumns); Mat dashboard(Size(images[0].cols * numColumns, images[0].rows * numRows), imageType); for (int i = 0; i < numColumns * numRows; i++) { if (i < images.size()) images[i].copyTo(dashboard(Rect((i%numColumns) * images[i].cols, floor((float) i/numColumns) * images[i].rows, images[i].cols, images[i].rows))); else { Mat black = Mat::zeros(images[0].size(), imageType); black.copyTo(dashboard(Rect((i%numColumns) * images[0].cols, floor((float) i/numColumns) * images[0].rows, images[0].cols, images[0].rows))); } } return dashboard; } Mat addLabel(Mat input, string label) { const int border_size = 1; const Scalar border_color(0,0,255); const int extraHeight = 20; const Scalar bg(222,222,222); const Scalar fg(0,0,0); Rect destinationRect(border_size, extraHeight, input.cols, input.rows); Mat newImage(Size(input.cols + (border_size), input.rows + extraHeight + (border_size )), input.type()); input.copyTo(newImage(destinationRect)); cout << " Adding label " << label << endl; if (input.type() == CV_8U) cvtColor(newImage, newImage, CV_GRAY2BGR); rectangle(newImage, Point(0,0), Point(input.cols, extraHeight), bg, CV_FILLED); putText(newImage, label, Point(5, extraHeight - 5), CV_FONT_HERSHEY_PLAIN , 0.7, fg); rectangle(newImage, Point(0,0), Point(newImage.cols - 1, newImage.rows -1), border_color, border_size); return newImage; } void drawAndWait(cv::Mat* frame) { cv::imshow("Temp Window", *frame); while (cv::waitKey(50) == -1) { // loop } cv::destroyWindow("Temp Window"); } void displayImage(Config* config, string windowName, cv::Mat frame) { if (config->debugShowImages) imshow(windowName, frame); } vector<Mat> produceThresholds(const Mat img_gray, Config* config) { const int THRESHOLD_COUNT = 10; //Mat img_equalized = equalizeBrightness(img_gray); timespec startTime; getTime(&startTime); vector<Mat> thresholds; //#pragma omp parallel for for (int i = 0; i < THRESHOLD_COUNT; i++) thresholds.push_back(Mat(img_gray.size(), CV_8U)); for (int i = 0; i < THRESHOLD_COUNT; i++) { if (i <= 2) //0-2 { int k = ((i%3) * 5) + 7; // 7, 12, 17 if (k==12) k = 13; // change 12 to 13 //#pragma omp ordered adaptiveThreshold(img_gray, thresholds[i], 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV , k, 3); } else if (i <= 6) //3-6 { int k = i%2; // 0 or 1 int win = 18 + (k * 4); // 18 or 22 //#pragma omp ordered NiblackSauvolaWolfJolion (img_gray, thresholds[i], WOLFJOLION, win, win, 0.05 + (k * 0.35)); bitwise_not(thresholds[i], thresholds[i]); } else if (i <= 9) //7-9 { int k = (i%3) + 1; // 1,2,3 //#pragma omp ordered NiblackSauvolaWolfJolion (img_gray, thresholds[i], SAUVOLA, 12, 12, 0.18 * k); bitwise_not(thresholds[i], thresholds[i]); } } if (config->debugTiming) { timespec endTime; getTime(&endTime); cout << " -- Produce Threshold Time: " << diffclock(startTime, endTime) << "ms." << endl; } return thresholds; //threshold(img_equalized, img_threshold, 100, 255, THRESH_BINARY); } Mat equalizeBrightness(Mat img) { // Divide the image by its morphologically closed counterpart Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(19,19)); Mat closed; morphologyEx(img, closed, MORPH_CLOSE, kernel); img.convertTo(img, CV_32FC1); // divide requires floating-point divide(img, closed, img, 1, CV_32FC1); normalize(img, img, 0, 255, NORM_MINMAX); img.convertTo(img, CV_8U); // convert back to unsigned int return img; } void drawRotatedRect(Mat* img, RotatedRect rect, Scalar color, int thickness) { Point2f rect_points[4]; rect.points( rect_points ); for( int j = 0; j < 4; j++ ) line( *img, rect_points[j], rect_points[(j+1)%4], color, thickness, 8 ); } void fillMask(Mat img, const Mat mask, Scalar color) { for (int row = 0; row < img.rows; row++) { for (int col = 0; col < img.cols; col++) { int m = (int) mask.at<uchar>(row, col); if (m) { for (int z = 0; z < 3; z++) { int prevVal = img.at<Vec3b>(row, col)[z]; img.at<Vec3b>(row, col)[z] = ((int) color[z]) | prevVal; } } } } } void drawX(Mat img, Rect rect, Scalar color, int thickness) { Point tl(rect.x, rect.y); Point tr(rect.x + rect.width, rect.y); Point bl(rect.x, rect.y + rect.height); Point br(rect.x + rect.width, rect.y + rect.height); line(img, tl, br, color, thickness); line(img, bl, tr, color, thickness); } double distanceBetweenPoints(Point p1, Point p2) { float asquared = (p2.x - p1.x)*(p2.x - p1.x); float bsquared = (p2.y - p1.y)*(p2.y - p1.y); return sqrt(asquared + bsquared); } float angleBetweenPoints(Point p1, Point p2) { int deltaY = p2.y - p1.y; int deltaX = p2.x - p1.x; return atan2((float) deltaY, (float) deltaX) * (180 / CV_PI); } Size getSizeMaintainingAspect(Mat inputImg, int maxWidth, int maxHeight) { float aspect = ((float) inputImg.cols) / ((float) inputImg.rows); if (maxWidth / aspect > maxHeight) { return Size(maxHeight * aspect, maxHeight); } else { return Size(maxWidth, maxWidth / aspect); } } LineSegment::LineSegment() { init(0, 0, 0, 0); } LineSegment::LineSegment(Point p1, Point p2) { init(p1.x, p1.y, p2.x, p2.y); } LineSegment::LineSegment(int x1, int y1, int x2, int y2) { init(x1, y1, x2, y2); } void LineSegment::init(int x1, int y1, int x2, int y2) { this->p1 = Point(x1, y1); this->p2 = Point(x2, y2); if (p2.x - p1.x == 0) this->slope = 0.00000000001; else this->slope = (float) (p2.y - p1.y) / (float) (p2.x - p1.x); this->length = distanceBetweenPoints(p1, p2); this->angle = angleBetweenPoints(p1, p2); } bool LineSegment::isPointBelowLine( Point tp ){ return ((p2.x - p1.x)*(tp.y - p1.y) - (p2.y - p1.y)*(tp.x - p1.x)) > 0; } float LineSegment::getPointAt(float x) { return slope * (x - p2.x) + p2.y; } Point LineSegment::closestPointOnSegmentTo(Point p) { float top = (p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y)*(p2.y - p1.y); float bottom = distanceBetweenPoints(p2, p1); bottom = bottom * bottom; float u = top / bottom; float x = p1.x + u * (p2.x - p1.x); float y = p1.y + u * (p2.y - p1.y); return Point(x, y); } Point LineSegment::intersection(LineSegment line) { float c1, c2; float intersection_X = -1, intersection_Y= -1; c1 = p1.y - slope * p1.x; // which is same as y2 - slope * x2 c2 = line.p2.y - line.slope * line.p2.x; // which is same as y2 - slope * x2 if( (slope - line.slope) == 0) { //std::cout << "No Intersection between the lines" << endl; } else if (p1.x == p2.x) { // Line1 is vertical return Point(p1.x, line.getPointAt(p1.x)); } else if (line.p1.x == line.p2.x) { // Line2 is vertical return Point(line.p1.x, getPointAt(line.p1.x)); } else { intersection_X = (c2 - c1) / (slope - line.slope); intersection_Y = slope * intersection_X + c1; } return Point(intersection_X, intersection_Y); } Point LineSegment::midpoint() { // Handle the case where the line is vertical if (p1.x == p2.x) { float ydiff = p2.y-p1.y; float y = p1.y + (ydiff/2); return Point(p1.x, y); } float diff = p2.x - p1.x; float midX = ((float) p1.x) + (diff / 2); int midY = getPointAt(midX); return Point(midX, midY); } LineSegment LineSegment::getParallelLine(float distance) { float diff_x = p2.x - p1.x; float diff_y = p2.y - p1.y; float angle = atan2( diff_x, diff_y); float dist_x = distance * cos(angle); float dist_y = -distance * sin(angle); int offsetX = (int)round(dist_x); int offsetY = (int)round(dist_y); LineSegment result(p1.x + offsetX, p1.y + offsetY, p2.x + offsetX, p2.y + offsetY); return result; } OpenMP is not yet supported on Mac OS X (clang) /* * Copyright (c) 2013 New Designs Unlimited, LLC * Opensource Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenAlpr. * * OpenAlpr is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utility.h" #ifndef __APPLE__ // CLang++ does not have yet implementet OpenMP #include <omp.h> #endif Rect expandRect(Rect original, int expandXPixels, int expandYPixels, int maxX, int maxY) { Rect expandedRegion = Rect(original); float halfX = round((float) expandXPixels / 2.0); float halfY = round((float) expandYPixels / 2.0); expandedRegion.x = expandedRegion.x - halfX; expandedRegion.width = expandedRegion.width + expandXPixels; expandedRegion.y = expandedRegion.y - halfY; expandedRegion.height = expandedRegion.height + expandYPixels; if (expandedRegion.x < 0) expandedRegion.x = 0; if (expandedRegion.y < 0) expandedRegion.y = 0; if (expandedRegion.x + expandedRegion.width > maxX) expandedRegion.width = maxX - expandedRegion.x; if (expandedRegion.y + expandedRegion.height > maxY) expandedRegion.height = maxY - expandedRegion.y; return expandedRegion; } Mat drawImageDashboard(vector<Mat> images, int imageType, int numColumns) { int numRows = ceil((float) images.size() / (float) numColumns); Mat dashboard(Size(images[0].cols * numColumns, images[0].rows * numRows), imageType); for (int i = 0; i < numColumns * numRows; i++) { if (i < images.size()) images[i].copyTo(dashboard(Rect((i%numColumns) * images[i].cols, floor((float) i/numColumns) * images[i].rows, images[i].cols, images[i].rows))); else { Mat black = Mat::zeros(images[0].size(), imageType); black.copyTo(dashboard(Rect((i%numColumns) * images[0].cols, floor((float) i/numColumns) * images[0].rows, images[0].cols, images[0].rows))); } } return dashboard; } Mat addLabel(Mat input, string label) { const int border_size = 1; const Scalar border_color(0,0,255); const int extraHeight = 20; const Scalar bg(222,222,222); const Scalar fg(0,0,0); Rect destinationRect(border_size, extraHeight, input.cols, input.rows); Mat newImage(Size(input.cols + (border_size), input.rows + extraHeight + (border_size )), input.type()); input.copyTo(newImage(destinationRect)); cout << " Adding label " << label << endl; if (input.type() == CV_8U) cvtColor(newImage, newImage, CV_GRAY2BGR); rectangle(newImage, Point(0,0), Point(input.cols, extraHeight), bg, CV_FILLED); putText(newImage, label, Point(5, extraHeight - 5), CV_FONT_HERSHEY_PLAIN , 0.7, fg); rectangle(newImage, Point(0,0), Point(newImage.cols - 1, newImage.rows -1), border_color, border_size); return newImage; } void drawAndWait(cv::Mat* frame) { cv::imshow("Temp Window", *frame); while (cv::waitKey(50) == -1) { // loop } cv::destroyWindow("Temp Window"); } void displayImage(Config* config, string windowName, cv::Mat frame) { if (config->debugShowImages) imshow(windowName, frame); } vector<Mat> produceThresholds(const Mat img_gray, Config* config) { const int THRESHOLD_COUNT = 10; //Mat img_equalized = equalizeBrightness(img_gray); timespec startTime; getTime(&startTime); vector<Mat> thresholds; //#pragma omp parallel for for (int i = 0; i < THRESHOLD_COUNT; i++) thresholds.push_back(Mat(img_gray.size(), CV_8U)); for (int i = 0; i < THRESHOLD_COUNT; i++) { if (i <= 2) //0-2 { int k = ((i%3) * 5) + 7; // 7, 12, 17 if (k==12) k = 13; // change 12 to 13 //#pragma omp ordered adaptiveThreshold(img_gray, thresholds[i], 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV , k, 3); } else if (i <= 6) //3-6 { int k = i%2; // 0 or 1 int win = 18 + (k * 4); // 18 or 22 //#pragma omp ordered NiblackSauvolaWolfJolion (img_gray, thresholds[i], WOLFJOLION, win, win, 0.05 + (k * 0.35)); bitwise_not(thresholds[i], thresholds[i]); } else if (i <= 9) //7-9 { int k = (i%3) + 1; // 1,2,3 //#pragma omp ordered NiblackSauvolaWolfJolion (img_gray, thresholds[i], SAUVOLA, 12, 12, 0.18 * k); bitwise_not(thresholds[i], thresholds[i]); } } if (config->debugTiming) { timespec endTime; getTime(&endTime); cout << " -- Produce Threshold Time: " << diffclock(startTime, endTime) << "ms." << endl; } return thresholds; //threshold(img_equalized, img_threshold, 100, 255, THRESH_BINARY); } Mat equalizeBrightness(Mat img) { // Divide the image by its morphologically closed counterpart Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(19,19)); Mat closed; morphologyEx(img, closed, MORPH_CLOSE, kernel); img.convertTo(img, CV_32FC1); // divide requires floating-point divide(img, closed, img, 1, CV_32FC1); normalize(img, img, 0, 255, NORM_MINMAX); img.convertTo(img, CV_8U); // convert back to unsigned int return img; } void drawRotatedRect(Mat* img, RotatedRect rect, Scalar color, int thickness) { Point2f rect_points[4]; rect.points( rect_points ); for( int j = 0; j < 4; j++ ) line( *img, rect_points[j], rect_points[(j+1)%4], color, thickness, 8 ); } void fillMask(Mat img, const Mat mask, Scalar color) { for (int row = 0; row < img.rows; row++) { for (int col = 0; col < img.cols; col++) { int m = (int) mask.at<uchar>(row, col); if (m) { for (int z = 0; z < 3; z++) { int prevVal = img.at<Vec3b>(row, col)[z]; img.at<Vec3b>(row, col)[z] = ((int) color[z]) | prevVal; } } } } } void drawX(Mat img, Rect rect, Scalar color, int thickness) { Point tl(rect.x, rect.y); Point tr(rect.x + rect.width, rect.y); Point bl(rect.x, rect.y + rect.height); Point br(rect.x + rect.width, rect.y + rect.height); line(img, tl, br, color, thickness); line(img, bl, tr, color, thickness); } double distanceBetweenPoints(Point p1, Point p2) { float asquared = (p2.x - p1.x)*(p2.x - p1.x); float bsquared = (p2.y - p1.y)*(p2.y - p1.y); return sqrt(asquared + bsquared); } float angleBetweenPoints(Point p1, Point p2) { int deltaY = p2.y - p1.y; int deltaX = p2.x - p1.x; return atan2((float) deltaY, (float) deltaX) * (180 / CV_PI); } Size getSizeMaintainingAspect(Mat inputImg, int maxWidth, int maxHeight) { float aspect = ((float) inputImg.cols) / ((float) inputImg.rows); if (maxWidth / aspect > maxHeight) { return Size(maxHeight * aspect, maxHeight); } else { return Size(maxWidth, maxWidth / aspect); } } LineSegment::LineSegment() { init(0, 0, 0, 0); } LineSegment::LineSegment(Point p1, Point p2) { init(p1.x, p1.y, p2.x, p2.y); } LineSegment::LineSegment(int x1, int y1, int x2, int y2) { init(x1, y1, x2, y2); } void LineSegment::init(int x1, int y1, int x2, int y2) { this->p1 = Point(x1, y1); this->p2 = Point(x2, y2); if (p2.x - p1.x == 0) this->slope = 0.00000000001; else this->slope = (float) (p2.y - p1.y) / (float) (p2.x - p1.x); this->length = distanceBetweenPoints(p1, p2); this->angle = angleBetweenPoints(p1, p2); } bool LineSegment::isPointBelowLine( Point tp ){ return ((p2.x - p1.x)*(tp.y - p1.y) - (p2.y - p1.y)*(tp.x - p1.x)) > 0; } float LineSegment::getPointAt(float x) { return slope * (x - p2.x) + p2.y; } Point LineSegment::closestPointOnSegmentTo(Point p) { float top = (p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y)*(p2.y - p1.y); float bottom = distanceBetweenPoints(p2, p1); bottom = bottom * bottom; float u = top / bottom; float x = p1.x + u * (p2.x - p1.x); float y = p1.y + u * (p2.y - p1.y); return Point(x, y); } Point LineSegment::intersection(LineSegment line) { float c1, c2; float intersection_X = -1, intersection_Y= -1; c1 = p1.y - slope * p1.x; // which is same as y2 - slope * x2 c2 = line.p2.y - line.slope * line.p2.x; // which is same as y2 - slope * x2 if( (slope - line.slope) == 0) { //std::cout << "No Intersection between the lines" << endl; } else if (p1.x == p2.x) { // Line1 is vertical return Point(p1.x, line.getPointAt(p1.x)); } else if (line.p1.x == line.p2.x) { // Line2 is vertical return Point(line.p1.x, getPointAt(line.p1.x)); } else { intersection_X = (c2 - c1) / (slope - line.slope); intersection_Y = slope * intersection_X + c1; } return Point(intersection_X, intersection_Y); } Point LineSegment::midpoint() { // Handle the case where the line is vertical if (p1.x == p2.x) { float ydiff = p2.y-p1.y; float y = p1.y + (ydiff/2); return Point(p1.x, y); } float diff = p2.x - p1.x; float midX = ((float) p1.x) + (diff / 2); int midY = getPointAt(midX); return Point(midX, midY); } LineSegment LineSegment::getParallelLine(float distance) { float diff_x = p2.x - p1.x; float diff_y = p2.y - p1.y; float angle = atan2( diff_x, diff_y); float dist_x = distance * cos(angle); float dist_y = -distance * sin(angle); int offsetX = (int)round(dist_x); int offsetY = (int)round(dist_y); LineSegment result(p1.x + offsetX, p1.y + offsetY, p2.x + offsetX, p2.y + offsetY); return result; }
remove needless friend declaration Change-Id: Ib816e8126193a3477fca1334d7526743da0d4423
Be careful not to access a string out of bounds Change-Id: Ibc43ffa0c535e0baf1bb6d8b213320da345a3d65
cid#1202755 Clarify with assert that new_size == 0 cannot happen ...so arena->m_hash_shfit will never be negative and never cause undefined shift by negative value. Change-Id: Ifc3d28d53bae38bc8deea72473c81f1d043dc18e
/* * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright 2012, 2013 SAP AG. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ // According to the AIX OS doc #pragma alloca must be used // with C++ compiler before referencing the function alloca() #pragma alloca // no precompiled headers #include "classfile/classLoader.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmSymbols.hpp" #include "code/icBuffer.hpp" #include "code/vtableStubs.hpp" #include "compiler/compileBroker.hpp" #include "interpreter/interpreter.hpp" #include "jvm_aix.h" #include "libperfstat_aix.hpp" #include "loadlib_aix.hpp" #include "memory/allocation.inline.hpp" #include "memory/filemap.hpp" #include "mutex_aix.inline.hpp" #include "oops/oop.inline.hpp" #include "os_share_aix.hpp" #include "porting_aix.hpp" #include "prims/jniFastGetField.hpp" #include "prims/jvm.h" #include "prims/jvm_misc.hpp" #include "runtime/arguments.hpp" #include "runtime/extendedPC.hpp" #include "runtime/globals.hpp" #include "runtime/interfaceSupport.hpp" #include "runtime/java.hpp" #include "runtime/javaCalls.hpp" #include "runtime/mutexLocker.hpp" #include "runtime/objectMonitor.hpp" #include "runtime/osThread.hpp" #include "runtime/perfMemory.hpp" #include "runtime/sharedRuntime.hpp" #include "runtime/statSampler.hpp" #include "runtime/stubRoutines.hpp" #include "runtime/threadCritical.hpp" #include "runtime/timer.hpp" #include "services/attachListener.hpp" #include "services/runtimeService.hpp" #include "thread_aix.inline.hpp" #include "utilities/decoder.hpp" #include "utilities/defaultStream.hpp" #include "utilities/events.hpp" #include "utilities/growableArray.hpp" #include "utilities/vmError.hpp" #ifdef TARGET_ARCH_ppc # include "assembler_ppc.inline.hpp" # include "nativeInst_ppc.hpp" #endif #ifdef COMPILER1 #include "c1/c1_Runtime1.hpp" #endif #ifdef COMPILER2 #include "opto/runtime.hpp" #endif // put OS-includes here (sorted alphabetically) #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <poll.h> #include <procinfo.h> #include <pthread.h> #include <pwd.h> #include <semaphore.h> #include <signal.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/ipc.h> #include <sys/mman.h> #include <sys/resource.h> #include <sys/select.h> #include <sys/shm.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/sysinfo.h> #include <sys/systemcfg.h> #include <sys/time.h> #include <sys/times.h> #include <sys/types.h> #include <sys/utsname.h> #include <sys/vminfo.h> #include <sys/wait.h> // Add missing declarations (should be in procinfo.h but isn't until AIX 6.1). #if !defined(_AIXVERSION_610) extern "C" { int getthrds64(pid_t ProcessIdentifier, struct thrdentry64* ThreadBuffer, int ThreadSize, tid64_t* IndexPointer, int Count); } #endif // Excerpts from systemcfg.h definitions newer than AIX 5.3 #ifndef PV_7 # define PV_7 0x200000 // Power PC 7 # define PV_7_Compat 0x208000 // Power PC 7 #endif #define MAX_PATH (2 * K) // for timer info max values which include all bits #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) // for multipage initialization error analysis (in 'g_multipage_error') #define ERROR_MP_OS_TOO_OLD 100 #define ERROR_MP_EXTSHM_ACTIVE 101 #define ERROR_MP_VMGETINFO_FAILED 102 #define ERROR_MP_VMGETINFO_CLAIMS_NO_SUPPORT_FOR_64K 103 // the semantics in this file are thus that codeptr_t is a *real code ptr* // This means that any function taking codeptr_t as arguments will assume // a real codeptr and won't handle function descriptors (eg getFuncName), // whereas functions taking address as args will deal with function // descriptors (eg os::dll_address_to_library_name) typedef unsigned int* codeptr_t; // typedefs for stackslots, stack pointers, pointers to op codes typedef unsigned long stackslot_t; typedef stackslot_t* stackptr_t; // query dimensions of the stack of the calling thread static void query_stack_dimensions(address* p_stack_base, size_t* p_stack_size); // function to check a given stack pointer against given stack limits inline bool is_valid_stackpointer(stackptr_t sp, stackptr_t stack_base, size_t stack_size) { if (((uintptr_t)sp) & 0x7) { return false; } if (sp > stack_base) { return false; } if (sp < (stackptr_t) ((address)stack_base - stack_size)) { return false; } return true; } // returns true if function is a valid codepointer inline bool is_valid_codepointer(codeptr_t p) { if (!p) { return false; } if (((uintptr_t)p) & 0x3) { return false; } if (LoadedLibraries::find_for_text_address((address)p) == NULL) { return false; } return true; } // macro to check a given stack pointer against given stack limits and to die if test fails #define CHECK_STACK_PTR(sp, stack_base, stack_size) { \ guarantee(is_valid_stackpointer((stackptr_t)(sp), (stackptr_t)(stack_base), stack_size), "Stack Pointer Invalid"); \ } // macro to check the current stack pointer against given stacklimits #define CHECK_CURRENT_STACK_PTR(stack_base, stack_size) { \ address sp; \ sp = os::current_stack_pointer(); \ CHECK_STACK_PTR(sp, stack_base, stack_size); \ } //////////////////////////////////////////////////////////////////////////////// // global variables (for a description see os_aix.hpp) julong os::Aix::_physical_memory = 0; pthread_t os::Aix::_main_thread = ((pthread_t)0); int os::Aix::_page_size = -1; int os::Aix::_on_pase = -1; int os::Aix::_os_version = -1; int os::Aix::_stack_page_size = -1; size_t os::Aix::_shm_default_page_size = -1; int os::Aix::_can_use_64K_pages = -1; int os::Aix::_can_use_16M_pages = -1; int os::Aix::_xpg_sus_mode = -1; int os::Aix::_extshm = -1; int os::Aix::_logical_cpus = -1; //////////////////////////////////////////////////////////////////////////////// // local variables static int g_multipage_error = -1; // error analysis for multipage initialization static jlong initial_time_count = 0; static int clock_tics_per_sec = 100; static sigset_t check_signal_done; // For diagnostics to print a message once (see run_periodic_checks) static bool check_signals = true; static pid_t _initial_pid = 0; static int SR_signum = SIGUSR2; // Signal used to suspend/resume a thread (must be > SIGSEGV, see 4355769) static sigset_t SR_sigset; static pthread_mutex_t dl_mutex; // Used to protect dlsym() calls */ julong os::available_memory() { return Aix::available_memory(); } julong os::Aix::available_memory() { Unimplemented(); return 0; } julong os::physical_memory() { return Aix::physical_memory(); } //////////////////////////////////////////////////////////////////////////////// // environment support bool os::getenv(const char* name, char* buf, int len) { const char* val = ::getenv(name); if (val != NULL && strlen(val) < (size_t)len) { strcpy(buf, val); return true; } if (len > 0) buf[0] = 0; // return a null string return false; } // Return true if user is running as root. bool os::have_special_privileges() { static bool init = false; static bool privileges = false; if (!init) { privileges = (getuid() != geteuid()) || (getgid() != getegid()); init = true; } return privileges; } // Helper function, emulates disclaim64 using multiple 32bit disclaims // because we cannot use disclaim64() on AS/400 and old AIX releases. static bool my_disclaim64(char* addr, size_t size) { if (size == 0) { return true; } // Maximum size 32bit disclaim() accepts. (Theoretically 4GB, but I just do not trust that.) const unsigned int maxDisclaimSize = 0x80000000; const unsigned int numFullDisclaimsNeeded = (size / maxDisclaimSize); const unsigned int lastDisclaimSize = (size % maxDisclaimSize); char* p = addr; for (int i = 0; i < numFullDisclaimsNeeded; i ++) { if (::disclaim(p, maxDisclaimSize, DISCLAIM_ZEROMEM) != 0) { //if (Verbose) fprintf(stderr, "Cannot disclaim %p - %p (errno %d)\n", p, p + maxDisclaimSize, errno); return false; } p += maxDisclaimSize; } if (lastDisclaimSize > 0) { if (::disclaim(p, lastDisclaimSize, DISCLAIM_ZEROMEM) != 0) { //if (Verbose) fprintf(stderr, "Cannot disclaim %p - %p (errno %d)\n", p, p + lastDisclaimSize, errno); return false; } } return true; } // Cpu architecture string #if defined(PPC32) static char cpu_arch[] = "ppc"; #elif defined(PPC64) static char cpu_arch[] = "ppc64"; #else #error Add appropriate cpu_arch setting #endif // Given an address, returns the size of the page backing that address. size_t os::Aix::query_pagesize(void* addr) { vm_page_info pi; pi.addr = (uint64_t)addr; if (::vmgetinfo(&pi, VM_PAGE_INFO, sizeof(pi)) == 0) { return pi.pagesize; } else { fprintf(stderr, "vmgetinfo failed to retrieve page size for address %p (errno %d).\n", addr, errno); assert(false, "vmgetinfo failed to retrieve page size"); return SIZE_4K; } } // Returns the kernel thread id of the currently running thread. pid_t os::Aix::gettid() { return (pid_t) thread_self(); } void os::Aix::initialize_system_info() { // get the number of online(logical) cpus instead of configured os::_processor_count = sysconf(_SC_NPROCESSORS_ONLN); assert(_processor_count > 0, "_processor_count must be > 0"); // retrieve total physical storage os::Aix::meminfo_t mi; if (!os::Aix::get_meminfo(&mi)) { fprintf(stderr, "os::Aix::get_meminfo failed.\n"); fflush(stderr); assert(false, "os::Aix::get_meminfo failed."); } _physical_memory = (julong) mi.real_total; } // Helper function for tracing page sizes. static const char* describe_pagesize(size_t pagesize) { switch (pagesize) { case SIZE_4K : return "4K"; case SIZE_64K: return "64K"; case SIZE_16M: return "16M"; case SIZE_16G: return "16G"; default: assert(false, "surprise"); return "??"; } } // Retrieve information about multipage size support. Will initialize // Aix::_page_size, Aix::_stack_page_size, Aix::_can_use_64K_pages, // Aix::_can_use_16M_pages. // Must be called before calling os::large_page_init(). void os::Aix::query_multipage_support() { guarantee(_page_size == -1 && _stack_page_size == -1 && _can_use_64K_pages == -1 && _can_use_16M_pages == -1 && g_multipage_error == -1, "do not call twice"); _page_size = ::sysconf(_SC_PAGESIZE); // This really would surprise me. assert(_page_size == SIZE_4K, "surprise!"); // query default data page size (default page size for C-Heap, pthread stacks and .bss). // Default data page size is influenced either by linker options (-bdatapsize) // or by environment variable LDR_CNTRL (suboption DATAPSIZE). If none is given, // default should be 4K. size_t data_page_size = SIZE_4K; { void* p = ::malloc(SIZE_16M); data_page_size = os::Aix::query_pagesize(p); ::free(p); } // query default shm page size (LDR_CNTRL SHMPSIZE) { const int shmid = ::shmget(IPC_PRIVATE, 1, IPC_CREAT | S_IRUSR | S_IWUSR); guarantee(shmid != -1, "shmget failed"); void* p = ::shmat(shmid, NULL, 0); ::shmctl(shmid, IPC_RMID, NULL); guarantee(p != (void*) -1, "shmat failed"); _shm_default_page_size = os::Aix::query_pagesize(p); ::shmdt(p); } // before querying the stack page size, make sure we are not running as primordial // thread (because primordial thread's stack may have different page size than // pthread thread stacks). Running a VM on the primordial thread won't work for a // number of reasons so we may just as well guarantee it here guarantee(!os::Aix::is_primordial_thread(), "Must not be called for primordial thread"); // query stack page size { int dummy = 0; _stack_page_size = os::Aix::query_pagesize(&dummy); // everything else would surprise me and should be looked into guarantee(_stack_page_size == SIZE_4K || _stack_page_size == SIZE_64K, "Wrong page size"); // also, just for completeness: pthread stacks are allocated from C heap, so // stack page size should be the same as data page size guarantee(_stack_page_size == data_page_size, "stack page size should be the same as data page size"); } // EXTSHM is bad: among other things, it prevents setting pagesize dynamically // for system V shm. if (Aix::extshm()) { if (Verbose) { fprintf(stderr, "EXTSHM is active - will disable large page support.\n" "Please make sure EXTSHM is OFF for large page support.\n"); } g_multipage_error = ERROR_MP_EXTSHM_ACTIVE; _can_use_64K_pages = _can_use_16M_pages = 0; goto query_multipage_support_end; } // now check which page sizes the OS claims it supports, and of those, which actually can be used. { const int MAX_PAGE_SIZES = 4; psize_t sizes[MAX_PAGE_SIZES]; const int num_psizes = ::vmgetinfo(sizes, VMINFO_GETPSIZES, MAX_PAGE_SIZES); if (num_psizes == -1) { if (Verbose) { fprintf(stderr, "vmgetinfo(VMINFO_GETPSIZES) failed (errno: %d)\n", errno); fprintf(stderr, "disabling multipage support.\n"); } g_multipage_error = ERROR_MP_VMGETINFO_FAILED; _can_use_64K_pages = _can_use_16M_pages = 0; goto query_multipage_support_end; } guarantee(num_psizes > 0, "vmgetinfo(.., VMINFO_GETPSIZES, ...) failed."); assert(num_psizes <= MAX_PAGE_SIZES, "Surprise! more than 4 page sizes?"); if (Verbose) { fprintf(stderr, "vmgetinfo(.., VMINFO_GETPSIZES, ...) returns %d supported page sizes: ", num_psizes); for (int i = 0; i < num_psizes; i ++) { fprintf(stderr, " %s ", describe_pagesize(sizes[i])); } fprintf(stderr, " .\n"); } // Can we use 64K, 16M pages? _can_use_64K_pages = 0; _can_use_16M_pages = 0; for (int i = 0; i < num_psizes; i ++) { if (sizes[i] == SIZE_64K) { _can_use_64K_pages = 1; } else if (sizes[i] == SIZE_16M) { _can_use_16M_pages = 1; } } if (!_can_use_64K_pages) { g_multipage_error = ERROR_MP_VMGETINFO_CLAIMS_NO_SUPPORT_FOR_64K; } // Double-check for 16M pages: Even if AIX claims to be able to use 16M pages, // there must be an actual 16M page pool, and we must run with enough rights. if (_can_use_16M_pages) { const int shmid = ::shmget(IPC_PRIVATE, SIZE_16M, IPC_CREAT | S_IRUSR | S_IWUSR); guarantee(shmid != -1, "shmget failed"); struct shmid_ds shm_buf = { 0 }; shm_buf.shm_pagesize = SIZE_16M; const bool can_set_pagesize = ::shmctl(shmid, SHM_PAGESIZE, &shm_buf) == 0 ? true : false; const int en = errno; ::shmctl(shmid, IPC_RMID, NULL); if (!can_set_pagesize) { if (Verbose) { fprintf(stderr, "Failed to allocate even one misely 16M page. shmctl failed with %d (%s).\n" "Will deactivate 16M support.\n", en, strerror(en)); } _can_use_16M_pages = 0; } } } // end: check which pages can be used for shared memory query_multipage_support_end: guarantee(_page_size != -1 && _stack_page_size != -1 && _can_use_64K_pages != -1 && _can_use_16M_pages != -1, "Page sizes not properly initialized"); if (_can_use_64K_pages) { g_multipage_error = 0; } if (Verbose) { fprintf(stderr, "Data page size (C-Heap, bss, etc): %s\n", describe_pagesize(data_page_size)); fprintf(stderr, "Thread stack page size (pthread): %s\n", describe_pagesize(_stack_page_size)); fprintf(stderr, "Default shared memory page size: %s\n", describe_pagesize(_shm_default_page_size)); fprintf(stderr, "Can use 64K pages dynamically with shared meory: %s\n", (_can_use_64K_pages ? "yes" :"no")); fprintf(stderr, "Can use 16M pages dynamically with shared memory: %s\n", (_can_use_16M_pages ? "yes" :"no")); fprintf(stderr, "Multipage error details: %d\n", g_multipage_error); } } // end os::Aix::query_multipage_support() // The code for this method was initially derived from the version in os_linux.cpp void os::init_system_properties_values() { // The next few definitions allow the code to be verbatim: #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal) #define DEFAULT_LIBPATH "/usr/lib:/lib" #define EXTENSIONS_DIR "/lib/ext" #define ENDORSED_DIR "/lib/endorsed" // sysclasspath, java_home, dll_dir char *home_path; char *dll_path; char *pslash; char buf[MAXPATHLEN]; os::jvm_path(buf, sizeof(buf)); // Found the full path to libjvm.so. // Now cut the path to <java_home>/jre if we can. *(strrchr(buf, '/')) = '\0'; // get rid of /libjvm.so pslash = strrchr(buf, '/'); if (pslash != NULL) { *pslash = '\0'; // get rid of /{client|server|hotspot} } dll_path = malloc(strlen(buf) + 1); strcpy(dll_path, buf); Arguments::set_dll_dir(dll_path); if (pslash != NULL) { pslash = strrchr(buf, '/'); if (pslash != NULL) { *pslash = '\0'; // get rid of /<arch> pslash = strrchr(buf, '/'); if (pslash != NULL) { *pslash = '\0'; // get rid of /lib } } } home_path = malloc(strlen(buf) + 1); strcpy(home_path, buf); Arguments::set_java_home(home_path); if (!set_boot_path('/', ':')) return; // Where to look for native libraries // On Aix we get the user setting of LIBPATH // Eventually, all the library path setting will be done here. char *ld_library_path; // Construct the invariant part of ld_library_path. ld_library_path = (char *) malloc(sizeof(DEFAULT_LIBPATH)); sprintf(ld_library_path, DEFAULT_LIBPATH); // Get the user setting of LIBPATH, and prepended it. char *v = ::getenv("LIBPATH"); if (v == NULL) { v = ""; } char *t = ld_library_path; // That's +1 for the colon and +1 for the trailing '\0' ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1); sprintf(ld_library_path, "%s:%s", v, t); Arguments::set_library_path(ld_library_path); // Extensions directories char* cbuf = malloc(strlen(Arguments::get_java_home()) + sizeof(EXTENSIONS_DIR)); sprintf(cbuf, "%s" EXTENSIONS_DIR, Arguments::get_java_home()); Arguments::set_ext_dirs(cbuf); // Endorsed standards default directory. cbuf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR)); sprintf(cbuf, "%s" ENDORSED_DIR, Arguments::get_java_home()); Arguments::set_endorsed_dirs(cbuf); #undef malloc #undef DEFAULT_LIBPATH #undef EXTENSIONS_DIR #undef ENDORSED_DIR } //////////////////////////////////////////////////////////////////////////////// // breakpoint support void os::breakpoint() { BREAKPOINT; } extern "C" void breakpoint() { // use debugger to set breakpoint here } //////////////////////////////////////////////////////////////////////////////// // signal support debug_only(static bool signal_sets_initialized = false); static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; bool os::Aix::is_sig_ignored(int sig) { struct sigaction oact; sigaction(sig, (struct sigaction*)NULL, &oact); void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) : CAST_FROM_FN_PTR(void*, oact.sa_handler); if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) return true; else return false; } void os::Aix::signal_sets_init() { // Should also have an assertion stating we are still single-threaded. assert(!signal_sets_initialized, "Already initialized"); // Fill in signals that are necessarily unblocked for all threads in // the VM. Currently, we unblock the following signals: // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden // by -Xrs (=ReduceSignalUsage)); // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all // other threads. The "ReduceSignalUsage" boolean tells us not to alter // the dispositions or masks wrt these signals. // Programs embedding the VM that want to use the above signals for their // own purposes must, at this time, use the "-Xrs" option to prevent // interference with shutdown hooks and BREAK_SIGNAL thread dumping. // (See bug 4345157, and other related bugs). // In reality, though, unblocking these signals is really a nop, since // these signals are not blocked by default. sigemptyset(&unblocked_sigs); sigemptyset(&allowdebug_blocked_sigs); sigaddset(&unblocked_sigs, SIGILL); sigaddset(&unblocked_sigs, SIGSEGV); sigaddset(&unblocked_sigs, SIGBUS); sigaddset(&unblocked_sigs, SIGFPE); sigaddset(&unblocked_sigs, SIGTRAP); sigaddset(&unblocked_sigs, SIGDANGER); sigaddset(&unblocked_sigs, SR_signum); if (!ReduceSignalUsage) { if (!os::Aix::is_sig_ignored(SHUTDOWN1_SIGNAL)) { sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); } if (!os::Aix::is_sig_ignored(SHUTDOWN2_SIGNAL)) { sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); } if (!os::Aix::is_sig_ignored(SHUTDOWN3_SIGNAL)) { sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); } } // Fill in signals that are blocked by all but the VM thread. sigemptyset(&vm_sigs); if (!ReduceSignalUsage) sigaddset(&vm_sigs, BREAK_SIGNAL); debug_only(signal_sets_initialized = true); } // These are signals that are unblocked while a thread is running Java. // (For some reason, they get blocked by default.) sigset_t* os::Aix::unblocked_signals() { assert(signal_sets_initialized, "Not initialized"); return &unblocked_sigs; } // These are the signals that are blocked while a (non-VM) thread is // running Java. Only the VM thread handles these signals. sigset_t* os::Aix::vm_signals() { assert(signal_sets_initialized, "Not initialized"); return &vm_sigs; } // These are signals that are blocked during cond_wait to allow debugger in sigset_t* os::Aix::allowdebug_blocked_signals() { assert(signal_sets_initialized, "Not initialized"); return &allowdebug_blocked_sigs; } void os::Aix::hotspot_sigmask(Thread* thread) { //Save caller's signal mask before setting VM signal mask sigset_t caller_sigmask; pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); OSThread* osthread = thread->osthread(); osthread->set_caller_sigmask(caller_sigmask); pthread_sigmask(SIG_UNBLOCK, os::Aix::unblocked_signals(), NULL); if (!ReduceSignalUsage) { if (thread->is_VM_thread()) { // Only the VM thread handles BREAK_SIGNAL ... pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); } else { // ... all other threads block BREAK_SIGNAL pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); } } } // retrieve memory information. // Returns false if something went wrong; // content of pmi undefined in this case. bool os::Aix::get_meminfo(meminfo_t* pmi) { assert(pmi, "get_meminfo: invalid parameter"); memset(pmi, 0, sizeof(meminfo_t)); if (os::Aix::on_pase()) { Unimplemented(); return false; } else { // On AIX, I use the (dynamically loaded) perfstat library to retrieve memory statistics // See: // http://publib.boulder.ibm.com/infocenter/systems/index.jsp // ?topic=/com.ibm.aix.basetechref/doc/basetrf1/perfstat_memtot.htm // http://publib.boulder.ibm.com/infocenter/systems/index.jsp // ?topic=/com.ibm.aix.files/doc/aixfiles/libperfstat.h.htm perfstat_memory_total_t psmt; memset (&psmt, '\0', sizeof(psmt)); const int rc = libperfstat::perfstat_memory_total(NULL, &psmt, sizeof(psmt), 1); if (rc == -1) { fprintf(stderr, "perfstat_memory_total() failed (errno=%d)\n", errno); assert(0, "perfstat_memory_total() failed"); return false; } assert(rc == 1, "perfstat_memory_total() - weird return code"); // excerpt from // http://publib.boulder.ibm.com/infocenter/systems/index.jsp // ?topic=/com.ibm.aix.files/doc/aixfiles/libperfstat.h.htm // The fields of perfstat_memory_total_t: // u_longlong_t virt_total Total virtual memory (in 4 KB pages). // u_longlong_t real_total Total real memory (in 4 KB pages). // u_longlong_t real_free Free real memory (in 4 KB pages). // u_longlong_t pgsp_total Total paging space (in 4 KB pages). // u_longlong_t pgsp_free Free paging space (in 4 KB pages). pmi->virt_total = psmt.virt_total * 4096; pmi->real_total = psmt.real_total * 4096; pmi->real_free = psmt.real_free * 4096; pmi->pgsp_total = psmt.pgsp_total * 4096; pmi->pgsp_free = psmt.pgsp_free * 4096; return true; } } // end os::Aix::get_meminfo // Retrieve global cpu information. // Returns false if something went wrong; // the content of pci is undefined in this case. bool os::Aix::get_cpuinfo(cpuinfo_t* pci) { assert(pci, "get_cpuinfo: invalid parameter"); memset(pci, 0, sizeof(cpuinfo_t)); perfstat_cpu_total_t psct; memset (&psct, '\0', sizeof(psct)); if (-1 == libperfstat::perfstat_cpu_total(NULL, &psct, sizeof(perfstat_cpu_total_t), 1)) { fprintf(stderr, "perfstat_cpu_total() failed (errno=%d)\n", errno); assert(0, "perfstat_cpu_total() failed"); return false; } // global cpu information strcpy (pci->description, psct.description); pci->processorHZ = psct.processorHZ; pci->ncpus = psct.ncpus; os::Aix::_logical_cpus = psct.ncpus; for (int i = 0; i < 3; i++) { pci->loadavg[i] = (double) psct.loadavg[i] / (1 << SBITS); } // get the processor version from _system_configuration switch (_system_configuration.version) { case PV_7: strcpy(pci->version, "Power PC 7"); break; case PV_6_1: strcpy(pci->version, "Power PC 6 DD1.x"); break; case PV_6: strcpy(pci->version, "Power PC 6"); break; case PV_5: strcpy(pci->version, "Power PC 5"); break; case PV_5_2: strcpy(pci->version, "Power PC 5_2"); break; case PV_5_3: strcpy(pci->version, "Power PC 5_3"); break; case PV_5_Compat: strcpy(pci->version, "PV_5_Compat"); break; case PV_6_Compat: strcpy(pci->version, "PV_6_Compat"); break; case PV_7_Compat: strcpy(pci->version, "PV_7_Compat"); break; default: strcpy(pci->version, "unknown"); } return true; } //end os::Aix::get_cpuinfo ////////////////////////////////////////////////////////////////////////////// // detecting pthread library void os::Aix::libpthread_init() { return; } ////////////////////////////////////////////////////////////////////////////// // create new thread // Thread start routine for all newly created threads static void *java_start(Thread *thread) { // find out my own stack dimensions { // actually, this should do exactly the same as thread->record_stack_base_and_size... address base = 0; size_t size = 0; query_stack_dimensions(&base, &size); thread->set_stack_base(base); thread->set_stack_size(size); } // Do some sanity checks. CHECK_CURRENT_STACK_PTR(thread->stack_base(), thread->stack_size()); // Try to randomize the cache line index of hot stack frames. // This helps when threads of the same stack traces evict each other's // cache lines. The threads can be either from the same JVM instance, or // from different JVM instances. The benefit is especially true for // processors with hyperthreading technology. static int counter = 0; int pid = os::current_process_id(); alloca(((pid ^ counter++) & 7) * 128); ThreadLocalStorage::set_thread(thread); OSThread* osthread = thread->osthread(); // thread_id is kernel thread id (similar to Solaris LWP id) osthread->set_thread_id(os::Aix::gettid()); // initialize signal mask for this thread os::Aix::hotspot_sigmask(thread); // initialize floating point control register os::Aix::init_thread_fpu_state(); assert(osthread->get_state() == RUNNABLE, "invalid os thread state"); // call one more level start routine thread->run(); return 0; } bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { // We want the whole function to be synchronized. ThreadCritical cs; assert(thread->osthread() == NULL, "caller responsible"); // Allocate the OSThread object OSThread* osthread = new OSThread(NULL, NULL); if (osthread == NULL) { return false; } // set the correct thread state osthread->set_thread_type(thr_type); // Initial state is ALLOCATED but not INITIALIZED osthread->set_state(ALLOCATED); thread->set_osthread(osthread); // init thread attributes pthread_attr_t attr; pthread_attr_init(&attr); guarantee(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0, "???"); // Make sure we run in 1:1 kernel-user-thread mode. if (os::Aix::on_aix()) { guarantee(pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) == 0, "???"); guarantee(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) == 0, "???"); } // end: aix // Start in suspended state, and in os::thread_start, wake the thread up. guarantee(pthread_attr_setsuspendstate_np(&attr, PTHREAD_CREATE_SUSPENDED_NP) == 0, "???"); // calculate stack size if it's not specified by caller if (os::Aix::supports_variable_stack_size()) { if (stack_size == 0) { stack_size = os::Aix::default_stack_size(thr_type); switch (thr_type) { case os::java_thread: // Java threads use ThreadStackSize whose default value can be changed with the flag -Xss. assert(JavaThread::stack_size_at_create() > 0, "this should be set"); stack_size = JavaThread::stack_size_at_create(); break; case os::compiler_thread: if (CompilerThreadStackSize > 0) { stack_size = (size_t)(CompilerThreadStackSize * K); break; } // else fall through: // use VMThreadStackSize if CompilerThreadStackSize is not defined case os::vm_thread: case os::pgc_thread: case os::cgc_thread: case os::watcher_thread: if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); break; } } stack_size = MAX2(stack_size, os::Aix::min_stack_allowed); pthread_attr_setstacksize(&attr, stack_size); } //else let thread_create() pick the default value (96 K on AIX) pthread_t tid; int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); pthread_attr_destroy(&attr); if (ret != 0) { if (PrintMiscellaneous && (Verbose || WizardMode)) { perror("pthread_create()"); } // Need to clean up stuff we've allocated so far thread->set_osthread(NULL); delete osthread; return false; } // Store pthread info into the OSThread osthread->set_pthread_id(tid); return true; } ///////////////////////////////////////////////////////////////////////////// // attach existing thread // bootstrap the main thread bool os::create_main_thread(JavaThread* thread) { assert(os::Aix::_main_thread == pthread_self(), "should be called inside main thread"); return create_attached_thread(thread); } bool os::create_attached_thread(JavaThread* thread) { #ifdef ASSERT thread->verify_not_published(); #endif // Allocate the OSThread object OSThread* osthread = new OSThread(NULL, NULL); if (osthread == NULL) { return false; } // Store pthread info into the OSThread osthread->set_thread_id(os::Aix::gettid()); osthread->set_pthread_id(::pthread_self()); // initialize floating point control register os::Aix::init_thread_fpu_state(); // some sanity checks CHECK_CURRENT_STACK_PTR(thread->stack_base(), thread->stack_size()); // Initial thread state is RUNNABLE osthread->set_state(RUNNABLE); thread->set_osthread(osthread); if (UseNUMA) { int lgrp_id = os::numa_get_group_id(); if (lgrp_id != -1) { thread->set_lgrp_id(lgrp_id); } } // initialize signal mask for this thread // and save the caller's signal mask os::Aix::hotspot_sigmask(thread); return true; } void os::pd_start_thread(Thread* thread) { int status = pthread_continue_np(thread->osthread()->pthread_id()); assert(status == 0, "thr_continue failed"); } // Free OS resources related to the OSThread void os::free_thread(OSThread* osthread) { assert(osthread != NULL, "osthread not set"); if (Thread::current()->osthread() == osthread) { // Restore caller's signal mask sigset_t sigmask = osthread->caller_sigmask(); pthread_sigmask(SIG_SETMASK, &sigmask, NULL); } delete osthread; } ////////////////////////////////////////////////////////////////////////////// // thread local storage int os::allocate_thread_local_storage() { pthread_key_t key; int rslt = pthread_key_create(&key, NULL); assert(rslt == 0, "cannot allocate thread local storage"); return (int)key; } // Note: This is currently not used by VM, as we don't destroy TLS key // on VM exit. void os::free_thread_local_storage(int index) { int rslt = pthread_key_delete((pthread_key_t)index); assert(rslt == 0, "invalid index"); } void os::thread_local_storage_at_put(int index, void* value) { int rslt = pthread_setspecific((pthread_key_t)index, value); assert(rslt == 0, "pthread_setspecific failed"); } extern "C" Thread* get_thread() { return ThreadLocalStorage::thread(); } //////////////////////////////////////////////////////////////////////////////// // time support // Time since start-up in seconds to a fine granularity. // Used by VMSelfDestructTimer and the MemProfiler. double os::elapsedTime() { return (double)(os::elapsed_counter()) * 0.000001; } jlong os::elapsed_counter() { timeval time; int status = gettimeofday(&time, NULL); return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count; } jlong os::elapsed_frequency() { return (1000 * 1000); } // For now, we say that linux does not support vtime. I have no idea // whether it can actually be made to (DLD, 9/13/05). bool os::supports_vtime() { return false; } bool os::enable_vtime() { return false; } bool os::vtime_enabled() { return false; } double os::elapsedVTime() { // better than nothing, but not much return elapsedTime(); } jlong os::javaTimeMillis() { timeval time; int status = gettimeofday(&time, NULL); assert(status != -1, "aix error at gettimeofday()"); return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); } // We need to manually declare mread_real_time, // because IBM didn't provide a prototype in time.h. // (they probably only ever tested in C, not C++) extern "C" int mread_real_time(timebasestruct_t *t, size_t size_of_timebasestruct_t); jlong os::javaTimeNanos() { if (os::Aix::on_pase()) { Unimplemented(); return 0; } else { // On AIX use the precision of processors real time clock // or time base registers. timebasestruct_t time; int rc; // If the CPU has a time register, it will be used and // we have to convert to real time first. After convertion we have following data: // time.tb_high [seconds since 00:00:00 UTC on 1.1.1970] // time.tb_low [nanoseconds after the last full second above] // We better use mread_real_time here instead of read_real_time // to ensure that we will get a monotonic increasing time. if (mread_real_time(&time, TIMEBASE_SZ) != RTC_POWER) { rc = time_base_to_time(&time, TIMEBASE_SZ); assert(rc != -1, "aix error at time_base_to_time()"); } return jlong(time.tb_high) * (1000 * 1000 * 1000) + jlong(time.tb_low); } } void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { { // gettimeofday - based on time in seconds since the Epoch thus does not wrap info_ptr->max_value = ALL_64_BITS; // gettimeofday is a real time clock so it skips info_ptr->may_skip_backward = true; info_ptr->may_skip_forward = true; } info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time } // Return the real, user, and system times in seconds from an // arbitrary fixed point in the past. bool os::getTimesSecs(double* process_real_time, double* process_user_time, double* process_system_time) { Unimplemented(); return false; } char * os::local_time_string(char *buf, size_t buflen) { struct tm t; time_t long_time; time(&long_time); localtime_r(&long_time, &t); jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); return buf; } struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { return localtime_r(clock, res); } //////////////////////////////////////////////////////////////////////////////// // runtime exit support // Note: os::shutdown() might be called very early during initialization, or // called from signal handler. Before adding something to os::shutdown(), make // sure it is async-safe and can handle partially initialized VM. void os::shutdown() { // allow PerfMemory to attempt cleanup of any persistent resources perfMemory_exit(); // needs to remove object in file system AttachListener::abort(); // flush buffered output, finish log files ostream_abort(); // Check for abort hook abort_hook_t abort_hook = Arguments::abort_hook(); if (abort_hook != NULL) { abort_hook(); } } // Note: os::abort() might be called very early during initialization, or // called from signal handler. Before adding something to os::abort(), make // sure it is async-safe and can handle partially initialized VM. void os::abort(bool dump_core) { os::shutdown(); if (dump_core) { #ifndef PRODUCT fdStream out(defaultStream::output_fd()); out.print_raw("Current thread is "); char buf[16]; jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); out.print_raw_cr(buf); out.print_raw_cr("Dumping core ..."); #endif ::abort(); // dump core } ::exit(1); } // Die immediately, no exit hook, no abort hook, no cleanup. void os::die() { ::abort(); } // Unused on Aix for now. void os::set_error_file(const char *logfile) {} // This method is a copy of JDK's sysGetLastErrorString // from src/solaris/hpi/src/system_md.c size_t os::lasterror(char *buf, size_t len) { if (errno == 0) return 0; const char *s = ::strerror(errno); size_t n = ::strlen(s); if (n >= len) { n = len - 1; } ::strncpy(buf, s, n); buf[n] = '\0'; return n; } intx os::current_thread_id() { return (intx)pthread_self(); } int os::current_process_id() { // This implementation returns a unique pid, the pid of the // launcher thread that starts the vm 'process'. // Under POSIX, getpid() returns the same pid as the // launcher thread rather than a unique pid per thread. // Use gettid() if you want the old pre NPTL behaviour. // if you are looking for the result of a call to getpid() that // returns a unique pid for the calling thread, then look at the // OSThread::thread_id() method in osThread_linux.hpp file return (int)(_initial_pid ? _initial_pid : getpid()); } // DLL functions const char* os::dll_file_extension() { return ".so"; } // This must be hard coded because it's the system's temporary // directory not the java application's temp directory, ala java.io.tmpdir. const char* os::get_temp_directory() { return "/tmp"; } static bool file_exists(const char* filename) { struct stat statbuf; if (filename == NULL || strlen(filename) == 0) { return false; } return os::stat(filename, &statbuf) == 0; } bool os::dll_build_name(char* buffer, size_t buflen, const char* pname, const char* fname) { bool retval = false; // Copied from libhpi const size_t pnamelen = pname ? strlen(pname) : 0; // Return error on buffer overflow. if (pnamelen + strlen(fname) + 10 > (size_t) buflen) { *buffer = '\0'; return retval; } if (pnamelen == 0) { snprintf(buffer, buflen, "lib%s.so", fname); retval = true; } else if (strchr(pname, *os::path_separator()) != NULL) { int n; char** pelements = split_path(pname, &n); for (int i = 0; i < n; i++) { // Really shouldn't be NULL, but check can't hurt if (pelements[i] == NULL || strlen(pelements[i]) == 0) { continue; // skip the empty path values } snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname); if (file_exists(buffer)) { retval = true; break; } } // release the storage for (int i = 0; i < n; i++) { if (pelements[i] != NULL) { FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); } } if (pelements != NULL) { FREE_C_HEAP_ARRAY(char*, pelements, mtInternal); } } else { snprintf(buffer, buflen, "%s/lib%s.so", pname, fname); retval = true; } return retval; } // Check if addr is inside libjvm.so. bool os::address_is_in_vm(address addr) { // Input could be a real pc or a function pointer literal. The latter // would be a function descriptor residing in the data segment of a module. const LoadedLibraryModule* lib = LoadedLibraries::find_for_text_address(addr); if (lib) { if (strcmp(lib->get_shortname(), "libjvm.so") == 0) { return true; } else { return false; } } else { lib = LoadedLibraries::find_for_data_address(addr); if (lib) { if (strcmp(lib->get_shortname(), "libjvm.so") == 0) { return true; } else { return false; } } else { return false; } } } // Resolve an AIX function descriptor literal to a code pointer. // If the input is a valid code pointer to a text segment of a loaded module, // it is returned unchanged. // If the input is a valid AIX function descriptor, it is resolved to the // code entry point. // If the input is neither a valid function descriptor nor a valid code pointer, // NULL is returned. static address resolve_function_descriptor_to_code_pointer(address p) { const LoadedLibraryModule* lib = LoadedLibraries::find_for_text_address(p); if (lib) { // its a real code pointer return p; } else { lib = LoadedLibraries::find_for_data_address(p); if (lib) { // pointer to data segment, potential function descriptor address code_entry = (address)(((FunctionDescriptor*)p)->entry()); if (LoadedLibraries::find_for_text_address(code_entry)) { // Its a function descriptor return code_entry; } } } return NULL; } bool os::dll_address_to_function_name(address addr, char *buf, int buflen, int *offset) { if (offset) { *offset = -1; } if (buf) { buf[0] = '\0'; } // Resolve function ptr literals first. addr = resolve_function_descriptor_to_code_pointer(addr); if (!addr) { return false; } // Go through Decoder::decode to call getFuncName which reads the name from the traceback table. return Decoder::decode(addr, buf, buflen, offset); } static int getModuleName(codeptr_t pc, // [in] program counter char* p_name, size_t namelen, // [out] optional: function name char* p_errmsg, size_t errmsglen // [out] optional: user provided buffer for error messages ) { // initialize output parameters if (p_name && namelen > 0) { *p_name = '\0'; } if (p_errmsg && errmsglen > 0) { *p_errmsg = '\0'; } const LoadedLibraryModule* const lib = LoadedLibraries::find_for_text_address((address)pc); if (lib) { if (p_name && namelen > 0) { sprintf(p_name, "%.*s", namelen, lib->get_shortname()); } return 0; } if (Verbose) { fprintf(stderr, "pc outside any module"); } return -1; } bool os::dll_address_to_library_name(address addr, char* buf, int buflen, int* offset) { if (offset) { *offset = -1; } if (buf) { buf[0] = '\0'; } // Resolve function ptr literals first. addr = resolve_function_descriptor_to_code_pointer(addr); if (!addr) { return false; } if (::getModuleName((codeptr_t) addr, buf, buflen, 0, 0) == 0) { return true; } return false; } // Loads .dll/.so and in case of error it checks if .dll/.so was built // for the same architecture as Hotspot is running on void *os::dll_load(const char *filename, char *ebuf, int ebuflen) { if (ebuf && ebuflen > 0) { ebuf[0] = '\0'; ebuf[ebuflen - 1] = '\0'; } if (!filename || strlen(filename) == 0) { ::strncpy(ebuf, "dll_load: empty filename specified", ebuflen - 1); return NULL; } // RTLD_LAZY is currently not implemented. The dl is loaded immediately with all its dependants. void * result= ::dlopen(filename, RTLD_LAZY); if (result != NULL) { // Reload dll cache. Don't do this in signal handling. LoadedLibraries::reload(); return result; } else { // error analysis when dlopen fails const char* const error_report = ::dlerror(); if (error_report && ebuf && ebuflen > 0) { snprintf(ebuf, ebuflen - 1, "%s, LIBPATH=%s, LD_LIBRARY_PATH=%s : %s", filename, ::getenv("LIBPATH"), ::getenv("LD_LIBRARY_PATH"), error_report); } } return NULL; } // Glibc-2.0 libdl is not MT safe. If you are building with any glibc, // chances are you might want to run the generated bits against glibc-2.0 // libdl.so, so always use locking for any version of glibc. void* os::dll_lookup(void* handle, const char* name) { pthread_mutex_lock(&dl_mutex); void* res = dlsym(handle, name); pthread_mutex_unlock(&dl_mutex); return res; } void os::print_dll_info(outputStream *st) { st->print_cr("Dynamic libraries:"); LoadedLibraries::print(st); } void os::print_os_info(outputStream* st) { st->print("OS:"); st->print("uname:"); struct utsname name; uname(&name); st->print(name.sysname); st->print(" "); st->print(name.nodename); st->print(" "); st->print(name.release); st->print(" "); st->print(name.version); st->print(" "); st->print(name.machine); st->cr(); // rlimit st->print("rlimit:"); struct rlimit rlim; st->print(" STACK "); getrlimit(RLIMIT_STACK, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%uk", rlim.rlim_cur >> 10); st->print(", CORE "); getrlimit(RLIMIT_CORE, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%uk", rlim.rlim_cur >> 10); st->print(", NPROC "); st->print("%d", sysconf(_SC_CHILD_MAX)); st->print(", NOFILE "); getrlimit(RLIMIT_NOFILE, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%d", rlim.rlim_cur); st->print(", AS "); getrlimit(RLIMIT_AS, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%uk", rlim.rlim_cur >> 10); // Print limits on DATA, because it limits the C-heap. st->print(", DATA "); getrlimit(RLIMIT_DATA, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%uk", rlim.rlim_cur >> 10); st->cr(); // load average st->print("load average:"); double loadavg[3] = {-1.L, -1.L, -1.L}; os::loadavg(loadavg, 3); st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); st->cr(); } void os::print_memory_info(outputStream* st) { st->print_cr("Memory:"); st->print_cr(" default page size: %s", describe_pagesize(os::vm_page_size())); st->print_cr(" default stack page size: %s", describe_pagesize(os::vm_page_size())); st->print_cr(" default shm page size: %s", describe_pagesize(os::Aix::shm_default_page_size())); st->print_cr(" can use 64K pages dynamically: %s", (os::Aix::can_use_64K_pages() ? "yes" :"no")); st->print_cr(" can use 16M pages dynamically: %s", (os::Aix::can_use_16M_pages() ? "yes" :"no")); if (g_multipage_error != 0) { st->print_cr(" multipage error: %d", g_multipage_error); } // print out LDR_CNTRL because it affects the default page sizes const char* const ldr_cntrl = ::getenv("LDR_CNTRL"); st->print_cr(" LDR_CNTRL=%s.", ldr_cntrl ? ldr_cntrl : "<unset>"); const char* const extshm = ::getenv("EXTSHM"); st->print_cr(" EXTSHM=%s.", extshm ? extshm : "<unset>"); // Call os::Aix::get_meminfo() to retrieve memory statistics. os::Aix::meminfo_t mi; if (os::Aix::get_meminfo(&mi)) { char buffer[256]; if (os::Aix::on_aix()) { jio_snprintf(buffer, sizeof(buffer), " physical total : %llu\n" " physical free : %llu\n" " swap total : %llu\n" " swap free : %llu\n", mi.real_total, mi.real_free, mi.pgsp_total, mi.pgsp_free); } else { Unimplemented(); } st->print_raw(buffer); } else { st->print_cr(" (no more information available)"); } } void os::pd_print_cpu_info(outputStream* st) { // cpu st->print("CPU:"); st->print("total %d", os::processor_count()); // It's not safe to query number of active processors after crash // st->print("(active %d)", os::active_processor_count()); st->print(" %s", VM_Version::cpu_features()); st->cr(); } void os::print_siginfo(outputStream* st, void* siginfo) { // Use common posix version. os::Posix::print_siginfo_brief(st, (const siginfo_t*) siginfo); st->cr(); } static void print_signal_handler(outputStream* st, int sig, char* buf, size_t buflen); void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { st->print_cr("Signal Handlers:"); print_signal_handler(st, SIGSEGV, buf, buflen); print_signal_handler(st, SIGBUS , buf, buflen); print_signal_handler(st, SIGFPE , buf, buflen); print_signal_handler(st, SIGPIPE, buf, buflen); print_signal_handler(st, SIGXFSZ, buf, buflen); print_signal_handler(st, SIGILL , buf, buflen); print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); print_signal_handler(st, SR_signum, buf, buflen); print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); print_signal_handler(st, BREAK_SIGNAL, buf, buflen); print_signal_handler(st, SIGTRAP, buf, buflen); print_signal_handler(st, SIGDANGER, buf, buflen); } static char saved_jvm_path[MAXPATHLEN] = {0}; // Find the full path to the current module, libjvm.so or libjvm_g.so void os::jvm_path(char *buf, jint buflen) { // Error checking. if (buflen < MAXPATHLEN) { assert(false, "must use a large-enough buffer"); buf[0] = '\0'; return; } // Lazy resolve the path to current module. if (saved_jvm_path[0] != 0) { strcpy(buf, saved_jvm_path); return; } Dl_info dlinfo; int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo); assert(ret != 0, "cannot locate libjvm"); char* rp = realpath((char *)dlinfo.dli_fname, buf); assert(rp != NULL, "error in realpath(): maybe the 'path' argument is too long?"); strcpy(saved_jvm_path, buf); } void os::print_jni_name_prefix_on(outputStream* st, int args_size) { // no prefix required, not even "_" } void os::print_jni_name_suffix_on(outputStream* st, int args_size) { // no suffix required } //////////////////////////////////////////////////////////////////////////////// // sun.misc.Signal support static volatile jint sigint_count = 0; static void UserHandler(int sig, void *siginfo, void *context) { // 4511530 - sem_post is serialized and handled by the manager thread. When // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We // don't want to flood the manager thread with sem_post requests. if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) return; // Ctrl-C is pressed during error reporting, likely because the error // handler fails to abort. Let VM die immediately. if (sig == SIGINT && is_error_reported()) { os::die(); } os::signal_notify(sig); } void* os::user_handler() { return CAST_FROM_FN_PTR(void*, UserHandler); } extern "C" { typedef void (*sa_handler_t)(int); typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); } void* os::signal(int signal_number, void* handler) { struct sigaction sigAct, oldSigAct; sigfillset(&(sigAct.sa_mask)); // Do not block out synchronous signals in the signal handler. // Blocking synchronous signals only makes sense if you can really // be sure that those signals won't happen during signal handling, // when the blocking applies. Normal signal handlers are lean and // do not cause signals. But our signal handlers tend to be "risky" // - secondary SIGSEGV, SIGILL, SIGBUS' may and do happen. // On AIX, PASE there was a case where a SIGSEGV happened, followed // by a SIGILL, which was blocked due to the signal mask. The process // just hung forever. Better to crash from a secondary signal than to hang. sigdelset(&(sigAct.sa_mask), SIGSEGV); sigdelset(&(sigAct.sa_mask), SIGBUS); sigdelset(&(sigAct.sa_mask), SIGILL); sigdelset(&(sigAct.sa_mask), SIGFPE); sigdelset(&(sigAct.sa_mask), SIGTRAP); sigAct.sa_flags = SA_RESTART|SA_SIGINFO; sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); if (sigaction(signal_number, &sigAct, &oldSigAct)) { // -1 means registration failed return (void *)-1; } return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); } void os::signal_raise(int signal_number) { ::raise(signal_number); } // // The following code is moved from os.cpp for making this // code platform specific, which it is by its very nature. // // Will be modified when max signal is changed to be dynamic int os::sigexitnum_pd() { return NSIG; } // a counter for each possible signal value static volatile jint pending_signals[NSIG+1] = { 0 }; // Linux(POSIX) specific hand shaking semaphore. static sem_t sig_sem; void os::signal_init_pd() { // Initialize signal structures ::memset((void*)pending_signals, 0, sizeof(pending_signals)); // Initialize signal semaphore int rc = ::sem_init(&sig_sem, 0, 0); guarantee(rc != -1, "sem_init failed"); } void os::signal_notify(int sig) { Atomic::inc(&pending_signals[sig]); ::sem_post(&sig_sem); } static int check_pending_signals(bool wait) { Atomic::store(0, &sigint_count); for (;;) { for (int i = 0; i < NSIG + 1; i++) { jint n = pending_signals[i]; if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { return i; } } if (!wait) { return -1; } JavaThread *thread = JavaThread::current(); ThreadBlockInVM tbivm(thread); bool threadIsSuspended; do { thread->set_suspend_equivalent(); // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() ::sem_wait(&sig_sem); // were we externally suspended while we were waiting? threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); if (threadIsSuspended) { // // The semaphore has been incremented, but while we were waiting // another thread suspended us. We don't want to continue running // while suspended because that would surprise the thread that // suspended us. // ::sem_post(&sig_sem); thread->java_suspend_self(); } } while (threadIsSuspended); } } int os::signal_lookup() { return check_pending_signals(false); } int os::signal_wait() { return check_pending_signals(true); } //////////////////////////////////////////////////////////////////////////////// // Virtual Memory // AddrRange describes an immutable address range // // This is a helper class for the 'shared memory bookkeeping' below. class AddrRange { friend class ShmBkBlock; char* _start; size_t _size; public: AddrRange(char* start, size_t size) : _start(start), _size(size) {} AddrRange(const AddrRange& r) : _start(r.start()), _size(r.size()) {} char* start() const { return _start; } size_t size() const { return _size; } char* end() const { return _start + _size; } bool is_empty() const { return _size == 0 ? true : false; } static AddrRange empty_range() { return AddrRange(NULL, 0); } bool contains(const char* p) const { return start() <= p && end() > p; } bool contains(const AddrRange& range) const { return start() <= range.start() && end() >= range.end(); } bool intersects(const AddrRange& range) const { return (range.start() <= start() && range.end() > start()) || (range.start() < end() && range.end() >= end()) || contains(range); } bool is_same_range(const AddrRange& range) const { return start() == range.start() && size() == range.size(); } // return the closest inside range consisting of whole pages AddrRange find_closest_aligned_range(size_t pagesize) const { if (pagesize == 0 || is_empty()) { return empty_range(); } char* const from = (char*)align_size_up((intptr_t)_start, pagesize); char* const to = (char*)align_size_down((intptr_t)end(), pagesize); if (from > to) { return empty_range(); } return AddrRange(from, to - from); } }; //////////////////////////////////////////////////////////////////////////// // shared memory bookkeeping // // the os::reserve_memory() API and friends hand out different kind of memory, depending // on need and circumstances. Memory may be allocated with mmap() or with shmget/shmat. // // But these memory types have to be treated differently. For example, to uncommit // mmap-based memory, msync(MS_INVALIDATE) is needed, to uncommit shmat-based memory, // disclaim64() is needed. // // Therefore we need to keep track of the allocated memory segments and their // properties. // ShmBkBlock: base class for all blocks in the shared memory bookkeeping class ShmBkBlock { ShmBkBlock* _next; protected: AddrRange _range; const size_t _pagesize; const bool _pinned; public: ShmBkBlock(AddrRange range, size_t pagesize, bool pinned) : _range(range), _pagesize(pagesize), _pinned(pinned) , _next(NULL) { assert(_pagesize == SIZE_4K || _pagesize == SIZE_64K || _pagesize == SIZE_16M, "invalid page size"); assert(!_range.is_empty(), "invalid range"); } virtual void print(outputStream* st) const { st->print("0x%p ... 0x%p (%llu) - %d %s pages - %s", _range.start(), _range.end(), _range.size(), _range.size() / _pagesize, describe_pagesize(_pagesize), _pinned ? "pinned" : ""); } enum Type { MMAP, SHMAT }; virtual Type getType() = 0; char* base() const { return _range.start(); } size_t size() const { return _range.size(); } void setAddrRange(AddrRange range) { _range = range; } bool containsAddress(const char* p) const { return _range.contains(p); } bool containsRange(const char* p, size_t size) const { return _range.contains(AddrRange((char*)p, size)); } bool isSameRange(const char* p, size_t size) const { return _range.is_same_range(AddrRange((char*)p, size)); } virtual bool disclaim(char* p, size_t size) = 0; virtual bool release() = 0; // blocks live in a list. ShmBkBlock* next() const { return _next; } void set_next(ShmBkBlock* blk) { _next = blk; } }; // end: ShmBkBlock // ShmBkMappedBlock: describes an block allocated with mmap() class ShmBkMappedBlock : public ShmBkBlock { public: ShmBkMappedBlock(AddrRange range) : ShmBkBlock(range, SIZE_4K, false) {} // mmap: always 4K, never pinned void print(outputStream* st) const { ShmBkBlock::print(st); st->print_cr(" - mmap'ed"); } Type getType() { return MMAP; } bool disclaim(char* p, size_t size) { AddrRange r(p, size); guarantee(_range.contains(r), "invalid disclaim"); // only disclaim whole ranges. const AddrRange r2 = r.find_closest_aligned_range(_pagesize); if (r2.is_empty()) { return true; } const int rc = ::msync(r2.start(), r2.size(), MS_INVALIDATE); if (rc != 0) { warning("msync(0x%p, %llu, MS_INVALIDATE) failed (%d)\n", r2.start(), r2.size(), errno); } return rc == 0 ? true : false; } bool release() { // mmap'ed blocks are released using munmap if (::munmap(_range.start(), _range.size()) != 0) { warning("munmap(0x%p, %llu) failed (%d)\n", _range.start(), _range.size(), errno); return false; } return true; } }; // end: ShmBkMappedBlock // ShmBkShmatedBlock: describes an block allocated with shmget/shmat() class ShmBkShmatedBlock : public ShmBkBlock { public: ShmBkShmatedBlock(AddrRange range, size_t pagesize, bool pinned) : ShmBkBlock(range, pagesize, pinned) {} void print(outputStream* st) const { ShmBkBlock::print(st); st->print_cr(" - shmat'ed"); } Type getType() { return SHMAT; } bool disclaim(char* p, size_t size) { AddrRange r(p, size); if (_pinned) { return true; } // shmat'ed blocks are disclaimed using disclaim64 guarantee(_range.contains(r), "invalid disclaim"); // only disclaim whole ranges. const AddrRange r2 = r.find_closest_aligned_range(_pagesize); if (r2.is_empty()) { return true; } const bool rc = my_disclaim64(r2.start(), r2.size()); if (Verbose && !rc) { warning("failed to disclaim shm %p-%p\n", r2.start(), r2.end()); } return rc; } bool release() { bool rc = false; if (::shmdt(_range.start()) != 0) { warning("shmdt(0x%p) failed (%d)\n", _range.start(), errno); } else { rc = true; } return rc; } }; // end: ShmBkShmatedBlock static ShmBkBlock* g_shmbk_list = NULL; static volatile jint g_shmbk_table_lock = 0; // keep some usage statistics static struct { int nodes; // number of nodes in list size_t bytes; // reserved - not committed - bytes. int reserves; // how often reserve was called int lookups; // how often a lookup was made } g_shmbk_stats = { 0, 0, 0, 0 }; // add information about a shared memory segment to the bookkeeping static void shmbk_register(ShmBkBlock* p_block) { guarantee(p_block, "logic error"); p_block->set_next(g_shmbk_list); g_shmbk_list = p_block; g_shmbk_stats.reserves ++; g_shmbk_stats.bytes += p_block->size(); g_shmbk_stats.nodes ++; } // remove information about a shared memory segment by its starting address static void shmbk_unregister(ShmBkBlock* p_block) { ShmBkBlock* p = g_shmbk_list; ShmBkBlock* prev = NULL; while (p) { if (p == p_block) { if (prev) { prev->set_next(p->next()); } else { g_shmbk_list = p->next(); } g_shmbk_stats.nodes --; g_shmbk_stats.bytes -= p->size(); return; } prev = p; p = p->next(); } assert(false, "should not happen"); } // given a pointer, return shared memory bookkeeping record for the segment it points into // using the returned block info must happen under lock protection static ShmBkBlock* shmbk_find_by_containing_address(const char* addr) { g_shmbk_stats.lookups ++; ShmBkBlock* p = g_shmbk_list; while (p) { if (p->containsAddress(addr)) { return p; } p = p->next(); } return NULL; } // dump all information about all memory segments allocated with os::reserve_memory() void shmbk_dump_info() { tty->print_cr("-- shared mem bookkeeping (alive: %d segments, %llu bytes, " "total reserves: %d total lookups: %d)", g_shmbk_stats.nodes, g_shmbk_stats.bytes, g_shmbk_stats.reserves, g_shmbk_stats.lookups); const ShmBkBlock* p = g_shmbk_list; int i = 0; while (p) { p->print(tty); p = p->next(); i ++; } } #define LOCK_SHMBK { ThreadCritical _LOCK_SHMBK; #define UNLOCK_SHMBK } // End: shared memory bookkeeping //////////////////////////////////////////////////////////////////////////////////////////////////// int os::vm_page_size() { // Seems redundant as all get out assert(os::Aix::page_size() != -1, "must call os::init"); return os::Aix::page_size(); } // Aix allocates memory by pages. int os::vm_allocation_granularity() { assert(os::Aix::page_size() != -1, "must call os::init"); return os::Aix::page_size(); } int os::Aix::commit_memory_impl(char* addr, size_t size, bool exec) { // Commit is a noop. There is no explicit commit // needed on AIX. Memory is committed when touched. // // Debug : check address range for validity #ifdef ASSERT LOCK_SHMBK ShmBkBlock* const block = shmbk_find_by_containing_address(addr); if (!block) { fprintf(stderr, "invalid pointer: " INTPTR_FORMAT "\n", addr); shmbk_dump_info(); assert(false, "invalid pointer"); return false; } else if (!block->containsRange(addr, size)) { fprintf(stderr, "invalid range: " INTPTR_FORMAT " .. " INTPTR_FORMAT "\n", addr, addr + size); shmbk_dump_info(); assert(false, "invalid range"); return false; } UNLOCK_SHMBK #endif // ASSERT return 0; } bool os::pd_commit_memory(char* addr, size_t size, bool exec) { return os::Aix::commit_memory_impl(addr, size, exec) == 0; } void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec, const char* mesg) { assert(mesg != NULL, "mesg must be specified"); os::Aix::commit_memory_impl(addr, size, exec); } int os::Aix::commit_memory_impl(char* addr, size_t size, size_t alignment_hint, bool exec) { return os::Aix::commit_memory_impl(addr, size, exec); } bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint, bool exec) { return os::Aix::commit_memory_impl(addr, size, alignment_hint, exec) == 0; } void os::pd_commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint, bool exec, const char* mesg) { os::Aix::commit_memory_impl(addr, size, alignment_hint, exec); } bool os::pd_uncommit_memory(char* addr, size_t size) { // Delegate to ShmBkBlock class which knows how to uncommit its memory. bool rc = false; LOCK_SHMBK ShmBkBlock* const block = shmbk_find_by_containing_address(addr); if (!block) { fprintf(stderr, "invalid pointer: 0x%p.\n", addr); shmbk_dump_info(); assert(false, "invalid pointer"); return false; } else if (!block->containsRange(addr, size)) { fprintf(stderr, "invalid range: 0x%p .. 0x%p.\n", addr, addr + size); shmbk_dump_info(); assert(false, "invalid range"); return false; } rc = block->disclaim(addr, size); UNLOCK_SHMBK if (Verbose && !rc) { warning("failed to disclaim 0x%p .. 0x%p (0x%llX bytes).", addr, addr + size, size); } return rc; } bool os::pd_create_stack_guard_pages(char* addr, size_t size) { return os::guard_memory(addr, size); } bool os::remove_stack_guard_pages(char* addr, size_t size) { return os::unguard_memory(addr, size); } void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { } void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) { } void os::numa_make_global(char *addr, size_t bytes) { } void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { } bool os::numa_topology_changed() { return false; } size_t os::numa_get_groups_num() { return 1; } int os::numa_get_group_id() { return 0; } size_t os::numa_get_leaf_groups(int *ids, size_t size) { if (size > 0) { ids[0] = 0; return 1; } return 0; } bool os::get_page_info(char *start, page_info* info) { return false; } char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { return end; } // Flags for reserve_shmatted_memory: #define RESSHM_WISHADDR_OR_FAIL 1 #define RESSHM_TRY_16M_PAGES 2 #define RESSHM_16M_PAGES_OR_FAIL 4 // Result of reserve_shmatted_memory: struct shmatted_memory_info_t { char* addr; size_t pagesize; bool pinned; }; // Reserve a section of shmatted memory. // params: // bytes [in]: size of memory, in bytes // requested_addr [in]: wish address. // NULL = no wish. // If RESSHM_WISHADDR_OR_FAIL is set in flags and wish address cannot // be obtained, function will fail. Otherwise wish address is treated as hint and // another pointer is returned. // flags [in]: some flags. Valid flags are: // RESSHM_WISHADDR_OR_FAIL - fail if wish address is given and cannot be obtained. // RESSHM_TRY_16M_PAGES - try to allocate from 16M page pool // (requires UseLargePages and Use16MPages) // RESSHM_16M_PAGES_OR_FAIL - if you cannot allocate from 16M page pool, fail. // Otherwise any other page size will do. // p_info [out] : holds information about the created shared memory segment. static bool reserve_shmatted_memory(size_t bytes, char* requested_addr, int flags, shmatted_memory_info_t* p_info) { assert(p_info, "parameter error"); // init output struct. p_info->addr = NULL; // neither should we be here for EXTSHM=ON. if (os::Aix::extshm()) { ShouldNotReachHere(); } // extract flags. sanity checks. const bool wishaddr_or_fail = flags & RESSHM_WISHADDR_OR_FAIL; const bool try_16M_pages = flags & RESSHM_TRY_16M_PAGES; const bool f16M_pages_or_fail = flags & RESSHM_16M_PAGES_OR_FAIL; // first check: if a wish address is given and it is mandatory, but not aligned to segment boundary, // shmat will fail anyway, so save some cycles by failing right away if (requested_addr && ((uintptr_t)requested_addr % SIZE_256M == 0)) { if (wishaddr_or_fail) { return false; } else { requested_addr = NULL; } } char* addr = NULL; // Align size of shm up to the largest possible page size, to avoid errors later on when we try to change // pagesize dynamically. const size_t size = align_size_up(bytes, SIZE_16M); // reserve the shared segment int shmid = shmget(IPC_PRIVATE, size, IPC_CREAT | S_IRUSR | S_IWUSR); if (shmid == -1) { warning("shmget(.., %lld, ..) failed (errno: %d).", size, errno); return false; } // Important note: // It is very important that we, upon leaving this function, do not leave a shm segment alive. // We must right after attaching it remove it from the system. System V shm segments are global and // survive the process. // So, from here on: Do not assert. Do not return. Always do a "goto cleanup_shm". // try forcing the page size size_t pagesize = -1; // unknown so far if (UseLargePages) { struct shmid_ds shmbuf; memset(&shmbuf, 0, sizeof(shmbuf)); // First, try to take from 16M page pool if... if (os::Aix::can_use_16M_pages() // we can ... && Use16MPages // we are not explicitly forbidden to do so (-XX:-Use16MPages).. && try_16M_pages) { // caller wants us to. shmbuf.shm_pagesize = SIZE_16M; if (shmctl(shmid, SHM_PAGESIZE, &shmbuf) == 0) { pagesize = SIZE_16M; } else { warning("Failed to allocate %d 16M pages. 16M page pool might be exhausted. (shmctl failed with %d)", size / SIZE_16M, errno); if (f16M_pages_or_fail) { goto cleanup_shm; } } } // Nothing yet? Try setting 64K pages. Note that I never saw this fail, but in theory it might, // because the 64K page pool may also be exhausted. if (pagesize == -1) { shmbuf.shm_pagesize = SIZE_64K; if (shmctl(shmid, SHM_PAGESIZE, &shmbuf) == 0) { pagesize = SIZE_64K; } else { warning("Failed to allocate %d 64K pages. (shmctl failed with %d)", size / SIZE_64K, errno); // here I give up. leave page_size -1 - later, after attaching, we will query the // real page size of the attached memory. (in theory, it may be something different // from 4K if LDR_CNTRL SHM_PSIZE is set) } } } // sanity point assert(pagesize == -1 || pagesize == SIZE_16M || pagesize == SIZE_64K, "wrong page size"); // Now attach the shared segment. addr = (char*) shmat(shmid, requested_addr, 0); if (addr == (char*)-1) { // How to handle attach failure: // If it failed for a specific wish address, tolerate this: in that case, if wish address was // mandatory, fail, if not, retry anywhere. // If it failed for any other reason, treat that as fatal error. addr = NULL; if (requested_addr) { if (wishaddr_or_fail) { goto cleanup_shm; } else { addr = (char*) shmat(shmid, NULL, 0); if (addr == (char*)-1) { // fatal addr = NULL; warning("shmat failed (errno: %d)", errno); goto cleanup_shm; } } } else { // fatal addr = NULL; warning("shmat failed (errno: %d)", errno); goto cleanup_shm; } } // sanity point assert(addr && addr != (char*) -1, "wrong address"); // after successful Attach remove the segment - right away. if (::shmctl(shmid, IPC_RMID, NULL) == -1) { warning("shmctl(%u, IPC_RMID) failed (%d)\n", shmid, errno); guarantee(false, "failed to remove shared memory segment!"); } shmid = -1; // query the real page size. In case setting the page size did not work (see above), the system // may have given us something other then 4K (LDR_CNTRL) { const size_t real_pagesize = os::Aix::query_pagesize(addr); if (pagesize != -1) { assert(pagesize == real_pagesize, "unexpected pagesize after shmat"); } else { pagesize = real_pagesize; } } // Now register the reserved block with internal book keeping. LOCK_SHMBK const bool pinned = pagesize >= SIZE_16M ? true : false; ShmBkShmatedBlock* const p_block = new ShmBkShmatedBlock(AddrRange(addr, size), pagesize, pinned); assert(p_block, ""); shmbk_register(p_block); UNLOCK_SHMBK cleanup_shm: // if we have not done so yet, remove the shared memory segment. This is very important. if (shmid != -1) { if (::shmctl(shmid, IPC_RMID, NULL) == -1) { warning("shmctl(%u, IPC_RMID) failed (%d)\n", shmid, errno); guarantee(false, "failed to remove shared memory segment!"); } shmid = -1; } // trace if (Verbose && !addr) { if (requested_addr != NULL) { warning("failed to shm-allocate 0x%llX bytes at with address 0x%p.", size, requested_addr); } else { warning("failed to shm-allocate 0x%llX bytes at any address.", size); } } // hand info to caller if (addr) { p_info->addr = addr; p_info->pagesize = pagesize; p_info->pinned = pagesize == SIZE_16M ? true : false; } // sanity test: if (requested_addr && addr && wishaddr_or_fail) { guarantee(addr == requested_addr, "shmat error"); } // just one more test to really make sure we have no dangling shm segments. guarantee(shmid == -1, "dangling shm segments"); return addr ? true : false; } // end: reserve_shmatted_memory // Reserve memory using mmap. Behaves the same as reserve_shmatted_memory(): // will return NULL in case of an error. static char* reserve_mmaped_memory(size_t bytes, char* requested_addr) { // if a wish address is given, but not aligned to 4K page boundary, mmap will fail. if (requested_addr && ((uintptr_t)requested_addr % os::vm_page_size() != 0)) { warning("Wish address 0x%p not aligned to page boundary.", requested_addr); return NULL; } const size_t size = align_size_up(bytes, SIZE_4K); // Note: MAP_SHARED (instead of MAP_PRIVATE) needed to be able to // msync(MS_INVALIDATE) (see os::uncommit_memory) int flags = MAP_ANONYMOUS | MAP_SHARED; // MAP_FIXED is needed to enforce requested_addr - manpage is vague about what // it means if wishaddress is given but MAP_FIXED is not set. // // Note however that this changes semantics in SPEC1170 mode insofar as MAP_FIXED // clobbers the address range, which is probably not what the caller wants. That's // why I assert here (again) that the SPEC1170 compat mode is off. // If we want to be able to run under SPEC1170, we have to do some porting and // testing. if (requested_addr != NULL) { assert(!os::Aix::xpg_sus_mode(), "SPEC1170 mode not allowed."); flags |= MAP_FIXED; } char* addr = (char*)::mmap(requested_addr, size, PROT_READ|PROT_WRITE|PROT_EXEC, flags, -1, 0); if (addr == MAP_FAILED) { // attach failed: tolerate for specific wish addresses. Not being able to attach // anywhere is a fatal error. if (requested_addr == NULL) { // It's ok to fail here if the machine has not enough memory. warning("mmap(NULL, 0x%llX, ..) failed (%d)", size, errno); } addr = NULL; goto cleanup_mmap; } // If we did request a specific address and that address was not available, fail. if (addr && requested_addr) { guarantee(addr == requested_addr, "unexpected"); } // register this mmap'ed segment with book keeping LOCK_SHMBK ShmBkMappedBlock* const p_block = new ShmBkMappedBlock(AddrRange(addr, size)); assert(p_block, ""); shmbk_register(p_block); UNLOCK_SHMBK cleanup_mmap: if (addr) { if (Verbose) { fprintf(stderr, "mmap-allocated 0x%p .. 0x%p (0x%llX bytes)\n", addr, addr + bytes, bytes); } } else { if (requested_addr != NULL) { warning("failed to mmap-allocate 0x%llX bytes at wish address 0x%p.", bytes, requested_addr); } else { warning("failed to mmap-allocate 0x%llX bytes at any address.", bytes); } } return addr; } // end: reserve_mmaped_memory // Reserves and attaches a shared memory segment. // Will assert if a wish address is given and could not be obtained. char* os::pd_reserve_memory(size_t bytes, char* requested_addr, size_t alignment_hint) { return os::attempt_reserve_memory_at(bytes, requested_addr); } bool os::pd_release_memory(char* addr, size_t size) { // delegate to ShmBkBlock class which knows how to uncommit its memory. bool rc = false; LOCK_SHMBK ShmBkBlock* const block = shmbk_find_by_containing_address(addr); if (!block) { fprintf(stderr, "invalid pointer: 0x%p.\n", addr); shmbk_dump_info(); assert(false, "invalid pointer"); return false; } else if (!block->isSameRange(addr, size)) { if (block->getType() == ShmBkBlock::MMAP) { // Release only the same range or a the beginning or the end of a range. if (block->base() == addr && size < block->size()) { ShmBkMappedBlock* const b = new ShmBkMappedBlock(AddrRange(block->base() + size, block->size() - size)); assert(b, ""); shmbk_register(b); block->setAddrRange(AddrRange(addr, size)); } else if (addr > block->base() && addr + size == block->base() + block->size()) { ShmBkMappedBlock* const b = new ShmBkMappedBlock(AddrRange(block->base(), block->size() - size)); assert(b, ""); shmbk_register(b); block->setAddrRange(AddrRange(addr, size)); } else { fprintf(stderr, "invalid mmap range: 0x%p .. 0x%p.\n", addr, addr + size); shmbk_dump_info(); assert(false, "invalid mmap range"); return false; } } else { // Release only the same range. No partial release allowed. // Soften the requirement a bit, because the user may think he owns a smaller size // than the block is due to alignment etc. if (block->base() != addr || block->size() < size) { fprintf(stderr, "invalid shmget range: 0x%p .. 0x%p.\n", addr, addr + size); shmbk_dump_info(); assert(false, "invalid shmget range"); return false; } } } rc = block->release(); assert(rc, "release failed"); // remove block from bookkeeping shmbk_unregister(block); delete block; UNLOCK_SHMBK if (!rc) { warning("failed to released %lu bytes at 0x%p", size, addr); } return rc; } static bool checked_mprotect(char* addr, size_t size, int prot) { // Little problem here: if SPEC1170 behaviour is off, mprotect() on AIX will // not tell me if protection failed when trying to protect an un-protectable range. // // This means if the memory was allocated using shmget/shmat, protection wont work // but mprotect will still return 0: // // See http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf1/mprotect.htm bool rc = ::mprotect(addr, size, prot) == 0 ? true : false; if (!rc) { const char* const s_errno = strerror(errno); warning("mprotect(" PTR_FORMAT "-" PTR_FORMAT ", 0x%X) failed (%s).", addr, addr + size, prot, s_errno); return false; } // mprotect success check // // Mprotect said it changed the protection but can I believe it? // // To be sure I need to check the protection afterwards. Try to // read from protected memory and check whether that causes a segfault. // if (!os::Aix::xpg_sus_mode()) { if (StubRoutines::SafeFetch32_stub()) { const bool read_protected = (SafeFetch32((int*)addr, 0x12345678) == 0x12345678 && SafeFetch32((int*)addr, 0x76543210) == 0x76543210) ? true : false; if (prot & PROT_READ) { rc = !read_protected; } else { rc = read_protected; } } } if (!rc) { assert(false, "mprotect failed."); } return rc; } // Set protections specified bool os::protect_memory(char* addr, size_t size, ProtType prot, bool is_committed) { unsigned int p = 0; switch (prot) { case MEM_PROT_NONE: p = PROT_NONE; break; case MEM_PROT_READ: p = PROT_READ; break; case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; default: ShouldNotReachHere(); } // is_committed is unused. return checked_mprotect(addr, size, p); } bool os::guard_memory(char* addr, size_t size) { return checked_mprotect(addr, size, PROT_NONE); } bool os::unguard_memory(char* addr, size_t size) { return checked_mprotect(addr, size, PROT_READ|PROT_WRITE|PROT_EXEC); } // Large page support static size_t _large_page_size = 0; // Enable large page support if OS allows that. void os::large_page_init() { // Note: os::Aix::query_multipage_support must run first. if (!UseLargePages) { return; } if (!Aix::can_use_64K_pages()) { assert(!Aix::can_use_16M_pages(), "64K is a precondition for 16M."); UseLargePages = false; return; } if (!Aix::can_use_16M_pages() && Use16MPages) { fprintf(stderr, "Cannot use 16M pages. Please ensure that there is a 16M page pool " " and that the VM runs with CAP_BYPASS_RAC_VMM and CAP_PROPAGATE capabilities.\n"); } // Do not report 16M page alignment as part of os::_page_sizes if we are // explicitly forbidden from using 16M pages. Doing so would increase the // alignment the garbage collector calculates with, slightly increasing // heap usage. We should only pay for 16M alignment if we really want to // use 16M pages. if (Use16MPages && Aix::can_use_16M_pages()) { _large_page_size = SIZE_16M; _page_sizes[0] = SIZE_16M; _page_sizes[1] = SIZE_64K; _page_sizes[2] = SIZE_4K; _page_sizes[3] = 0; } else if (Aix::can_use_64K_pages()) { _large_page_size = SIZE_64K; _page_sizes[0] = SIZE_64K; _page_sizes[1] = SIZE_4K; _page_sizes[2] = 0; } if (Verbose) { ("Default large page size is 0x%llX.", _large_page_size); } } // end: os::large_page_init() char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) { // "exec" is passed in but not used. Creating the shared image for // the code cache doesn't have an SHM_X executable permission to check. Unimplemented(); return 0; } bool os::release_memory_special(char* base, size_t bytes) { // detaching the SHM segment will also delete it, see reserve_memory_special() Unimplemented(); return false; } size_t os::large_page_size() { return _large_page_size; } bool os::can_commit_large_page_memory() { // Well, sadly we cannot commit anything at all (see comment in // os::commit_memory) but we claim to so we can make use of large pages return true; } bool os::can_execute_large_page_memory() { // We can do that return true; } // Reserve memory at an arbitrary address, only if that area is // available (and not reserved for something else). char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { bool use_mmap = false; // mmap: smaller graining, no large page support // shm: large graining (256M), large page support, limited number of shm segments // // Prefer mmap wherever we either do not need large page support or have OS limits if (!UseLargePages || bytes < SIZE_16M) { use_mmap = true; } char* addr = NULL; if (use_mmap) { addr = reserve_mmaped_memory(bytes, requested_addr); } else { // shmat: wish address is mandatory, and do not try 16M pages here. shmatted_memory_info_t info; const int flags = RESSHM_WISHADDR_OR_FAIL; if (reserve_shmatted_memory(bytes, requested_addr, flags, &info)) { addr = info.addr; } } return addr; } size_t os::read(int fd, void *buf, unsigned int nBytes) { return ::read(fd, buf, nBytes); } #define NANOSECS_PER_MILLISEC 1000000 int os::sleep(Thread* thread, jlong millis, bool interruptible) { assert(thread == Thread::current(), "thread consistency check"); // Prevent nasty overflow in deadline calculation // by handling long sleeps similar to solaris or windows. const jlong limit = INT_MAX; int result; while (millis > limit) { if ((result = os::sleep(thread, limit, interruptible)) != OS_OK) { return result; } millis -= limit; } ParkEvent * const slp = thread->_SleepEvent; slp->reset(); OrderAccess::fence(); if (interruptible) { jlong prevtime = javaTimeNanos(); // Prevent precision loss and too long sleeps jlong deadline = prevtime + millis * NANOSECS_PER_MILLISEC; for (;;) { if (os::is_interrupted(thread, true)) { return OS_INTRPT; } jlong newtime = javaTimeNanos(); assert(newtime >= prevtime, "time moving backwards"); // Doing prevtime and newtime in microseconds doesn't help precision, // and trying to round up to avoid lost milliseconds can result in a // too-short delay. millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; if (millis <= 0) { return OS_OK; } // Stop sleeping if we passed the deadline if (newtime >= deadline) { return OS_OK; } prevtime = newtime; { assert(thread->is_Java_thread(), "sanity check"); JavaThread *jt = (JavaThread *) thread; ThreadBlockInVM tbivm(jt); OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */); jt->set_suspend_equivalent(); slp->park(millis); // were we externally suspended while we were waiting? jt->check_and_wait_while_suspended(); } } } else { OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); jlong prevtime = javaTimeNanos(); // Prevent precision loss and too long sleeps jlong deadline = prevtime + millis * NANOSECS_PER_MILLISEC; for (;;) { // It'd be nice to avoid the back-to-back javaTimeNanos() calls on // the 1st iteration ... jlong newtime = javaTimeNanos(); if (newtime - prevtime < 0) { // time moving backwards, should only happen if no monotonic clock // not a guarantee() because JVM should not abort on kernel/glibc bugs // - HS14 Commented out as not implemented. // - TODO Maybe we should implement it? //assert(!Aix::supports_monotonic_clock(), "time moving backwards"); } else { millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; } if (millis <= 0) break; if (newtime >= deadline) { break; } prevtime = newtime; slp->park(millis); } return OS_OK; } } int os::naked_sleep() { // %% make the sleep time an integer flag. for now use 1 millisec. return os::sleep(Thread::current(), 1, false); } // Sleep forever; naked call to OS-specific sleep; use with CAUTION void os::infinite_sleep() { while (true) { // sleep forever ... ::sleep(100); // ... 100 seconds at a time } } // Used to convert frequent JVM_Yield() to nops bool os::dont_yield() { return DontYieldALot; } void os::yield() { sched_yield(); } os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; } void os::yield_all(int attempts) { // Yields to all threads, including threads with lower priorities // Threads on Linux are all with same priority. The Solaris style // os::yield_all() with nanosleep(1ms) is not necessary. sched_yield(); } // Called from the tight loops to possibly influence time-sharing heuristics void os::loop_breaker(int attempts) { os::yield_all(attempts); } //////////////////////////////////////////////////////////////////////////////// // thread priority support // From AIX manpage to pthread_setschedparam // (see: http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp? // topic=/com.ibm.aix.basetechref/doc/basetrf1/pthread_setschedparam.htm): // // "If schedpolicy is SCHED_OTHER, then sched_priority must be in the // range from 40 to 80, where 40 is the least favored priority and 80 // is the most favored." // // (Actually, I doubt this even has an impact on AIX, as we do kernel // scheduling there; however, this still leaves iSeries.) // // We use the same values for AIX and PASE. int os::java_to_os_priority[CriticalPriority + 1] = { 54, // 0 Entry should never be used 55, // 1 MinPriority 55, // 2 56, // 3 56, // 4 57, // 5 NormPriority 57, // 6 58, // 7 58, // 8 59, // 9 NearMaxPriority 60, // 10 MaxPriority 60 // 11 CriticalPriority }; OSReturn os::set_native_priority(Thread* thread, int newpri) { if (!UseThreadPriorities) return OS_OK; pthread_t thr = thread->osthread()->pthread_id(); int policy = SCHED_OTHER; struct sched_param param; param.sched_priority = newpri; int ret = pthread_setschedparam(thr, policy, &param); if (Verbose) { if (ret == 0) { fprintf(stderr, "changed priority of thread %d to %d\n", (int)thr, newpri); } else { fprintf(stderr, "Could not changed priority for thread %d to %d (error %d, %s)\n", (int)thr, newpri, ret, strerror(ret)); } } return (ret == 0) ? OS_OK : OS_ERR; } OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { if (!UseThreadPriorities) { *priority_ptr = java_to_os_priority[NormPriority]; return OS_OK; } pthread_t thr = thread->osthread()->pthread_id(); int policy = SCHED_OTHER; struct sched_param param; int ret = pthread_getschedparam(thr, &policy, &param); *priority_ptr = param.sched_priority; return (ret == 0) ? OS_OK : OS_ERR; } // Hint to the underlying OS that a task switch would not be good. // Void return because it's a hint and can fail. void os::hint_no_preempt() {} //////////////////////////////////////////////////////////////////////////////// // suspend/resume support // the low-level signal-based suspend/resume support is a remnant from the // old VM-suspension that used to be for java-suspension, safepoints etc, // within hotspot. Now there is a single use-case for this: // - calling get_thread_pc() on the VMThread by the flat-profiler task // that runs in the watcher thread. // The remaining code is greatly simplified from the more general suspension // code that used to be used. // // The protocol is quite simple: // - suspend: // - sends a signal to the target thread // - polls the suspend state of the osthread using a yield loop // - target thread signal handler (SR_handler) sets suspend state // and blocks in sigsuspend until continued // - resume: // - sets target osthread state to continue // - sends signal to end the sigsuspend loop in the SR_handler // // Note that the SR_lock plays no role in this suspend/resume protocol. // static void resume_clear_context(OSThread *osthread) { osthread->set_ucontext(NULL); osthread->set_siginfo(NULL); } static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) { osthread->set_ucontext(context); osthread->set_siginfo(siginfo); } // // Handler function invoked when a thread's execution is suspended or // resumed. We have to be careful that only async-safe functions are // called here (Note: most pthread functions are not async safe and // should be avoided.) // // Note: sigwait() is a more natural fit than sigsuspend() from an // interface point of view, but sigwait() prevents the signal hander // from being run. libpthread would get very confused by not having // its signal handlers run and prevents sigwait()'s use with the // mutex granting granting signal. // // Currently only ever called on the VMThread and JavaThreads (PC sampling). // static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { // Save and restore errno to avoid confusing native code with EINTR // after sigsuspend. int old_errno = errno; Thread* thread = Thread::current(); OSThread* osthread = thread->osthread(); assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); os::SuspendResume::State current = osthread->sr.state(); if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { suspend_save_context(osthread, siginfo, context); // attempt to switch the state, we assume we had a SUSPEND_REQUEST os::SuspendResume::State state = osthread->sr.suspended(); if (state == os::SuspendResume::SR_SUSPENDED) { sigset_t suspend_set; // signals for sigsuspend() // get current set of blocked signals and unblock resume signal pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); sigdelset(&suspend_set, SR_signum); // wait here until we are resumed while (1) { sigsuspend(&suspend_set); os::SuspendResume::State result = osthread->sr.running(); if (result == os::SuspendResume::SR_RUNNING) { break; } } } else if (state == os::SuspendResume::SR_RUNNING) { // request was cancelled, continue } else { ShouldNotReachHere(); } resume_clear_context(osthread); } else if (current == os::SuspendResume::SR_RUNNING) { // request was cancelled, continue } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { // ignore } else { ShouldNotReachHere(); } errno = old_errno; } static int SR_initialize() { struct sigaction act; char *s; // Get signal number to use for suspend/resume if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { int sig = ::strtol(s, 0, 10); if (sig > 0 || sig < NSIG) { SR_signum = sig; } } assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); sigemptyset(&SR_sigset); sigaddset(&SR_sigset, SR_signum); // Set up signal handler for suspend/resume. act.sa_flags = SA_RESTART|SA_SIGINFO; act.sa_handler = (void (*)(int)) SR_handler; // SR_signum is blocked by default. // 4528190 - We also need to block pthread restart signal (32 on all // supported Linux platforms). Note that LinuxThreads need to block // this signal for all threads to work properly. So we don't have // to use hard-coded signal number when setting up the mask. pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); if (sigaction(SR_signum, &act, 0) == -1) { return -1; } // Save signal flag os::Aix::set_our_sigflags(SR_signum, act.sa_flags); return 0; } static int SR_finalize() { return 0; } static int sr_notify(OSThread* osthread) { int status = pthread_kill(osthread->pthread_id(), SR_signum); assert_status(status == 0, status, "pthread_kill"); return status; } // "Randomly" selected value for how long we want to spin // before bailing out on suspending a thread, also how often // we send a signal to a thread we want to resume static const int RANDOMLY_LARGE_INTEGER = 1000000; static const int RANDOMLY_LARGE_INTEGER2 = 100; // returns true on success and false on error - really an error is fatal // but this seems the normal response to library errors static bool do_suspend(OSThread* osthread) { assert(osthread->sr.is_running(), "thread should be running"); // mark as suspended and send signal if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { // failed to switch, state wasn't running? ShouldNotReachHere(); return false; } if (sr_notify(osthread) != 0) { // try to cancel, switch to running os::SuspendResume::State result = osthread->sr.cancel_suspend(); if (result == os::SuspendResume::SR_RUNNING) { // cancelled return false; } else if (result == os::SuspendResume::SR_SUSPENDED) { // somehow managed to suspend return true; } else { ShouldNotReachHere(); return false; } } // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED for (int n = 0; !osthread->sr.is_suspended(); n++) { for (int i = 0; i < RANDOMLY_LARGE_INTEGER2 && !osthread->sr.is_suspended(); i++) { os::yield_all(i); } // timeout, try to cancel the request if (n >= RANDOMLY_LARGE_INTEGER) { os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); if (cancelled == os::SuspendResume::SR_RUNNING) { return false; } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { return true; } else { ShouldNotReachHere(); return false; } } } guarantee(osthread->sr.is_suspended(), "Must be suspended"); return true; } static void do_resume(OSThread* osthread) { //assert(osthread->sr.is_suspended(), "thread should be suspended"); if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { // failed to switch to WAKEUP_REQUEST ShouldNotReachHere(); return; } while (!osthread->sr.is_running()) { if (sr_notify(osthread) == 0) { for (int n = 0; n < RANDOMLY_LARGE_INTEGER && !osthread->sr.is_running(); n++) { for (int i = 0; i < 100 && !osthread->sr.is_running(); i++) { os::yield_all(i); } } } else { ShouldNotReachHere(); } } guarantee(osthread->sr.is_running(), "Must be running!"); } //////////////////////////////////////////////////////////////////////////////// // interrupt support void os::interrupt(Thread* thread) { assert(Thread::current() == thread || Threads_lock->owned_by_self(), "possibility of dangling Thread pointer"); OSThread* osthread = thread->osthread(); if (!osthread->interrupted()) { osthread->set_interrupted(true); // More than one thread can get here with the same value of osthread, // resulting in multiple notifications. We do, however, want the store // to interrupted() to be visible to other threads before we execute unpark(). OrderAccess::fence(); ParkEvent * const slp = thread->_SleepEvent; if (slp != NULL) slp->unpark(); } // For JSR166. Unpark even if interrupt status already was set if (thread->is_Java_thread()) ((JavaThread*)thread)->parker()->unpark(); ParkEvent * ev = thread->_ParkEvent; if (ev != NULL) ev->unpark(); } bool os::is_interrupted(Thread* thread, bool clear_interrupted) { assert(Thread::current() == thread || Threads_lock->owned_by_self(), "possibility of dangling Thread pointer"); OSThread* osthread = thread->osthread(); bool interrupted = osthread->interrupted(); if (interrupted && clear_interrupted) { osthread->set_interrupted(false); // consider thread->_SleepEvent->reset() ... optional optimization } return interrupted; } /////////////////////////////////////////////////////////////////////////////////// // signal handling (except suspend/resume) // This routine may be used by user applications as a "hook" to catch signals. // The user-defined signal handler must pass unrecognized signals to this // routine, and if it returns true (non-zero), then the signal handler must // return immediately. If the flag "abort_if_unrecognized" is true, then this // routine will never retun false (zero), but instead will execute a VM panic // routine kill the process. // // If this routine returns false, it is OK to call it again. This allows // the user-defined signal handler to perform checks either before or after // the VM performs its own checks. Naturally, the user code would be making // a serious error if it tried to handle an exception (such as a null check // or breakpoint) that the VM was generating for its own correct operation. // // This routine may recognize any of the following kinds of signals: // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. // It should be consulted by handlers for any of those signals. // // The caller of this routine must pass in the three arguments supplied // to the function referred to in the "sa_sigaction" (not the "sa_handler") // field of the structure passed to sigaction(). This routine assumes that // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. // // Note that the VM will print warnings if it detects conflicting signal // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". // extern "C" JNIEXPORT int JVM_handle_aix_signal(int signo, siginfo_t* siginfo, void* ucontext, int abort_if_unrecognized); // Set thread signal mask (for some reason on AIX sigthreadmask() seems // to be the thing to call; documentation is not terribly clear about whether // pthread_sigmask also works, and if it does, whether it does the same. bool set_thread_signal_mask(int how, const sigset_t* set, sigset_t* oset) { const int rc = ::pthread_sigmask(how, set, oset); // return value semantics differ slightly for error case: // pthread_sigmask returns error number, sigthreadmask -1 and sets global errno // (so, pthread_sigmask is more theadsafe for error handling) // But success is always 0. return rc == 0 ? true : false; } // Function to unblock all signals which are, according // to POSIX, typical program error signals. If they happen while being blocked, // they typically will bring down the process immediately. bool unblock_program_error_signals() { sigset_t set; ::sigemptyset(&set); ::sigaddset(&set, SIGILL); ::sigaddset(&set, SIGBUS); ::sigaddset(&set, SIGFPE); ::sigaddset(&set, SIGSEGV); return set_thread_signal_mask(SIG_UNBLOCK, &set, NULL); } // Renamed from 'signalHandler' to avoid collision with other shared libs. void javaSignalHandler(int sig, siginfo_t* info, void* uc) { assert(info != NULL && uc != NULL, "it must be old kernel"); // Never leave program error signals blocked; // on all our platforms they would bring down the process immediately when // getting raised while being blocked. unblock_program_error_signals(); JVM_handle_aix_signal(sig, info, uc, true); } // This boolean allows users to forward their own non-matching signals // to JVM_handle_aix_signal, harmlessly. bool os::Aix::signal_handlers_are_installed = false; // For signal-chaining struct sigaction os::Aix::sigact[MAXSIGNUM]; unsigned int os::Aix::sigs = 0; bool os::Aix::libjsig_is_loaded = false; typedef struct sigaction *(*get_signal_t)(int); get_signal_t os::Aix::get_signal_action = NULL; struct sigaction* os::Aix::get_chained_signal_action(int sig) { struct sigaction *actp = NULL; if (libjsig_is_loaded) { // Retrieve the old signal handler from libjsig actp = (*get_signal_action)(sig); } if (actp == NULL) { // Retrieve the preinstalled signal handler from jvm actp = get_preinstalled_handler(sig); } return actp; } static bool call_chained_handler(struct sigaction *actp, int sig, siginfo_t *siginfo, void *context) { Unimplemented(); return true; } bool os::Aix::chained_handler(int sig, siginfo_t* siginfo, void* context) { bool chained = false; // signal-chaining if (UseSignalChaining) { struct sigaction *actp = get_chained_signal_action(sig); if (actp != NULL) { chained = call_chained_handler(actp, sig, siginfo, context); } } return chained; } struct sigaction* os::Aix::get_preinstalled_handler(int sig) { if ((((unsigned int)1 << sig) & sigs) != 0) { return &sigact[sig]; } return NULL; } void os::Aix::save_preinstalled_handler(int sig, struct sigaction& oldAct) { assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); sigact[sig] = oldAct; sigs |= (unsigned int)1 << sig; } // for diagnostic int os::Aix::sigflags[MAXSIGNUM]; int os::Aix::get_our_sigflags(int sig) { assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); return sigflags[sig]; } void os::Aix::set_our_sigflags(int sig, int flags) { assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); sigflags[sig] = flags; } void os::Aix::set_signal_handler(int sig, bool set_installed) { // Check for overwrite. struct sigaction oldAct; sigaction(sig, (struct sigaction*)NULL, &oldAct); void* oldhand = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); // Renamed 'signalHandler' to avoid collision with other shared libs. if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)javaSignalHandler)) { if (AllowUserSignalHandlers || !set_installed) { // Do not overwrite; user takes responsibility to forward to us. return; } else if (UseSignalChaining) { // save the old handler in jvm save_preinstalled_handler(sig, oldAct); // libjsig also interposes the sigaction() call below and saves the // old sigaction on it own. } else { fatal(err_msg("Encountered unexpected pre-existing sigaction handler " "%#lx for signal %d.", (long)oldhand, sig)); } } struct sigaction sigAct; sigfillset(&(sigAct.sa_mask)); if (!set_installed) { sigAct.sa_handler = SIG_DFL; sigAct.sa_flags = SA_RESTART; } else { // Renamed 'signalHandler' to avoid collision with other shared libs. sigAct.sa_sigaction = javaSignalHandler; sigAct.sa_flags = SA_SIGINFO|SA_RESTART; } // Save flags, which are set by ours assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); sigflags[sig] = sigAct.sa_flags; int ret = sigaction(sig, &sigAct, &oldAct); assert(ret == 0, "check"); void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); assert(oldhand2 == oldhand, "no concurrent signal handler installation"); } // install signal handlers for signals that HotSpot needs to // handle in order to support Java-level exception handling. void os::Aix::install_signal_handlers() { if (!signal_handlers_are_installed) { signal_handlers_are_installed = true; // signal-chaining typedef void (*signal_setting_t)(); signal_setting_t begin_signal_setting = NULL; signal_setting_t end_signal_setting = NULL; begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); if (begin_signal_setting != NULL) { end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); get_signal_action = CAST_TO_FN_PTR(get_signal_t, dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); libjsig_is_loaded = true; assert(UseSignalChaining, "should enable signal-chaining"); } if (libjsig_is_loaded) { // Tell libjsig jvm is setting signal handlers (*begin_signal_setting)(); } set_signal_handler(SIGSEGV, true); set_signal_handler(SIGPIPE, true); set_signal_handler(SIGBUS, true); set_signal_handler(SIGILL, true); set_signal_handler(SIGFPE, true); set_signal_handler(SIGTRAP, true); set_signal_handler(SIGXFSZ, true); set_signal_handler(SIGDANGER, true); if (libjsig_is_loaded) { // Tell libjsig jvm finishes setting signal handlers (*end_signal_setting)(); } // We don't activate signal checker if libjsig is in place, we trust ourselves // and if UserSignalHandler is installed all bets are off. // Log that signal checking is off only if -verbose:jni is specified. if (CheckJNICalls) { if (libjsig_is_loaded) { tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); check_signals = false; } if (AllowUserSignalHandlers) { tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); check_signals = false; } // need to initialize check_signal_done ::sigemptyset(&check_signal_done); } } } static const char* get_signal_handler_name(address handler, char* buf, int buflen) { int offset; bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); if (found) { // skip directory names const char *p1, *p2; p1 = buf; size_t len = strlen(os::file_separator()); while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; // The way os::dll_address_to_library_name is implemented on Aix // right now, it always returns -1 for the offset which is not // terribly informative. // Will fix that. For now, omit the offset. jio_snprintf(buf, buflen, "%s", p1); } else { jio_snprintf(buf, buflen, PTR_FORMAT, handler); } return buf; } static void print_signal_handler(outputStream* st, int sig, char* buf, size_t buflen) { struct sigaction sa; sigaction(sig, NULL, &sa); st->print("%s: ", os::exception_name(sig, buf, buflen)); address handler = (sa.sa_flags & SA_SIGINFO) ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) : CAST_FROM_FN_PTR(address, sa.sa_handler); if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { st->print("SIG_DFL"); } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { st->print("SIG_IGN"); } else { st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); } // Print readable mask. st->print(", sa_mask[0]="); os::Posix::print_signal_set_short(st, &sa.sa_mask); address rh = VMError::get_resetted_sighandler(sig); // May be, handler was resetted by VMError? if (rh != NULL) { handler = rh; sa.sa_flags = VMError::get_resetted_sigflags(sig); } // Print textual representation of sa_flags. st->print(", sa_flags="); os::Posix::print_sa_flags(st, sa.sa_flags); // Check: is it our handler? if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)javaSignalHandler) || handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { // It is our signal handler. // Check for flags, reset system-used one! if ((int)sa.sa_flags != os::Aix::get_our_sigflags(sig)) { st->print(", flags was changed from " PTR32_FORMAT ", consider using jsig library", os::Aix::get_our_sigflags(sig)); } } st->cr(); } #define DO_SIGNAL_CHECK(sig) \ if (!sigismember(&check_signal_done, sig)) \ os::Aix::check_signal_handler(sig) // This method is a periodic task to check for misbehaving JNI applications // under CheckJNI, we can add any periodic checks here void os::run_periodic_checks() { if (check_signals == false) return; // SEGV and BUS if overridden could potentially prevent // generation of hs*.log in the event of a crash, debugging // such a case can be very challenging, so we absolutely // check the following for a good measure: DO_SIGNAL_CHECK(SIGSEGV); DO_SIGNAL_CHECK(SIGILL); DO_SIGNAL_CHECK(SIGFPE); DO_SIGNAL_CHECK(SIGBUS); DO_SIGNAL_CHECK(SIGPIPE); DO_SIGNAL_CHECK(SIGXFSZ); if (UseSIGTRAP) { DO_SIGNAL_CHECK(SIGTRAP); } DO_SIGNAL_CHECK(SIGDANGER); // ReduceSignalUsage allows the user to override these handlers // see comments at the very top and jvm_solaris.h if (!ReduceSignalUsage) { DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); DO_SIGNAL_CHECK(BREAK_SIGNAL); } DO_SIGNAL_CHECK(SR_signum); DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); } typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); static os_sigaction_t os_sigaction = NULL; void os::Aix::check_signal_handler(int sig) { char buf[O_BUFLEN]; address jvmHandler = NULL; struct sigaction act; if (os_sigaction == NULL) { // only trust the default sigaction, in case it has been interposed os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); if (os_sigaction == NULL) return; } os_sigaction(sig, (struct sigaction*)NULL, &act); address thisHandler = (act.sa_flags & SA_SIGINFO) ? CAST_FROM_FN_PTR(address, act.sa_sigaction) : CAST_FROM_FN_PTR(address, act.sa_handler); switch(sig) { case SIGSEGV: case SIGBUS: case SIGFPE: case SIGPIPE: case SIGILL: case SIGXFSZ: // Renamed 'signalHandler' to avoid collision with other shared libs. jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)javaSignalHandler); break; case SHUTDOWN1_SIGNAL: case SHUTDOWN2_SIGNAL: case SHUTDOWN3_SIGNAL: case BREAK_SIGNAL: jvmHandler = (address)user_handler(); break; case INTERRUPT_SIGNAL: jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); break; default: if (sig == SR_signum) { jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); } else { return; } break; } if (thisHandler != jvmHandler) { tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); // No need to check this sig any longer sigaddset(&check_signal_done, sig); } else if (os::Aix::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Aix::get_our_sigflags(sig)) { tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); tty->print("expected:" PTR32_FORMAT, os::Aix::get_our_sigflags(sig)); tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); // No need to check this sig any longer sigaddset(&check_signal_done, sig); } // Dump all the signal if (sigismember(&check_signal_done, sig)) { print_signal_handlers(tty, buf, O_BUFLEN); } } extern bool signal_name(int signo, char* buf, size_t len); const char* os::exception_name(int exception_code, char* buf, size_t size) { if (0 < exception_code && exception_code <= SIGRTMAX) { // signal if (!signal_name(exception_code, buf, size)) { jio_snprintf(buf, size, "SIG%d", exception_code); } return buf; } else { return NULL; } } // To install functions for atexit system call extern "C" { static void perfMemory_exit_helper() { perfMemory_exit(); } } // This is called _before_ the most of global arguments have been parsed. void os::init(void) { // This is basic, we want to know if that ever changes. // (shared memory boundary is supposed to be a 256M aligned) assert(SHMLBA == ((uint64_t)0x10000000ULL)/*256M*/, "unexpected"); // First off, we need to know whether we run on AIX or PASE, and // the OS level we run on. os::Aix::initialize_os_info(); // Scan environment (SPEC1170 behaviour, etc) os::Aix::scan_environment(); // Check which pages are supported by AIX. os::Aix::query_multipage_support(); // Next, we need to initialize libo4 and libperfstat libraries. if (os::Aix::on_pase()) { os::Aix::initialize_libo4(); } else { os::Aix::initialize_libperfstat(); } // Reset the perfstat information provided by ODM. if (os::Aix::on_aix()) { libperfstat::perfstat_reset(); } // Now initialze basic system properties. Note that for some of the values we // need libperfstat etc. os::Aix::initialize_system_info(); // Initialize large page support. if (UseLargePages) { os::large_page_init(); if (!UseLargePages) { // initialize os::_page_sizes _page_sizes[0] = Aix::page_size(); _page_sizes[1] = 0; if (Verbose) { fprintf(stderr, "Large Page initialization failed: setting UseLargePages=0.\n"); } } } else { // initialize os::_page_sizes _page_sizes[0] = Aix::page_size(); _page_sizes[1] = 0; } // debug trace if (Verbose) { fprintf(stderr, "os::vm_page_size 0x%llX\n", os::vm_page_size()); fprintf(stderr, "os::large_page_size 0x%llX\n", os::large_page_size()); fprintf(stderr, "os::_page_sizes = ( "); for (int i = 0; _page_sizes[i]; i ++) { fprintf(stderr, " %s ", describe_pagesize(_page_sizes[i])); } fprintf(stderr, ")\n"); } _initial_pid = getpid(); clock_tics_per_sec = sysconf(_SC_CLK_TCK); init_random(1234567); ThreadCritical::initialize(); // Main_thread points to the aboriginal thread. Aix::_main_thread = pthread_self(); initial_time_count = os::elapsed_counter(); pthread_mutex_init(&dl_mutex, NULL); } // this is called _after_ the global arguments have been parsed jint os::init_2(void) { if (Verbose) { fprintf(stderr, "processor count: %d\n", os::_processor_count); fprintf(stderr, "physical memory: %lu\n", Aix::_physical_memory); } // initially build up the loaded dll map LoadedLibraries::reload(); const int page_size = Aix::page_size(); const int map_size = page_size; address map_address = (address) MAP_FAILED; const int prot = PROT_READ; const int flags = MAP_PRIVATE|MAP_ANONYMOUS; // use optimized addresses for the polling page, // e.g. map it to a special 32-bit address. if (OptimizePollingPageLocation) { // architecture-specific list of address wishes: address address_wishes[] = { // AIX: addresses lower than 0x30000000 don't seem to work on AIX. // PPC64: all address wishes are non-negative 32 bit values where // the lower 16 bits are all zero. we can load these addresses // with a single ppc_lis instruction. (address) 0x30000000, (address) 0x31000000, (address) 0x32000000, (address) 0x33000000, (address) 0x40000000, (address) 0x41000000, (address) 0x42000000, (address) 0x43000000, (address) 0x50000000, (address) 0x51000000, (address) 0x52000000, (address) 0x53000000, (address) 0x60000000, (address) 0x61000000, (address) 0x62000000, (address) 0x63000000 }; int address_wishes_length = sizeof(address_wishes)/sizeof(address); // iterate over the list of address wishes: for (int i=0; i<address_wishes_length; i++) { // try to map with current address wish. // AIX: AIX needs MAP_FIXED if we provide an address and mmap will // fail if the address is already mapped. map_address = (address) ::mmap(address_wishes[i] - (ssize_t)page_size, map_size, prot, flags | MAP_FIXED, -1, 0); if (Verbose) { fprintf(stderr, "SafePoint Polling Page address: %p (wish) => %p\n", address_wishes[i], map_address + (ssize_t)page_size); } if (map_address + (ssize_t)page_size == address_wishes[i]) { // map succeeded and map_address is at wished address, exit loop. break; } if (map_address != (address) MAP_FAILED) { // map succeeded, but polling_page is not at wished address, unmap and continue. ::munmap(map_address, map_size); map_address = (address) MAP_FAILED; } // map failed, continue loop. } } // end OptimizePollingPageLocation if (map_address == (address) MAP_FAILED) { map_address = (address) ::mmap(NULL, map_size, prot, flags, -1, 0); } guarantee(map_address != MAP_FAILED, "os::init_2: failed to allocate polling page"); os::set_polling_page(map_address); if (!UseMembar) { address mem_serialize_page = (address) ::mmap(NULL, Aix::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); guarantee(mem_serialize_page != NULL, "mmap Failed for memory serialize page"); os::set_memory_serialize_page(mem_serialize_page); #ifndef PRODUCT if (Verbose && PrintMiscellaneous) tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); #endif } // initialize suspend/resume support - must do this before signal_sets_init() if (SR_initialize() != 0) { perror("SR_initialize failed"); return JNI_ERR; } Aix::signal_sets_init(); Aix::install_signal_handlers(); // Check minimum allowable stack size for thread creation and to initialize // the java system classes, including StackOverflowError - depends on page // size. Add a page for compiler2 recursion in main thread. // Add in 2*BytesPerWord times page size to account for VM stack during // class initialization depending on 32 or 64 bit VM. os::Aix::min_stack_allowed = MAX2(os::Aix::min_stack_allowed, (size_t)(StackYellowPages+StackRedPages+StackShadowPages + 2*BytesPerWord COMPILER2_PRESENT(+1)) * Aix::page_size()); size_t threadStackSizeInBytes = ThreadStackSize * K; if (threadStackSizeInBytes != 0 && threadStackSizeInBytes < os::Aix::min_stack_allowed) { tty->print_cr("\nThe stack size specified is too small, " "Specify at least %dk", os::Aix::min_stack_allowed / K); return JNI_ERR; } // Make the stack size a multiple of the page size so that // the yellow/red zones can be guarded. // note that this can be 0, if no default stacksize was set JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, vm_page_size())); Aix::libpthread_init(); if (MaxFDLimit) { // set the number of file descriptors to max. print out error // if getrlimit/setrlimit fails but continue regardless. struct rlimit nbr_files; int status = getrlimit(RLIMIT_NOFILE, &nbr_files); if (status != 0) { if (PrintMiscellaneous && (Verbose || WizardMode)) perror("os::init_2 getrlimit failed"); } else { nbr_files.rlim_cur = nbr_files.rlim_max; status = setrlimit(RLIMIT_NOFILE, &nbr_files); if (status != 0) { if (PrintMiscellaneous && (Verbose || WizardMode)) perror("os::init_2 setrlimit failed"); } } } if (PerfAllowAtExitRegistration) { // only register atexit functions if PerfAllowAtExitRegistration is set. // atexit functions can be delayed until process exit time, which // can be problematic for embedded VM situations. Embedded VMs should // call DestroyJavaVM() to assure that VM resources are released. // note: perfMemory_exit_helper atexit function may be removed in // the future if the appropriate cleanup code can be added to the // VM_Exit VMOperation's doit method. if (atexit(perfMemory_exit_helper) != 0) { warning("os::init_2 atexit(perfMemory_exit_helper) failed"); } } return JNI_OK; } // this is called at the end of vm_initialization void os::init_3(void) { return; } // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { if (!guard_memory((char*)_polling_page, Aix::page_size())) { fatal("Could not disable polling page"); } }; // Mark the polling page as readable void os::make_polling_page_readable(void) { // Changed according to os_linux.cpp. if (!checked_mprotect((char *)_polling_page, Aix::page_size(), PROT_READ)) { fatal(err_msg("Could not enable polling page at " PTR_FORMAT, _polling_page)); } }; int os::active_processor_count() { int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN); assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check"); return online_cpus; } void os::set_native_thread_name(const char *name) { // Not yet implemented. return; } bool os::distribute_processes(uint length, uint* distribution) { // Not yet implemented. return false; } bool os::bind_to_processor(uint processor_id) { // Not yet implemented. return false; } void os::SuspendedThreadTask::internal_do_task() { if (do_suspend(_thread->osthread())) { SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); do_task(context); do_resume(_thread->osthread()); } } class PcFetcher : public os::SuspendedThreadTask { public: PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {} ExtendedPC result(); protected: void do_task(const os::SuspendedThreadTaskContext& context); private: ExtendedPC _epc; }; ExtendedPC PcFetcher::result() { guarantee(is_done(), "task is not done yet."); return _epc; } void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) { Thread* thread = context.thread(); OSThread* osthread = thread->osthread(); if (osthread->ucontext() != NULL) { _epc = os::Aix::ucontext_get_pc((ucontext_t *) context.ucontext()); } else { // NULL context is unexpected, double-check this is the VMThread. guarantee(thread->is_VM_thread(), "can only be called for VMThread"); } } // Suspends the target using the signal mechanism and then grabs the PC before // resuming the target. Used by the flat-profiler only ExtendedPC os::get_thread_pc(Thread* thread) { // Make sure that it is called by the watcher for the VMThread. assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); assert(thread->is_VM_thread(), "Can only be called for VMThread"); PcFetcher fetcher(thread); fetcher.run(); return fetcher.result(); } // Not neede on Aix. // int os::Aix::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime) { // } //////////////////////////////////////////////////////////////////////////////// // debug support static address same_page(address x, address y) { intptr_t page_bits = -os::vm_page_size(); if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits)) return x; else if (x > y) return (address)(intptr_t(y) | ~page_bits) + 1; else return (address)(intptr_t(y) & page_bits); } bool os::find(address addr, outputStream* st) { Unimplemented(); return false; } //////////////////////////////////////////////////////////////////////////////// // misc // This does not do anything on Aix. This is basically a hook for being // able to use structured exception handling (thread-local exception filters) // on, e.g., Win32. void os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, JavaCallArguments* args, Thread* thread) { f(value, method, args, thread); } void os::print_statistics() { } int os::message_box(const char* title, const char* message) { int i; fdStream err(defaultStream::error_fd()); for (i = 0; i < 78; i++) err.print_raw("="); err.cr(); err.print_raw_cr(title); for (i = 0; i < 78; i++) err.print_raw("-"); err.cr(); err.print_raw_cr(message); for (i = 0; i < 78; i++) err.print_raw("="); err.cr(); char buf[16]; // Prevent process from exiting upon "read error" without consuming all CPU while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } return buf[0] == 'y' || buf[0] == 'Y'; } int os::stat(const char *path, struct stat *sbuf) { char pathbuf[MAX_PATH]; if (strlen(path) > MAX_PATH - 1) { errno = ENAMETOOLONG; return -1; } os::native_path(strcpy(pathbuf, path)); return ::stat(pathbuf, sbuf); } bool os::check_heap(bool force) { return true; } // int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) { // return ::vsnprintf(buf, count, format, args); // } // Is a (classpath) directory empty? bool os::dir_is_empty(const char* path) { Unimplemented(); return false; } // This code originates from JDK's sysOpen and open64_w // from src/solaris/hpi/src/system_md.c #ifndef O_DELETE #define O_DELETE 0x10000 #endif // Open a file. Unlink the file immediately after open returns // if the specified oflag has the O_DELETE flag set. // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c int os::open(const char *path, int oflag, int mode) { if (strlen(path) > MAX_PATH - 1) { errno = ENAMETOOLONG; return -1; } int fd; int o_delete = (oflag & O_DELETE); oflag = oflag & ~O_DELETE; fd = ::open64(path, oflag, mode); if (fd == -1) return -1; //If the open succeeded, the file might still be a directory { struct stat64 buf64; int ret = ::fstat64(fd, &buf64); int st_mode = buf64.st_mode; if (ret != -1) { if ((st_mode & S_IFMT) == S_IFDIR) { errno = EISDIR; ::close(fd); return -1; } } else { ::close(fd); return -1; } } // All file descriptors that are opened in the JVM and not // specifically destined for a subprocess should have the // close-on-exec flag set. If we don't set it, then careless 3rd // party native code might fork and exec without closing all // appropriate file descriptors (e.g. as we do in closeDescriptors in // UNIXProcess.c), and this in turn might: // // - cause end-of-file to fail to be detected on some file // descriptors, resulting in mysterious hangs, or // // - might cause an fopen in the subprocess to fail on a system // suffering from bug 1085341. // // (Yes, the default setting of the close-on-exec flag is a Unix // design flaw.) // // See: // 1085341: 32-bit stdio routines should support file descriptors >255 // 4843136: (process) pipe file descriptor from Runtime.exec not being closed // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 #ifdef FD_CLOEXEC { int flags = ::fcntl(fd, F_GETFD); if (flags != -1) ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); } #endif if (o_delete != 0) { ::unlink(path); } return fd; } // create binary file, rewriting existing file if required int os::create_binary_file(const char* path, bool rewrite_existing) { Unimplemented(); return 0; } // return current position of file pointer jlong os::current_file_offset(int fd) { return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR); } // move file pointer to the specified offset jlong os::seek_to_file_offset(int fd, jlong offset) { return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET); } // This code originates from JDK's sysAvailable // from src/solaris/hpi/src/native_threads/src/sys_api_td.c int os::available(int fd, jlong *bytes) { jlong cur, end; int mode; struct stat64 buf64; if (::fstat64(fd, &buf64) >= 0) { mode = buf64.st_mode; if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { // XXX: is the following call interruptible? If so, this might // need to go through the INTERRUPT_IO() wrapper as for other // blocking, interruptible calls in this file. int n; if (::ioctl(fd, FIONREAD, &n) >= 0) { *bytes = n; return 1; } } } if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) { return 0; } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) { return 0; } else if (::lseek64(fd, cur, SEEK_SET) == -1) { return 0; } *bytes = end - cur; return 1; } int os::socket_available(int fd, jint *pbytes) { // Linux doc says EINTR not returned, unlike Solaris int ret = ::ioctl(fd, FIONREAD, pbytes); //%% note ioctl can return 0 when successful, JVM_SocketAvailable // is expected to return 0 on failure and 1 on success to the jdk. return (ret < 0) ? 0 : 1; } // Map a block of memory. char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, char *addr, size_t bytes, bool read_only, bool allow_exec) { Unimplemented(); return NULL; } // Remap a block of memory. char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, char *addr, size_t bytes, bool read_only, bool allow_exec) { // same as map_memory() on this OS return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec); } // Unmap a block of memory. bool os::pd_unmap_memory(char* addr, size_t bytes) { return munmap(addr, bytes) == 0; } // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) // are used by JVM M&M and JVMTI to get user+sys or user CPU time // of a thread. // // current_thread_cpu_time() and thread_cpu_time(Thread*) returns // the fast estimate available on the platform. jlong os::current_thread_cpu_time() { // return user + sys since the cost is the same const jlong n = os::thread_cpu_time(Thread::current(), true /* user + sys */); assert(n >= 0, "negative CPU time"); return n; } jlong os::thread_cpu_time(Thread* thread) { // consistent with what current_thread_cpu_time() returns const jlong n = os::thread_cpu_time(thread, true /* user + sys */); assert(n >= 0, "negative CPU time"); return n; } jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { const jlong n = os::thread_cpu_time(Thread::current(), user_sys_cpu_time); assert(n >= 0, "negative CPU time"); return n; } static bool thread_cpu_time_unchecked(Thread* thread, jlong* p_sys_time, jlong* p_user_time) { bool error = false; jlong sys_time = 0; jlong user_time = 0; // reimplemented using getthrds64(). // // goes like this: // For the thread in question, get the kernel thread id. Then get the // kernel thread statistics using that id. // // This only works of course when no pthread scheduling is used, // ie there is a 1:1 relationship to kernel threads. // On AIX, see AIXTHREAD_SCOPE variable. pthread_t pthtid = thread->osthread()->pthread_id(); // retrieve kernel thread id for the pthread: tid64_t tid = 0; struct __pthrdsinfo pinfo; // I just love those otherworldly IBM APIs which force me to hand down // dummy buffers for stuff I dont care for... char dummy[1]; int dummy_size = sizeof(dummy); if (pthread_getthrds_np(&pthtid, PTHRDSINFO_QUERY_TID, &pinfo, sizeof(pinfo), dummy, &dummy_size) == 0) { tid = pinfo.__pi_tid; } else { tty->print_cr("pthread_getthrds_np failed."); error = true; } // retrieve kernel timing info for that kernel thread if (!error) { struct thrdentry64 thrdentry; if (getthrds64(getpid(), &thrdentry, sizeof(thrdentry), &tid, 1) == 1) { sys_time = thrdentry.ti_ru.ru_stime.tv_sec * 1000000000LL + thrdentry.ti_ru.ru_stime.tv_usec * 1000LL; user_time = thrdentry.ti_ru.ru_utime.tv_sec * 1000000000LL + thrdentry.ti_ru.ru_utime.tv_usec * 1000LL; } else { tty->print_cr("pthread_getthrds_np failed."); error = true; } } if (p_sys_time) { *p_sys_time = sys_time; } if (p_user_time) { *p_user_time = user_time; } if (error) { return false; } return true; } jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { jlong sys_time; jlong user_time; if (!thread_cpu_time_unchecked(thread, &sys_time, &user_time)) { return -1; } return user_sys_cpu_time ? sys_time + user_time : user_time; } void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits info_ptr->may_skip_backward = false; // elapsed time not wall time info_ptr->may_skip_forward = false; // elapsed time not wall time info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned } void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits info_ptr->may_skip_backward = false; // elapsed time not wall time info_ptr->may_skip_forward = false; // elapsed time not wall time info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned } bool os::is_thread_cpu_time_supported() { return true; } // System loadavg support. Returns -1 if load average cannot be obtained. // For now just return the system wide load average (no processor sets). int os::loadavg(double values[], int nelem) { // Implemented using libperfstat on AIX. guarantee(nelem >= 0 && nelem <= 3, "argument error"); guarantee(values, "argument error"); if (os::Aix::on_pase()) { Unimplemented(); return -1; } else { // AIX: use libperfstat // // See also: // http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf1/perfstat_cputot.htm // /usr/include/libperfstat.h: // Use the already AIX version independent get_cpuinfo. os::Aix::cpuinfo_t ci; if (os::Aix::get_cpuinfo(&ci)) { for (int i = 0; i < nelem; i++) { values[i] = ci.loadavg[i]; } } else { return -1; } return nelem; } } void os::pause() { char filename[MAX_PATH]; if (PauseAtStartupFile && PauseAtStartupFile[0]) { jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); } else { jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); } int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd != -1) { struct stat buf; ::close(fd); while (::stat(filename, &buf) == 0) { (void)::poll(NULL, 0, 100); } } else { jio_fprintf(stderr, "Could not open pause file '%s', continuing immediately.\n", filename); } } bool os::Aix::is_primordial_thread() { if (pthread_self() == (pthread_t)1) { return true; } else { return false; } } // OS recognitions (PASE/AIX, OS level) call this before calling any // one of Aix::on_pase(), Aix::os_version() static void os::Aix::initialize_os_info() { assert(_on_pase == -1 && _os_version == -1, "already called."); struct utsname uts; memset(&uts, 0, sizeof(uts)); strcpy(uts.sysname, "?"); if (::uname(&uts) == -1) { fprintf(stderr, "uname failed (%d)\n", errno); guarantee(0, "Could not determine whether we run on AIX or PASE"); } else { if (Verbose) { fprintf(stderr,"uname says: sysname \"%s\" version \"%s\" release \"%s\" " "node \"%s\" machine \"%s\"\n", uts.sysname, uts.version, uts.release, uts.nodename, uts.machine); } const int major = atoi(uts.version); assert(major > 0, "invalid OS version"); const int minor = atoi(uts.release); assert(minor > 0, "invalid OS release"); _os_version = (major << 8) | minor; if (strcmp(uts.sysname, "OS400") == 0) { Unimplemented(); } else if (strcmp(uts.sysname, "AIX") == 0) { // We run on AIX. We do not support versions older than AIX 5.3. _on_pase = 0; if (_os_version < 0x0503) { fprintf(stderr, "AIX release older than AIX 5.3 not supported.\n"); assert(false, "AIX release too old."); } else { if (Verbose) { fprintf(stderr, "We run on AIX %d.%d\n", major, minor); } } } else { assert(false, "unknown OS"); } } guarantee(_on_pase != -1 && _os_version, "Could not determine AIX/OS400 release"); } // end: os::Aix::initialize_os_info() // Scan environment for important settings which might effect the VM. // Trace out settings. Warn about invalid settings and/or correct them. // // Must run after os::Aix::initialue_os_info(). void os::Aix::scan_environment() { char* p; int rc; // Warn explicity if EXTSHM=ON is used. That switch changes how // System V shared memory behaves. One effect is that page size of // shared memory cannot be change dynamically, effectivly preventing // large pages from working. // This switch was needed on AIX 32bit, but on AIX 64bit the general // recommendation is (in OSS notes) to switch it off. p = ::getenv("EXTSHM"); if (Verbose) { fprintf(stderr, "EXTSHM=%s.\n", p ? p : "<unset>"); } if (p && strcmp(p, "ON") == 0) { fprintf(stderr, "Unsupported setting: EXTSHM=ON. Large Page support will be disabled.\n"); _extshm = 1; } else { _extshm = 0; } // SPEC1170 behaviour: will change the behaviour of a number of POSIX APIs. // Not tested, not supported. // // Note that it might be worth the trouble to test and to require it, if only to // get useful return codes for mprotect. // // Note: Setting XPG_SUS_ENV in the process is too late. Must be set earlier (before // exec() ? before loading the libjvm ? ....) p = ::getenv("XPG_SUS_ENV"); if (Verbose) { fprintf(stderr, "XPG_SUS_ENV=%s.\n", p ? p : "<unset>"); } if (p && strcmp(p, "ON") == 0) { _xpg_sus_mode = 1; fprintf(stderr, "Unsupported setting: XPG_SUS_ENV=ON\n"); // This is not supported. Worst of all, it changes behaviour of mmap MAP_FIXED to // clobber address ranges. If we ever want to support that, we have to do some // testing first. guarantee(false, "XPG_SUS_ENV=ON not supported"); } else { _xpg_sus_mode = 0; } // Switch off AIX internal (pthread) guard pages. This has // immediate effect for any pthread_create calls which follow. p = ::getenv("AIXTHREAD_GUARDPAGES"); if (Verbose) { fprintf(stderr, "AIXTHREAD_GUARDPAGES=%s.\n", p ? p : "<unset>"); fprintf(stderr, "setting AIXTHREAD_GUARDPAGES=0.\n"); } rc = ::putenv("AIXTHREAD_GUARDPAGES=0"); guarantee(rc == 0, ""); } // end: os::Aix::scan_environment() // PASE: initialize the libo4 library (AS400 PASE porting library). void os::Aix::initialize_libo4() { Unimplemented(); } // AIX: initialize the libperfstat library (we load this dynamically // because it is only available on AIX. void os::Aix::initialize_libperfstat() { assert(os::Aix::on_aix(), "AIX only"); if (!libperfstat::init()) { fprintf(stderr, "libperfstat initialization failed.\n"); assert(false, "libperfstat initialization failed"); } else { if (Verbose) { fprintf(stderr, "libperfstat initialized.\n"); } } } // end: os::Aix::initialize_libperfstat ///////////////////////////////////////////////////////////////////////////// // thread stack // function to query the current stack size using pthread_getthrds_np // // ! do not change anything here unless you know what you are doing ! static void query_stack_dimensions(address* p_stack_base, size_t* p_stack_size) { // This only works when invoked on a pthread. As we agreed not to use // primordial threads anyway, I assert here guarantee(!os::Aix::is_primordial_thread(), "not allowed on the primordial thread"); // information about this api can be found (a) in the pthread.h header and // (b) in http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf1/pthread_getthrds_np.htm // // The use of this API to find out the current stack is kind of undefined. // But after a lot of tries and asking IBM about it, I concluded that it is safe // enough for cases where I let the pthread library create its stacks. For cases // where I create an own stack and pass this to pthread_create, it seems not to // work (the returned stack size in that case is 0). pthread_t tid = pthread_self(); struct __pthrdsinfo pinfo; char dummy[1]; // we only need this to satisfy the api and to not get E int dummy_size = sizeof(dummy); memset(&pinfo, 0, sizeof(pinfo)); const int rc = pthread_getthrds_np (&tid, PTHRDSINFO_QUERY_ALL, &pinfo, sizeof(pinfo), dummy, &dummy_size); if (rc != 0) { fprintf(stderr, "pthread_getthrds_np failed (%d)\n", rc); guarantee(0, "pthread_getthrds_np failed"); } guarantee(pinfo.__pi_stackend, "returned stack base invalid"); // the following can happen when invoking pthread_getthrds_np on a pthread running on a user provided stack // (when handing down a stack to pthread create, see pthread_attr_setstackaddr). // Not sure what to do here - I feel inclined to forbid this use case completely. guarantee(pinfo.__pi_stacksize, "returned stack size invalid"); // On AIX, stacks are not necessarily page aligned so round the base and size accordingly if (p_stack_base) { (*p_stack_base) = (address) align_size_up((intptr_t)pinfo.__pi_stackend, os::Aix::stack_page_size()); } if (p_stack_size) { (*p_stack_size) = pinfo.__pi_stacksize - os::Aix::stack_page_size(); } #ifndef PRODUCT if (Verbose) { fprintf(stderr, "query_stack_dimensions() -> real stack_base=" INTPTR_FORMAT ", real stack_addr=" INTPTR_FORMAT ", real stack_size=" INTPTR_FORMAT ", stack_base=" INTPTR_FORMAT ", stack_size=" INTPTR_FORMAT "\n", (intptr_t)pinfo.__pi_stackend, (intptr_t)pinfo.__pi_stackaddr, pinfo.__pi_stacksize, (intptr_t)align_size_up((intptr_t)pinfo.__pi_stackend, os::Aix::stack_page_size()), pinfo.__pi_stacksize - os::Aix::stack_page_size()); } #endif } // end query_stack_dimensions // get the current stack base from the OS (actually, the pthread library) address os::current_stack_base() { address p; query_stack_dimensions(&p, 0); return p; } // get the current stack size from the OS (actually, the pthread library) size_t os::current_stack_size() { size_t s; query_stack_dimensions(0, &s); return s; } // Refer to the comments in os_solaris.cpp park-unpark. // // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. // For specifics regarding the bug see GLIBC BUGID 261237 : // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar // is used. (The simple C test-case provided in the GLIBC bug report manifests the // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() // and monitorenter when we're using 1-0 locking. All those operations may result in // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version // of libpthread avoids the problem, but isn't practical. // // Possible remedies: // // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. // This is palliative and probabilistic, however. If the thread is preempted // between the call to compute_abstime() and pthread_cond_timedwait(), more // than the minimum period may have passed, and the abstime may be stale (in the // past) resultin in a hang. Using this technique reduces the odds of a hang // but the JVM is still vulnerable, particularly on heavily loaded systems. // // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead // of the usual flag-condvar-mutex idiom. The write side of the pipe is set // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) // reduces to poll()+read(). This works well, but consumes 2 FDs per extant // thread. // // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing // a timeout request to the chron thread and then blocking via pthread_cond_wait(). // This also works well. In fact it avoids kernel-level scalability impediments // on certain platforms that don't handle lots of active pthread_cond_timedwait() // timers in a graceful fashion. // // 4. When the abstime value is in the past it appears that control returns // correctly from pthread_cond_timedwait(), but the condvar is left corrupt. // Subsequent timedwait/wait calls may hang indefinitely. Given that, we // can avoid the problem by reinitializing the condvar -- by cond_destroy() // followed by cond_init() -- after all calls to pthread_cond_timedwait(). // It may be possible to avoid reinitialization by checking the return // value from pthread_cond_timedwait(). In addition to reinitializing the // condvar we must establish the invariant that cond_signal() is only called // within critical sections protected by the adjunct mutex. This prevents // cond_signal() from "seeing" a condvar that's in the midst of being // reinitialized or that is corrupt. Sadly, this invariant obviates the // desirable signal-after-unlock optimization that avoids futile context switching. // // I'm also concerned that some versions of NTPL might allocate an auxilliary // structure when a condvar is used or initialized. cond_destroy() would // release the helper structure. Our reinitialize-after-timedwait fix // put excessive stress on malloc/free and locks protecting the c-heap. // // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. // It may be possible to refine (4) by checking the kernel and NTPL verisons // and only enabling the work-around for vulnerable environments. // utility to compute the abstime argument to timedwait: // millis is the relative timeout time // abstime will be the absolute timeout time // TODO: replace compute_abstime() with unpackTime() static struct timespec* compute_abstime(timespec* abstime, jlong millis) { if (millis < 0) millis = 0; struct timeval now; int status = gettimeofday(&now, NULL); assert(status == 0, "gettimeofday"); jlong seconds = millis / 1000; millis %= 1000; if (seconds > 50000000) { // see man cond_timedwait(3T) seconds = 50000000; } abstime->tv_sec = now.tv_sec + seconds; long usec = now.tv_usec + millis * 1000; if (usec >= 1000000) { abstime->tv_sec += 1; usec -= 1000000; } abstime->tv_nsec = usec * 1000; return abstime; } // Test-and-clear _Event, always leaves _Event set to 0, returns immediately. // Conceptually TryPark() should be equivalent to park(0). int os::PlatformEvent::TryPark() { for (;;) { const int v = _Event; guarantee ((v == 0) || (v == 1), "invariant"); if (Atomic::cmpxchg (0, &_Event, v) == v) return v; } } void os::PlatformEvent::park() { // AKA "down()" // Invariant: Only the thread associated with the Event/PlatformEvent // may call park(). // TODO: assert that _Assoc != NULL or _Assoc == Self int v; for (;;) { v = _Event; if (Atomic::cmpxchg (v-1, &_Event, v) == v) break; } guarantee (v >= 0, "invariant"); if (v == 0) { // Do this the hard way by blocking ... int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); guarantee (_nParked == 0, "invariant"); ++ _nParked; while (_Event < 0) { status = pthread_cond_wait(_cond, _mutex); assert_status(status == 0 || status == ETIMEDOUT, status, "cond_timedwait"); } -- _nParked; // In theory we could move the ST of 0 into _Event past the unlock(), // but then we'd need a MEMBAR after the ST. _Event = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); } guarantee (_Event >= 0, "invariant"); } int os::PlatformEvent::park(jlong millis) { guarantee (_nParked == 0, "invariant"); int v; for (;;) { v = _Event; if (Atomic::cmpxchg (v-1, &_Event, v) == v) break; } guarantee (v >= 0, "invariant"); if (v != 0) return OS_OK; // We do this the hard way, by blocking the thread. // Consider enforcing a minimum timeout value. struct timespec abst; compute_abstime(&abst, millis); int ret = OS_TIMEOUT; int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); guarantee (_nParked == 0, "invariant"); ++_nParked; // Object.wait(timo) will return because of // (a) notification // (b) timeout // (c) thread.interrupt // // Thread.interrupt and object.notify{All} both call Event::set. // That is, we treat thread.interrupt as a special case of notification. // The underlying Solaris implementation, cond_timedwait, admits // spurious/premature wakeups, but the JLS/JVM spec prevents the // JVM from making those visible to Java code. As such, we must // filter out spurious wakeups. We assume all ETIME returns are valid. // // TODO: properly differentiate simultaneous notify+interrupt. // In that case, we should propagate the notify to another waiter. while (_Event < 0) { status = pthread_cond_timedwait(_cond, _mutex, &abst); assert_status(status == 0 || status == ETIMEDOUT, status, "cond_timedwait"); if (!FilterSpuriousWakeups) break; // previous semantics if (status == ETIMEDOUT) break; // We consume and ignore EINTR and spurious wakeups. } --_nParked; if (_Event >= 0) { ret = OS_OK; } _Event = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); assert (_nParked == 0, "invariant"); return ret; } void os::PlatformEvent::unpark() { int v, AnyWaiters; for (;;) { v = _Event; if (v > 0) { // The LD of _Event could have reordered or be satisfied // by a read-aside from this processor's write buffer. // To avoid problems execute a barrier and then // ratify the value. OrderAccess::fence(); if (_Event == v) return; continue; } if (Atomic::cmpxchg (v+1, &_Event, v) == v) break; } if (v < 0) { // Wait for the thread associated with the event to vacate int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); AnyWaiters = _nParked; if (AnyWaiters != 0) { // We intentional signal *after* dropping the lock // to avoid a common class of futile wakeups. status = pthread_cond_signal(_cond); assert_status(status == 0, status, "cond_signal"); } // Mutex should be locked for pthread_cond_signal(_cond). status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); } // Note that we signal() _after dropping the lock for "immortal" Events. // This is safe and avoids a common class of futile wakeups. In rare // circumstances this can cause a thread to return prematurely from // cond_{timed}wait() but the spurious wakeup is benign and the victim will // simply re-test the condition and re-park itself. } // JSR166 // ------------------------------------------------------- // // The solaris and linux implementations of park/unpark are fairly // conservative for now, but can be improved. They currently use a // mutex/condvar pair, plus a a count. // Park decrements count if > 0, else does a condvar wait. Unpark // sets count to 1 and signals condvar. Only one thread ever waits // on the condvar. Contention seen when trying to park implies that someone // is unparking you, so don't wait. And spurious returns are fine, so there // is no need to track notifications. // #define MAX_SECS 100000000 // // This code is common to linux and solaris and will be moved to a // common place in dolphin. // // The passed in time value is either a relative time in nanoseconds // or an absolute time in milliseconds. Either way it has to be unpacked // into suitable seconds and nanoseconds components and stored in the // given timespec structure. // Given time is a 64-bit value and the time_t used in the timespec is only // a signed-32-bit value (except on 64-bit Linux) we have to watch for // overflow if times way in the future are given. Further on Solaris versions // prior to 10 there is a restriction (see cond_timedwait) that the specified // number of seconds, in abstime, is less than current_time + 100,000,000. // As it will be 28 years before "now + 100000000" will overflow we can // ignore overflow and just impose a hard-limit on seconds using the value // of "now + 100,000,000". This places a limit on the timeout of about 3.17 // years from "now". // static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { assert (time > 0, "convertTime"); struct timeval now; int status = gettimeofday(&now, NULL); assert(status == 0, "gettimeofday"); time_t max_secs = now.tv_sec + MAX_SECS; if (isAbsolute) { jlong secs = time / 1000; if (secs > max_secs) { absTime->tv_sec = max_secs; } else { absTime->tv_sec = secs; } absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; } else { jlong secs = time / NANOSECS_PER_SEC; if (secs >= MAX_SECS) { absTime->tv_sec = max_secs; absTime->tv_nsec = 0; } else { absTime->tv_sec = now.tv_sec + secs; absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; if (absTime->tv_nsec >= NANOSECS_PER_SEC) { absTime->tv_nsec -= NANOSECS_PER_SEC; ++absTime->tv_sec; // note: this must be <= max_secs } } } assert(absTime->tv_sec >= 0, "tv_sec < 0"); assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); } void Parker::park(bool isAbsolute, jlong time) { // Optional fast-path check: // Return immediately if a permit is available. if (_counter > 0) { _counter = 0; OrderAccess::fence(); return; } Thread* thread = Thread::current(); assert(thread->is_Java_thread(), "Must be JavaThread"); JavaThread *jt = (JavaThread *)thread; // Optional optimization -- avoid state transitions if there's an interrupt pending. // Check interrupt before trying to wait if (Thread::is_interrupted(thread, false)) { return; } // Next, demultiplex/decode time arguments timespec absTime; if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all return; } if (time > 0) { unpackTime(&absTime, isAbsolute, time); } // Enter safepoint region // Beware of deadlocks such as 6317397. // The per-thread Parker:: mutex is a classic leaf-lock. // In particular a thread must never block on the Threads_lock while // holding the Parker:: mutex. If safepoints are pending both the // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. ThreadBlockInVM tbivm(jt); // Don't wait if cannot get lock since interference arises from // unblocking. Also. check interrupt before trying wait if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { return; } int status; if (_counter > 0) { // no wait needed _counter = 0; status = pthread_mutex_unlock(_mutex); assert (status == 0, "invariant"); OrderAccess::fence(); return; } #ifdef ASSERT // Don't catch signals while blocked; let the running threads have the signals. // (This allows a debugger to break into the running thread.) sigset_t oldsigs; sigset_t* allowdebug_blocked = os::Aix::allowdebug_blocked_signals(); pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); #endif OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); jt->set_suspend_equivalent(); // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() if (time == 0) { status = pthread_cond_wait (_cond, _mutex); } else { status = pthread_cond_timedwait (_cond, _mutex, &absTime); if (status != 0 && WorkAroundNPTLTimedWaitHang) { pthread_cond_destroy (_cond); pthread_cond_init (_cond, NULL); } } assert_status(status == 0 || status == EINTR || status == ETIME || status == ETIMEDOUT, status, "cond_timedwait"); #ifdef ASSERT pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); #endif _counter = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "invariant"); // If externally suspended while waiting, re-suspend if (jt->handle_special_suspend_equivalent_condition()) { jt->java_suspend_self(); } OrderAccess::fence(); } void Parker::unpark() { int s, status; status = pthread_mutex_lock(_mutex); assert (status == 0, "invariant"); s = _counter; _counter = 1; if (s < 1) { if (WorkAroundNPTLTimedWaitHang) { status = pthread_cond_signal (_cond); assert (status == 0, "invariant"); status = pthread_mutex_unlock(_mutex); assert (status == 0, "invariant"); } else { status = pthread_mutex_unlock(_mutex); assert (status == 0, "invariant"); status = pthread_cond_signal (_cond); assert (status == 0, "invariant"); } } else { pthread_mutex_unlock(_mutex); assert (status == 0, "invariant"); } } extern char** environ; // Run the specified command in a separate process. Return its exit value, // or -1 on failure (e.g. can't fork a new process). // Unlike system(), this function can be called from signal handler. It // doesn't block SIGINT et al. int os::fork_and_exec(char* cmd) { Unimplemented(); return 0; } // is_headless_jre() // // Test for the existence of xawt/libmawt.so or libawt_xawt.so // in order to report if we are running in a headless jre. // // Since JDK8 xawt/libmawt.so is moved into the same directory // as libawt.so, and renamed libawt_xawt.so bool os::is_headless_jre() { struct stat statbuf; char buf[MAXPATHLEN]; char libmawtpath[MAXPATHLEN]; const char *xawtstr = "/xawt/libmawt.so"; const char *new_xawtstr = "/libawt_xawt.so"; char *p; // Get path to libjvm.so os::jvm_path(buf, sizeof(buf)); // Get rid of libjvm.so p = strrchr(buf, '/'); if (p == NULL) return false; else *p = '\0'; // Get rid of client or server p = strrchr(buf, '/'); if (p == NULL) return false; else *p = '\0'; // check xawt/libmawt.so strcpy(libmawtpath, buf); strcat(libmawtpath, xawtstr); if (::stat(libmawtpath, &statbuf) == 0) return false; // check libawt_xawt.so strcpy(libmawtpath, buf); strcat(libmawtpath, new_xawtstr); if (::stat(libmawtpath, &statbuf) == 0) return false; return true; } // Get the default path to the core file // Returns the length of the string int os::get_core_path(char* buffer, size_t bufferSize) { const char* p = get_current_directory(buffer, bufferSize); if (p == NULL) { assert(p != NULL, "failed to get current directory"); return 0; } return strlen(buffer); } #ifndef PRODUCT void TestReserveMemorySpecial_test() { // No tests available for this platform } #endif 8026487: PPC64: Implement 'os::fork_and_exec' on AIX Reviewed-by: kvn, twisti /* * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright 2012, 2013 SAP AG. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ // According to the AIX OS doc #pragma alloca must be used // with C++ compiler before referencing the function alloca() #pragma alloca // no precompiled headers #include "classfile/classLoader.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmSymbols.hpp" #include "code/icBuffer.hpp" #include "code/vtableStubs.hpp" #include "compiler/compileBroker.hpp" #include "interpreter/interpreter.hpp" #include "jvm_aix.h" #include "libperfstat_aix.hpp" #include "loadlib_aix.hpp" #include "memory/allocation.inline.hpp" #include "memory/filemap.hpp" #include "mutex_aix.inline.hpp" #include "oops/oop.inline.hpp" #include "os_share_aix.hpp" #include "porting_aix.hpp" #include "prims/jniFastGetField.hpp" #include "prims/jvm.h" #include "prims/jvm_misc.hpp" #include "runtime/arguments.hpp" #include "runtime/extendedPC.hpp" #include "runtime/globals.hpp" #include "runtime/interfaceSupport.hpp" #include "runtime/java.hpp" #include "runtime/javaCalls.hpp" #include "runtime/mutexLocker.hpp" #include "runtime/objectMonitor.hpp" #include "runtime/osThread.hpp" #include "runtime/perfMemory.hpp" #include "runtime/sharedRuntime.hpp" #include "runtime/statSampler.hpp" #include "runtime/stubRoutines.hpp" #include "runtime/threadCritical.hpp" #include "runtime/timer.hpp" #include "services/attachListener.hpp" #include "services/runtimeService.hpp" #include "thread_aix.inline.hpp" #include "utilities/decoder.hpp" #include "utilities/defaultStream.hpp" #include "utilities/events.hpp" #include "utilities/growableArray.hpp" #include "utilities/vmError.hpp" #ifdef TARGET_ARCH_ppc # include "assembler_ppc.inline.hpp" # include "nativeInst_ppc.hpp" #endif #ifdef COMPILER1 #include "c1/c1_Runtime1.hpp" #endif #ifdef COMPILER2 #include "opto/runtime.hpp" #endif // put OS-includes here (sorted alphabetically) #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <poll.h> #include <procinfo.h> #include <pthread.h> #include <pwd.h> #include <semaphore.h> #include <signal.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/ipc.h> #include <sys/mman.h> #include <sys/resource.h> #include <sys/select.h> #include <sys/shm.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/sysinfo.h> #include <sys/systemcfg.h> #include <sys/time.h> #include <sys/times.h> #include <sys/types.h> #include <sys/utsname.h> #include <sys/vminfo.h> #include <sys/wait.h> // Add missing declarations (should be in procinfo.h but isn't until AIX 6.1). #if !defined(_AIXVERSION_610) extern "C" { int getthrds64(pid_t ProcessIdentifier, struct thrdentry64* ThreadBuffer, int ThreadSize, tid64_t* IndexPointer, int Count); } #endif // Excerpts from systemcfg.h definitions newer than AIX 5.3 #ifndef PV_7 # define PV_7 0x200000 // Power PC 7 # define PV_7_Compat 0x208000 // Power PC 7 #endif #define MAX_PATH (2 * K) // for timer info max values which include all bits #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) // for multipage initialization error analysis (in 'g_multipage_error') #define ERROR_MP_OS_TOO_OLD 100 #define ERROR_MP_EXTSHM_ACTIVE 101 #define ERROR_MP_VMGETINFO_FAILED 102 #define ERROR_MP_VMGETINFO_CLAIMS_NO_SUPPORT_FOR_64K 103 // the semantics in this file are thus that codeptr_t is a *real code ptr* // This means that any function taking codeptr_t as arguments will assume // a real codeptr and won't handle function descriptors (eg getFuncName), // whereas functions taking address as args will deal with function // descriptors (eg os::dll_address_to_library_name) typedef unsigned int* codeptr_t; // typedefs for stackslots, stack pointers, pointers to op codes typedef unsigned long stackslot_t; typedef stackslot_t* stackptr_t; // query dimensions of the stack of the calling thread static void query_stack_dimensions(address* p_stack_base, size_t* p_stack_size); // function to check a given stack pointer against given stack limits inline bool is_valid_stackpointer(stackptr_t sp, stackptr_t stack_base, size_t stack_size) { if (((uintptr_t)sp) & 0x7) { return false; } if (sp > stack_base) { return false; } if (sp < (stackptr_t) ((address)stack_base - stack_size)) { return false; } return true; } // returns true if function is a valid codepointer inline bool is_valid_codepointer(codeptr_t p) { if (!p) { return false; } if (((uintptr_t)p) & 0x3) { return false; } if (LoadedLibraries::find_for_text_address((address)p) == NULL) { return false; } return true; } // macro to check a given stack pointer against given stack limits and to die if test fails #define CHECK_STACK_PTR(sp, stack_base, stack_size) { \ guarantee(is_valid_stackpointer((stackptr_t)(sp), (stackptr_t)(stack_base), stack_size), "Stack Pointer Invalid"); \ } // macro to check the current stack pointer against given stacklimits #define CHECK_CURRENT_STACK_PTR(stack_base, stack_size) { \ address sp; \ sp = os::current_stack_pointer(); \ CHECK_STACK_PTR(sp, stack_base, stack_size); \ } //////////////////////////////////////////////////////////////////////////////// // global variables (for a description see os_aix.hpp) julong os::Aix::_physical_memory = 0; pthread_t os::Aix::_main_thread = ((pthread_t)0); int os::Aix::_page_size = -1; int os::Aix::_on_pase = -1; int os::Aix::_os_version = -1; int os::Aix::_stack_page_size = -1; size_t os::Aix::_shm_default_page_size = -1; int os::Aix::_can_use_64K_pages = -1; int os::Aix::_can_use_16M_pages = -1; int os::Aix::_xpg_sus_mode = -1; int os::Aix::_extshm = -1; int os::Aix::_logical_cpus = -1; //////////////////////////////////////////////////////////////////////////////// // local variables static int g_multipage_error = -1; // error analysis for multipage initialization static jlong initial_time_count = 0; static int clock_tics_per_sec = 100; static sigset_t check_signal_done; // For diagnostics to print a message once (see run_periodic_checks) static bool check_signals = true; static pid_t _initial_pid = 0; static int SR_signum = SIGUSR2; // Signal used to suspend/resume a thread (must be > SIGSEGV, see 4355769) static sigset_t SR_sigset; static pthread_mutex_t dl_mutex; // Used to protect dlsym() calls */ julong os::available_memory() { return Aix::available_memory(); } julong os::Aix::available_memory() { os::Aix::meminfo_t mi; if (os::Aix::get_meminfo(&mi)) { return mi.real_free; } else { return 0xFFFFFFFFFFFFFFFFLL; } } julong os::physical_memory() { return Aix::physical_memory(); } //////////////////////////////////////////////////////////////////////////////// // environment support bool os::getenv(const char* name, char* buf, int len) { const char* val = ::getenv(name); if (val != NULL && strlen(val) < (size_t)len) { strcpy(buf, val); return true; } if (len > 0) buf[0] = 0; // return a null string return false; } // Return true if user is running as root. bool os::have_special_privileges() { static bool init = false; static bool privileges = false; if (!init) { privileges = (getuid() != geteuid()) || (getgid() != getegid()); init = true; } return privileges; } // Helper function, emulates disclaim64 using multiple 32bit disclaims // because we cannot use disclaim64() on AS/400 and old AIX releases. static bool my_disclaim64(char* addr, size_t size) { if (size == 0) { return true; } // Maximum size 32bit disclaim() accepts. (Theoretically 4GB, but I just do not trust that.) const unsigned int maxDisclaimSize = 0x80000000; const unsigned int numFullDisclaimsNeeded = (size / maxDisclaimSize); const unsigned int lastDisclaimSize = (size % maxDisclaimSize); char* p = addr; for (int i = 0; i < numFullDisclaimsNeeded; i ++) { if (::disclaim(p, maxDisclaimSize, DISCLAIM_ZEROMEM) != 0) { //if (Verbose) fprintf(stderr, "Cannot disclaim %p - %p (errno %d)\n", p, p + maxDisclaimSize, errno); return false; } p += maxDisclaimSize; } if (lastDisclaimSize > 0) { if (::disclaim(p, lastDisclaimSize, DISCLAIM_ZEROMEM) != 0) { //if (Verbose) fprintf(stderr, "Cannot disclaim %p - %p (errno %d)\n", p, p + lastDisclaimSize, errno); return false; } } return true; } // Cpu architecture string #if defined(PPC32) static char cpu_arch[] = "ppc"; #elif defined(PPC64) static char cpu_arch[] = "ppc64"; #else #error Add appropriate cpu_arch setting #endif // Given an address, returns the size of the page backing that address. size_t os::Aix::query_pagesize(void* addr) { vm_page_info pi; pi.addr = (uint64_t)addr; if (::vmgetinfo(&pi, VM_PAGE_INFO, sizeof(pi)) == 0) { return pi.pagesize; } else { fprintf(stderr, "vmgetinfo failed to retrieve page size for address %p (errno %d).\n", addr, errno); assert(false, "vmgetinfo failed to retrieve page size"); return SIZE_4K; } } // Returns the kernel thread id of the currently running thread. pid_t os::Aix::gettid() { return (pid_t) thread_self(); } void os::Aix::initialize_system_info() { // get the number of online(logical) cpus instead of configured os::_processor_count = sysconf(_SC_NPROCESSORS_ONLN); assert(_processor_count > 0, "_processor_count must be > 0"); // retrieve total physical storage os::Aix::meminfo_t mi; if (!os::Aix::get_meminfo(&mi)) { fprintf(stderr, "os::Aix::get_meminfo failed.\n"); fflush(stderr); assert(false, "os::Aix::get_meminfo failed."); } _physical_memory = (julong) mi.real_total; } // Helper function for tracing page sizes. static const char* describe_pagesize(size_t pagesize) { switch (pagesize) { case SIZE_4K : return "4K"; case SIZE_64K: return "64K"; case SIZE_16M: return "16M"; case SIZE_16G: return "16G"; default: assert(false, "surprise"); return "??"; } } // Retrieve information about multipage size support. Will initialize // Aix::_page_size, Aix::_stack_page_size, Aix::_can_use_64K_pages, // Aix::_can_use_16M_pages. // Must be called before calling os::large_page_init(). void os::Aix::query_multipage_support() { guarantee(_page_size == -1 && _stack_page_size == -1 && _can_use_64K_pages == -1 && _can_use_16M_pages == -1 && g_multipage_error == -1, "do not call twice"); _page_size = ::sysconf(_SC_PAGESIZE); // This really would surprise me. assert(_page_size == SIZE_4K, "surprise!"); // query default data page size (default page size for C-Heap, pthread stacks and .bss). // Default data page size is influenced either by linker options (-bdatapsize) // or by environment variable LDR_CNTRL (suboption DATAPSIZE). If none is given, // default should be 4K. size_t data_page_size = SIZE_4K; { void* p = ::malloc(SIZE_16M); data_page_size = os::Aix::query_pagesize(p); ::free(p); } // query default shm page size (LDR_CNTRL SHMPSIZE) { const int shmid = ::shmget(IPC_PRIVATE, 1, IPC_CREAT | S_IRUSR | S_IWUSR); guarantee(shmid != -1, "shmget failed"); void* p = ::shmat(shmid, NULL, 0); ::shmctl(shmid, IPC_RMID, NULL); guarantee(p != (void*) -1, "shmat failed"); _shm_default_page_size = os::Aix::query_pagesize(p); ::shmdt(p); } // before querying the stack page size, make sure we are not running as primordial // thread (because primordial thread's stack may have different page size than // pthread thread stacks). Running a VM on the primordial thread won't work for a // number of reasons so we may just as well guarantee it here guarantee(!os::Aix::is_primordial_thread(), "Must not be called for primordial thread"); // query stack page size { int dummy = 0; _stack_page_size = os::Aix::query_pagesize(&dummy); // everything else would surprise me and should be looked into guarantee(_stack_page_size == SIZE_4K || _stack_page_size == SIZE_64K, "Wrong page size"); // also, just for completeness: pthread stacks are allocated from C heap, so // stack page size should be the same as data page size guarantee(_stack_page_size == data_page_size, "stack page size should be the same as data page size"); } // EXTSHM is bad: among other things, it prevents setting pagesize dynamically // for system V shm. if (Aix::extshm()) { if (Verbose) { fprintf(stderr, "EXTSHM is active - will disable large page support.\n" "Please make sure EXTSHM is OFF for large page support.\n"); } g_multipage_error = ERROR_MP_EXTSHM_ACTIVE; _can_use_64K_pages = _can_use_16M_pages = 0; goto query_multipage_support_end; } // now check which page sizes the OS claims it supports, and of those, which actually can be used. { const int MAX_PAGE_SIZES = 4; psize_t sizes[MAX_PAGE_SIZES]; const int num_psizes = ::vmgetinfo(sizes, VMINFO_GETPSIZES, MAX_PAGE_SIZES); if (num_psizes == -1) { if (Verbose) { fprintf(stderr, "vmgetinfo(VMINFO_GETPSIZES) failed (errno: %d)\n", errno); fprintf(stderr, "disabling multipage support.\n"); } g_multipage_error = ERROR_MP_VMGETINFO_FAILED; _can_use_64K_pages = _can_use_16M_pages = 0; goto query_multipage_support_end; } guarantee(num_psizes > 0, "vmgetinfo(.., VMINFO_GETPSIZES, ...) failed."); assert(num_psizes <= MAX_PAGE_SIZES, "Surprise! more than 4 page sizes?"); if (Verbose) { fprintf(stderr, "vmgetinfo(.., VMINFO_GETPSIZES, ...) returns %d supported page sizes: ", num_psizes); for (int i = 0; i < num_psizes; i ++) { fprintf(stderr, " %s ", describe_pagesize(sizes[i])); } fprintf(stderr, " .\n"); } // Can we use 64K, 16M pages? _can_use_64K_pages = 0; _can_use_16M_pages = 0; for (int i = 0; i < num_psizes; i ++) { if (sizes[i] == SIZE_64K) { _can_use_64K_pages = 1; } else if (sizes[i] == SIZE_16M) { _can_use_16M_pages = 1; } } if (!_can_use_64K_pages) { g_multipage_error = ERROR_MP_VMGETINFO_CLAIMS_NO_SUPPORT_FOR_64K; } // Double-check for 16M pages: Even if AIX claims to be able to use 16M pages, // there must be an actual 16M page pool, and we must run with enough rights. if (_can_use_16M_pages) { const int shmid = ::shmget(IPC_PRIVATE, SIZE_16M, IPC_CREAT | S_IRUSR | S_IWUSR); guarantee(shmid != -1, "shmget failed"); struct shmid_ds shm_buf = { 0 }; shm_buf.shm_pagesize = SIZE_16M; const bool can_set_pagesize = ::shmctl(shmid, SHM_PAGESIZE, &shm_buf) == 0 ? true : false; const int en = errno; ::shmctl(shmid, IPC_RMID, NULL); if (!can_set_pagesize) { if (Verbose) { fprintf(stderr, "Failed to allocate even one misely 16M page. shmctl failed with %d (%s).\n" "Will deactivate 16M support.\n", en, strerror(en)); } _can_use_16M_pages = 0; } } } // end: check which pages can be used for shared memory query_multipage_support_end: guarantee(_page_size != -1 && _stack_page_size != -1 && _can_use_64K_pages != -1 && _can_use_16M_pages != -1, "Page sizes not properly initialized"); if (_can_use_64K_pages) { g_multipage_error = 0; } if (Verbose) { fprintf(stderr, "Data page size (C-Heap, bss, etc): %s\n", describe_pagesize(data_page_size)); fprintf(stderr, "Thread stack page size (pthread): %s\n", describe_pagesize(_stack_page_size)); fprintf(stderr, "Default shared memory page size: %s\n", describe_pagesize(_shm_default_page_size)); fprintf(stderr, "Can use 64K pages dynamically with shared meory: %s\n", (_can_use_64K_pages ? "yes" :"no")); fprintf(stderr, "Can use 16M pages dynamically with shared memory: %s\n", (_can_use_16M_pages ? "yes" :"no")); fprintf(stderr, "Multipage error details: %d\n", g_multipage_error); } } // end os::Aix::query_multipage_support() // The code for this method was initially derived from the version in os_linux.cpp void os::init_system_properties_values() { // The next few definitions allow the code to be verbatim: #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal) #define DEFAULT_LIBPATH "/usr/lib:/lib" #define EXTENSIONS_DIR "/lib/ext" #define ENDORSED_DIR "/lib/endorsed" // sysclasspath, java_home, dll_dir char *home_path; char *dll_path; char *pslash; char buf[MAXPATHLEN]; os::jvm_path(buf, sizeof(buf)); // Found the full path to libjvm.so. // Now cut the path to <java_home>/jre if we can. *(strrchr(buf, '/')) = '\0'; // get rid of /libjvm.so pslash = strrchr(buf, '/'); if (pslash != NULL) { *pslash = '\0'; // get rid of /{client|server|hotspot} } dll_path = malloc(strlen(buf) + 1); strcpy(dll_path, buf); Arguments::set_dll_dir(dll_path); if (pslash != NULL) { pslash = strrchr(buf, '/'); if (pslash != NULL) { *pslash = '\0'; // get rid of /<arch> pslash = strrchr(buf, '/'); if (pslash != NULL) { *pslash = '\0'; // get rid of /lib } } } home_path = malloc(strlen(buf) + 1); strcpy(home_path, buf); Arguments::set_java_home(home_path); if (!set_boot_path('/', ':')) return; // Where to look for native libraries // On Aix we get the user setting of LIBPATH // Eventually, all the library path setting will be done here. char *ld_library_path; // Construct the invariant part of ld_library_path. ld_library_path = (char *) malloc(sizeof(DEFAULT_LIBPATH)); sprintf(ld_library_path, DEFAULT_LIBPATH); // Get the user setting of LIBPATH, and prepended it. char *v = ::getenv("LIBPATH"); if (v == NULL) { v = ""; } char *t = ld_library_path; // That's +1 for the colon and +1 for the trailing '\0' ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1); sprintf(ld_library_path, "%s:%s", v, t); Arguments::set_library_path(ld_library_path); // Extensions directories char* cbuf = malloc(strlen(Arguments::get_java_home()) + sizeof(EXTENSIONS_DIR)); sprintf(cbuf, "%s" EXTENSIONS_DIR, Arguments::get_java_home()); Arguments::set_ext_dirs(cbuf); // Endorsed standards default directory. cbuf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR)); sprintf(cbuf, "%s" ENDORSED_DIR, Arguments::get_java_home()); Arguments::set_endorsed_dirs(cbuf); #undef malloc #undef DEFAULT_LIBPATH #undef EXTENSIONS_DIR #undef ENDORSED_DIR } //////////////////////////////////////////////////////////////////////////////// // breakpoint support void os::breakpoint() { BREAKPOINT; } extern "C" void breakpoint() { // use debugger to set breakpoint here } //////////////////////////////////////////////////////////////////////////////// // signal support debug_only(static bool signal_sets_initialized = false); static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; bool os::Aix::is_sig_ignored(int sig) { struct sigaction oact; sigaction(sig, (struct sigaction*)NULL, &oact); void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) : CAST_FROM_FN_PTR(void*, oact.sa_handler); if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) return true; else return false; } void os::Aix::signal_sets_init() { // Should also have an assertion stating we are still single-threaded. assert(!signal_sets_initialized, "Already initialized"); // Fill in signals that are necessarily unblocked for all threads in // the VM. Currently, we unblock the following signals: // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden // by -Xrs (=ReduceSignalUsage)); // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all // other threads. The "ReduceSignalUsage" boolean tells us not to alter // the dispositions or masks wrt these signals. // Programs embedding the VM that want to use the above signals for their // own purposes must, at this time, use the "-Xrs" option to prevent // interference with shutdown hooks and BREAK_SIGNAL thread dumping. // (See bug 4345157, and other related bugs). // In reality, though, unblocking these signals is really a nop, since // these signals are not blocked by default. sigemptyset(&unblocked_sigs); sigemptyset(&allowdebug_blocked_sigs); sigaddset(&unblocked_sigs, SIGILL); sigaddset(&unblocked_sigs, SIGSEGV); sigaddset(&unblocked_sigs, SIGBUS); sigaddset(&unblocked_sigs, SIGFPE); sigaddset(&unblocked_sigs, SIGTRAP); sigaddset(&unblocked_sigs, SIGDANGER); sigaddset(&unblocked_sigs, SR_signum); if (!ReduceSignalUsage) { if (!os::Aix::is_sig_ignored(SHUTDOWN1_SIGNAL)) { sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); } if (!os::Aix::is_sig_ignored(SHUTDOWN2_SIGNAL)) { sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); } if (!os::Aix::is_sig_ignored(SHUTDOWN3_SIGNAL)) { sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); } } // Fill in signals that are blocked by all but the VM thread. sigemptyset(&vm_sigs); if (!ReduceSignalUsage) sigaddset(&vm_sigs, BREAK_SIGNAL); debug_only(signal_sets_initialized = true); } // These are signals that are unblocked while a thread is running Java. // (For some reason, they get blocked by default.) sigset_t* os::Aix::unblocked_signals() { assert(signal_sets_initialized, "Not initialized"); return &unblocked_sigs; } // These are the signals that are blocked while a (non-VM) thread is // running Java. Only the VM thread handles these signals. sigset_t* os::Aix::vm_signals() { assert(signal_sets_initialized, "Not initialized"); return &vm_sigs; } // These are signals that are blocked during cond_wait to allow debugger in sigset_t* os::Aix::allowdebug_blocked_signals() { assert(signal_sets_initialized, "Not initialized"); return &allowdebug_blocked_sigs; } void os::Aix::hotspot_sigmask(Thread* thread) { //Save caller's signal mask before setting VM signal mask sigset_t caller_sigmask; pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); OSThread* osthread = thread->osthread(); osthread->set_caller_sigmask(caller_sigmask); pthread_sigmask(SIG_UNBLOCK, os::Aix::unblocked_signals(), NULL); if (!ReduceSignalUsage) { if (thread->is_VM_thread()) { // Only the VM thread handles BREAK_SIGNAL ... pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); } else { // ... all other threads block BREAK_SIGNAL pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); } } } // retrieve memory information. // Returns false if something went wrong; // content of pmi undefined in this case. bool os::Aix::get_meminfo(meminfo_t* pmi) { assert(pmi, "get_meminfo: invalid parameter"); memset(pmi, 0, sizeof(meminfo_t)); if (os::Aix::on_pase()) { Unimplemented(); return false; } else { // On AIX, I use the (dynamically loaded) perfstat library to retrieve memory statistics // See: // http://publib.boulder.ibm.com/infocenter/systems/index.jsp // ?topic=/com.ibm.aix.basetechref/doc/basetrf1/perfstat_memtot.htm // http://publib.boulder.ibm.com/infocenter/systems/index.jsp // ?topic=/com.ibm.aix.files/doc/aixfiles/libperfstat.h.htm perfstat_memory_total_t psmt; memset (&psmt, '\0', sizeof(psmt)); const int rc = libperfstat::perfstat_memory_total(NULL, &psmt, sizeof(psmt), 1); if (rc == -1) { fprintf(stderr, "perfstat_memory_total() failed (errno=%d)\n", errno); assert(0, "perfstat_memory_total() failed"); return false; } assert(rc == 1, "perfstat_memory_total() - weird return code"); // excerpt from // http://publib.boulder.ibm.com/infocenter/systems/index.jsp // ?topic=/com.ibm.aix.files/doc/aixfiles/libperfstat.h.htm // The fields of perfstat_memory_total_t: // u_longlong_t virt_total Total virtual memory (in 4 KB pages). // u_longlong_t real_total Total real memory (in 4 KB pages). // u_longlong_t real_free Free real memory (in 4 KB pages). // u_longlong_t pgsp_total Total paging space (in 4 KB pages). // u_longlong_t pgsp_free Free paging space (in 4 KB pages). pmi->virt_total = psmt.virt_total * 4096; pmi->real_total = psmt.real_total * 4096; pmi->real_free = psmt.real_free * 4096; pmi->pgsp_total = psmt.pgsp_total * 4096; pmi->pgsp_free = psmt.pgsp_free * 4096; return true; } } // end os::Aix::get_meminfo // Retrieve global cpu information. // Returns false if something went wrong; // the content of pci is undefined in this case. bool os::Aix::get_cpuinfo(cpuinfo_t* pci) { assert(pci, "get_cpuinfo: invalid parameter"); memset(pci, 0, sizeof(cpuinfo_t)); perfstat_cpu_total_t psct; memset (&psct, '\0', sizeof(psct)); if (-1 == libperfstat::perfstat_cpu_total(NULL, &psct, sizeof(perfstat_cpu_total_t), 1)) { fprintf(stderr, "perfstat_cpu_total() failed (errno=%d)\n", errno); assert(0, "perfstat_cpu_total() failed"); return false; } // global cpu information strcpy (pci->description, psct.description); pci->processorHZ = psct.processorHZ; pci->ncpus = psct.ncpus; os::Aix::_logical_cpus = psct.ncpus; for (int i = 0; i < 3; i++) { pci->loadavg[i] = (double) psct.loadavg[i] / (1 << SBITS); } // get the processor version from _system_configuration switch (_system_configuration.version) { case PV_7: strcpy(pci->version, "Power PC 7"); break; case PV_6_1: strcpy(pci->version, "Power PC 6 DD1.x"); break; case PV_6: strcpy(pci->version, "Power PC 6"); break; case PV_5: strcpy(pci->version, "Power PC 5"); break; case PV_5_2: strcpy(pci->version, "Power PC 5_2"); break; case PV_5_3: strcpy(pci->version, "Power PC 5_3"); break; case PV_5_Compat: strcpy(pci->version, "PV_5_Compat"); break; case PV_6_Compat: strcpy(pci->version, "PV_6_Compat"); break; case PV_7_Compat: strcpy(pci->version, "PV_7_Compat"); break; default: strcpy(pci->version, "unknown"); } return true; } //end os::Aix::get_cpuinfo ////////////////////////////////////////////////////////////////////////////// // detecting pthread library void os::Aix::libpthread_init() { return; } ////////////////////////////////////////////////////////////////////////////// // create new thread // Thread start routine for all newly created threads static void *java_start(Thread *thread) { // find out my own stack dimensions { // actually, this should do exactly the same as thread->record_stack_base_and_size... address base = 0; size_t size = 0; query_stack_dimensions(&base, &size); thread->set_stack_base(base); thread->set_stack_size(size); } // Do some sanity checks. CHECK_CURRENT_STACK_PTR(thread->stack_base(), thread->stack_size()); // Try to randomize the cache line index of hot stack frames. // This helps when threads of the same stack traces evict each other's // cache lines. The threads can be either from the same JVM instance, or // from different JVM instances. The benefit is especially true for // processors with hyperthreading technology. static int counter = 0; int pid = os::current_process_id(); alloca(((pid ^ counter++) & 7) * 128); ThreadLocalStorage::set_thread(thread); OSThread* osthread = thread->osthread(); // thread_id is kernel thread id (similar to Solaris LWP id) osthread->set_thread_id(os::Aix::gettid()); // initialize signal mask for this thread os::Aix::hotspot_sigmask(thread); // initialize floating point control register os::Aix::init_thread_fpu_state(); assert(osthread->get_state() == RUNNABLE, "invalid os thread state"); // call one more level start routine thread->run(); return 0; } bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { // We want the whole function to be synchronized. ThreadCritical cs; assert(thread->osthread() == NULL, "caller responsible"); // Allocate the OSThread object OSThread* osthread = new OSThread(NULL, NULL); if (osthread == NULL) { return false; } // set the correct thread state osthread->set_thread_type(thr_type); // Initial state is ALLOCATED but not INITIALIZED osthread->set_state(ALLOCATED); thread->set_osthread(osthread); // init thread attributes pthread_attr_t attr; pthread_attr_init(&attr); guarantee(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0, "???"); // Make sure we run in 1:1 kernel-user-thread mode. if (os::Aix::on_aix()) { guarantee(pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) == 0, "???"); guarantee(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) == 0, "???"); } // end: aix // Start in suspended state, and in os::thread_start, wake the thread up. guarantee(pthread_attr_setsuspendstate_np(&attr, PTHREAD_CREATE_SUSPENDED_NP) == 0, "???"); // calculate stack size if it's not specified by caller if (os::Aix::supports_variable_stack_size()) { if (stack_size == 0) { stack_size = os::Aix::default_stack_size(thr_type); switch (thr_type) { case os::java_thread: // Java threads use ThreadStackSize whose default value can be changed with the flag -Xss. assert(JavaThread::stack_size_at_create() > 0, "this should be set"); stack_size = JavaThread::stack_size_at_create(); break; case os::compiler_thread: if (CompilerThreadStackSize > 0) { stack_size = (size_t)(CompilerThreadStackSize * K); break; } // else fall through: // use VMThreadStackSize if CompilerThreadStackSize is not defined case os::vm_thread: case os::pgc_thread: case os::cgc_thread: case os::watcher_thread: if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); break; } } stack_size = MAX2(stack_size, os::Aix::min_stack_allowed); pthread_attr_setstacksize(&attr, stack_size); } //else let thread_create() pick the default value (96 K on AIX) pthread_t tid; int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); pthread_attr_destroy(&attr); if (ret != 0) { if (PrintMiscellaneous && (Verbose || WizardMode)) { perror("pthread_create()"); } // Need to clean up stuff we've allocated so far thread->set_osthread(NULL); delete osthread; return false; } // Store pthread info into the OSThread osthread->set_pthread_id(tid); return true; } ///////////////////////////////////////////////////////////////////////////// // attach existing thread // bootstrap the main thread bool os::create_main_thread(JavaThread* thread) { assert(os::Aix::_main_thread == pthread_self(), "should be called inside main thread"); return create_attached_thread(thread); } bool os::create_attached_thread(JavaThread* thread) { #ifdef ASSERT thread->verify_not_published(); #endif // Allocate the OSThread object OSThread* osthread = new OSThread(NULL, NULL); if (osthread == NULL) { return false; } // Store pthread info into the OSThread osthread->set_thread_id(os::Aix::gettid()); osthread->set_pthread_id(::pthread_self()); // initialize floating point control register os::Aix::init_thread_fpu_state(); // some sanity checks CHECK_CURRENT_STACK_PTR(thread->stack_base(), thread->stack_size()); // Initial thread state is RUNNABLE osthread->set_state(RUNNABLE); thread->set_osthread(osthread); if (UseNUMA) { int lgrp_id = os::numa_get_group_id(); if (lgrp_id != -1) { thread->set_lgrp_id(lgrp_id); } } // initialize signal mask for this thread // and save the caller's signal mask os::Aix::hotspot_sigmask(thread); return true; } void os::pd_start_thread(Thread* thread) { int status = pthread_continue_np(thread->osthread()->pthread_id()); assert(status == 0, "thr_continue failed"); } // Free OS resources related to the OSThread void os::free_thread(OSThread* osthread) { assert(osthread != NULL, "osthread not set"); if (Thread::current()->osthread() == osthread) { // Restore caller's signal mask sigset_t sigmask = osthread->caller_sigmask(); pthread_sigmask(SIG_SETMASK, &sigmask, NULL); } delete osthread; } ////////////////////////////////////////////////////////////////////////////// // thread local storage int os::allocate_thread_local_storage() { pthread_key_t key; int rslt = pthread_key_create(&key, NULL); assert(rslt == 0, "cannot allocate thread local storage"); return (int)key; } // Note: This is currently not used by VM, as we don't destroy TLS key // on VM exit. void os::free_thread_local_storage(int index) { int rslt = pthread_key_delete((pthread_key_t)index); assert(rslt == 0, "invalid index"); } void os::thread_local_storage_at_put(int index, void* value) { int rslt = pthread_setspecific((pthread_key_t)index, value); assert(rslt == 0, "pthread_setspecific failed"); } extern "C" Thread* get_thread() { return ThreadLocalStorage::thread(); } //////////////////////////////////////////////////////////////////////////////// // time support // Time since start-up in seconds to a fine granularity. // Used by VMSelfDestructTimer and the MemProfiler. double os::elapsedTime() { return (double)(os::elapsed_counter()) * 0.000001; } jlong os::elapsed_counter() { timeval time; int status = gettimeofday(&time, NULL); return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count; } jlong os::elapsed_frequency() { return (1000 * 1000); } // For now, we say that linux does not support vtime. I have no idea // whether it can actually be made to (DLD, 9/13/05). bool os::supports_vtime() { return false; } bool os::enable_vtime() { return false; } bool os::vtime_enabled() { return false; } double os::elapsedVTime() { // better than nothing, but not much return elapsedTime(); } jlong os::javaTimeMillis() { timeval time; int status = gettimeofday(&time, NULL); assert(status != -1, "aix error at gettimeofday()"); return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); } // We need to manually declare mread_real_time, // because IBM didn't provide a prototype in time.h. // (they probably only ever tested in C, not C++) extern "C" int mread_real_time(timebasestruct_t *t, size_t size_of_timebasestruct_t); jlong os::javaTimeNanos() { if (os::Aix::on_pase()) { Unimplemented(); return 0; } else { // On AIX use the precision of processors real time clock // or time base registers. timebasestruct_t time; int rc; // If the CPU has a time register, it will be used and // we have to convert to real time first. After convertion we have following data: // time.tb_high [seconds since 00:00:00 UTC on 1.1.1970] // time.tb_low [nanoseconds after the last full second above] // We better use mread_real_time here instead of read_real_time // to ensure that we will get a monotonic increasing time. if (mread_real_time(&time, TIMEBASE_SZ) != RTC_POWER) { rc = time_base_to_time(&time, TIMEBASE_SZ); assert(rc != -1, "aix error at time_base_to_time()"); } return jlong(time.tb_high) * (1000 * 1000 * 1000) + jlong(time.tb_low); } } void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { { // gettimeofday - based on time in seconds since the Epoch thus does not wrap info_ptr->max_value = ALL_64_BITS; // gettimeofday is a real time clock so it skips info_ptr->may_skip_backward = true; info_ptr->may_skip_forward = true; } info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time } // Return the real, user, and system times in seconds from an // arbitrary fixed point in the past. bool os::getTimesSecs(double* process_real_time, double* process_user_time, double* process_system_time) { Unimplemented(); return false; } char * os::local_time_string(char *buf, size_t buflen) { struct tm t; time_t long_time; time(&long_time); localtime_r(&long_time, &t); jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); return buf; } struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { return localtime_r(clock, res); } //////////////////////////////////////////////////////////////////////////////// // runtime exit support // Note: os::shutdown() might be called very early during initialization, or // called from signal handler. Before adding something to os::shutdown(), make // sure it is async-safe and can handle partially initialized VM. void os::shutdown() { // allow PerfMemory to attempt cleanup of any persistent resources perfMemory_exit(); // needs to remove object in file system AttachListener::abort(); // flush buffered output, finish log files ostream_abort(); // Check for abort hook abort_hook_t abort_hook = Arguments::abort_hook(); if (abort_hook != NULL) { abort_hook(); } } // Note: os::abort() might be called very early during initialization, or // called from signal handler. Before adding something to os::abort(), make // sure it is async-safe and can handle partially initialized VM. void os::abort(bool dump_core) { os::shutdown(); if (dump_core) { #ifndef PRODUCT fdStream out(defaultStream::output_fd()); out.print_raw("Current thread is "); char buf[16]; jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); out.print_raw_cr(buf); out.print_raw_cr("Dumping core ..."); #endif ::abort(); // dump core } ::exit(1); } // Die immediately, no exit hook, no abort hook, no cleanup. void os::die() { ::abort(); } // Unused on Aix for now. void os::set_error_file(const char *logfile) {} // This method is a copy of JDK's sysGetLastErrorString // from src/solaris/hpi/src/system_md.c size_t os::lasterror(char *buf, size_t len) { if (errno == 0) return 0; const char *s = ::strerror(errno); size_t n = ::strlen(s); if (n >= len) { n = len - 1; } ::strncpy(buf, s, n); buf[n] = '\0'; return n; } intx os::current_thread_id() { return (intx)pthread_self(); } int os::current_process_id() { // This implementation returns a unique pid, the pid of the // launcher thread that starts the vm 'process'. // Under POSIX, getpid() returns the same pid as the // launcher thread rather than a unique pid per thread. // Use gettid() if you want the old pre NPTL behaviour. // if you are looking for the result of a call to getpid() that // returns a unique pid for the calling thread, then look at the // OSThread::thread_id() method in osThread_linux.hpp file return (int)(_initial_pid ? _initial_pid : getpid()); } // DLL functions const char* os::dll_file_extension() { return ".so"; } // This must be hard coded because it's the system's temporary // directory not the java application's temp directory, ala java.io.tmpdir. const char* os::get_temp_directory() { return "/tmp"; } static bool file_exists(const char* filename) { struct stat statbuf; if (filename == NULL || strlen(filename) == 0) { return false; } return os::stat(filename, &statbuf) == 0; } bool os::dll_build_name(char* buffer, size_t buflen, const char* pname, const char* fname) { bool retval = false; // Copied from libhpi const size_t pnamelen = pname ? strlen(pname) : 0; // Return error on buffer overflow. if (pnamelen + strlen(fname) + 10 > (size_t) buflen) { *buffer = '\0'; return retval; } if (pnamelen == 0) { snprintf(buffer, buflen, "lib%s.so", fname); retval = true; } else if (strchr(pname, *os::path_separator()) != NULL) { int n; char** pelements = split_path(pname, &n); for (int i = 0; i < n; i++) { // Really shouldn't be NULL, but check can't hurt if (pelements[i] == NULL || strlen(pelements[i]) == 0) { continue; // skip the empty path values } snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname); if (file_exists(buffer)) { retval = true; break; } } // release the storage for (int i = 0; i < n; i++) { if (pelements[i] != NULL) { FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); } } if (pelements != NULL) { FREE_C_HEAP_ARRAY(char*, pelements, mtInternal); } } else { snprintf(buffer, buflen, "%s/lib%s.so", pname, fname); retval = true; } return retval; } // Check if addr is inside libjvm.so. bool os::address_is_in_vm(address addr) { // Input could be a real pc or a function pointer literal. The latter // would be a function descriptor residing in the data segment of a module. const LoadedLibraryModule* lib = LoadedLibraries::find_for_text_address(addr); if (lib) { if (strcmp(lib->get_shortname(), "libjvm.so") == 0) { return true; } else { return false; } } else { lib = LoadedLibraries::find_for_data_address(addr); if (lib) { if (strcmp(lib->get_shortname(), "libjvm.so") == 0) { return true; } else { return false; } } else { return false; } } } // Resolve an AIX function descriptor literal to a code pointer. // If the input is a valid code pointer to a text segment of a loaded module, // it is returned unchanged. // If the input is a valid AIX function descriptor, it is resolved to the // code entry point. // If the input is neither a valid function descriptor nor a valid code pointer, // NULL is returned. static address resolve_function_descriptor_to_code_pointer(address p) { const LoadedLibraryModule* lib = LoadedLibraries::find_for_text_address(p); if (lib) { // its a real code pointer return p; } else { lib = LoadedLibraries::find_for_data_address(p); if (lib) { // pointer to data segment, potential function descriptor address code_entry = (address)(((FunctionDescriptor*)p)->entry()); if (LoadedLibraries::find_for_text_address(code_entry)) { // Its a function descriptor return code_entry; } } } return NULL; } bool os::dll_address_to_function_name(address addr, char *buf, int buflen, int *offset) { if (offset) { *offset = -1; } if (buf) { buf[0] = '\0'; } // Resolve function ptr literals first. addr = resolve_function_descriptor_to_code_pointer(addr); if (!addr) { return false; } // Go through Decoder::decode to call getFuncName which reads the name from the traceback table. return Decoder::decode(addr, buf, buflen, offset); } static int getModuleName(codeptr_t pc, // [in] program counter char* p_name, size_t namelen, // [out] optional: function name char* p_errmsg, size_t errmsglen // [out] optional: user provided buffer for error messages ) { // initialize output parameters if (p_name && namelen > 0) { *p_name = '\0'; } if (p_errmsg && errmsglen > 0) { *p_errmsg = '\0'; } const LoadedLibraryModule* const lib = LoadedLibraries::find_for_text_address((address)pc); if (lib) { if (p_name && namelen > 0) { sprintf(p_name, "%.*s", namelen, lib->get_shortname()); } return 0; } if (Verbose) { fprintf(stderr, "pc outside any module"); } return -1; } bool os::dll_address_to_library_name(address addr, char* buf, int buflen, int* offset) { if (offset) { *offset = -1; } if (buf) { buf[0] = '\0'; } // Resolve function ptr literals first. addr = resolve_function_descriptor_to_code_pointer(addr); if (!addr) { return false; } if (::getModuleName((codeptr_t) addr, buf, buflen, 0, 0) == 0) { return true; } return false; } // Loads .dll/.so and in case of error it checks if .dll/.so was built // for the same architecture as Hotspot is running on void *os::dll_load(const char *filename, char *ebuf, int ebuflen) { if (ebuf && ebuflen > 0) { ebuf[0] = '\0'; ebuf[ebuflen - 1] = '\0'; } if (!filename || strlen(filename) == 0) { ::strncpy(ebuf, "dll_load: empty filename specified", ebuflen - 1); return NULL; } // RTLD_LAZY is currently not implemented. The dl is loaded immediately with all its dependants. void * result= ::dlopen(filename, RTLD_LAZY); if (result != NULL) { // Reload dll cache. Don't do this in signal handling. LoadedLibraries::reload(); return result; } else { // error analysis when dlopen fails const char* const error_report = ::dlerror(); if (error_report && ebuf && ebuflen > 0) { snprintf(ebuf, ebuflen - 1, "%s, LIBPATH=%s, LD_LIBRARY_PATH=%s : %s", filename, ::getenv("LIBPATH"), ::getenv("LD_LIBRARY_PATH"), error_report); } } return NULL; } // Glibc-2.0 libdl is not MT safe. If you are building with any glibc, // chances are you might want to run the generated bits against glibc-2.0 // libdl.so, so always use locking for any version of glibc. void* os::dll_lookup(void* handle, const char* name) { pthread_mutex_lock(&dl_mutex); void* res = dlsym(handle, name); pthread_mutex_unlock(&dl_mutex); return res; } void os::print_dll_info(outputStream *st) { st->print_cr("Dynamic libraries:"); LoadedLibraries::print(st); } void os::print_os_info(outputStream* st) { st->print("OS:"); st->print("uname:"); struct utsname name; uname(&name); st->print(name.sysname); st->print(" "); st->print(name.nodename); st->print(" "); st->print(name.release); st->print(" "); st->print(name.version); st->print(" "); st->print(name.machine); st->cr(); // rlimit st->print("rlimit:"); struct rlimit rlim; st->print(" STACK "); getrlimit(RLIMIT_STACK, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%uk", rlim.rlim_cur >> 10); st->print(", CORE "); getrlimit(RLIMIT_CORE, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%uk", rlim.rlim_cur >> 10); st->print(", NPROC "); st->print("%d", sysconf(_SC_CHILD_MAX)); st->print(", NOFILE "); getrlimit(RLIMIT_NOFILE, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%d", rlim.rlim_cur); st->print(", AS "); getrlimit(RLIMIT_AS, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%uk", rlim.rlim_cur >> 10); // Print limits on DATA, because it limits the C-heap. st->print(", DATA "); getrlimit(RLIMIT_DATA, &rlim); if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); else st->print("%uk", rlim.rlim_cur >> 10); st->cr(); // load average st->print("load average:"); double loadavg[3] = {-1.L, -1.L, -1.L}; os::loadavg(loadavg, 3); st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); st->cr(); } void os::print_memory_info(outputStream* st) { st->print_cr("Memory:"); st->print_cr(" default page size: %s", describe_pagesize(os::vm_page_size())); st->print_cr(" default stack page size: %s", describe_pagesize(os::vm_page_size())); st->print_cr(" default shm page size: %s", describe_pagesize(os::Aix::shm_default_page_size())); st->print_cr(" can use 64K pages dynamically: %s", (os::Aix::can_use_64K_pages() ? "yes" :"no")); st->print_cr(" can use 16M pages dynamically: %s", (os::Aix::can_use_16M_pages() ? "yes" :"no")); if (g_multipage_error != 0) { st->print_cr(" multipage error: %d", g_multipage_error); } // print out LDR_CNTRL because it affects the default page sizes const char* const ldr_cntrl = ::getenv("LDR_CNTRL"); st->print_cr(" LDR_CNTRL=%s.", ldr_cntrl ? ldr_cntrl : "<unset>"); const char* const extshm = ::getenv("EXTSHM"); st->print_cr(" EXTSHM=%s.", extshm ? extshm : "<unset>"); // Call os::Aix::get_meminfo() to retrieve memory statistics. os::Aix::meminfo_t mi; if (os::Aix::get_meminfo(&mi)) { char buffer[256]; if (os::Aix::on_aix()) { jio_snprintf(buffer, sizeof(buffer), " physical total : %llu\n" " physical free : %llu\n" " swap total : %llu\n" " swap free : %llu\n", mi.real_total, mi.real_free, mi.pgsp_total, mi.pgsp_free); } else { Unimplemented(); } st->print_raw(buffer); } else { st->print_cr(" (no more information available)"); } } void os::pd_print_cpu_info(outputStream* st) { // cpu st->print("CPU:"); st->print("total %d", os::processor_count()); // It's not safe to query number of active processors after crash // st->print("(active %d)", os::active_processor_count()); st->print(" %s", VM_Version::cpu_features()); st->cr(); } void os::print_siginfo(outputStream* st, void* siginfo) { // Use common posix version. os::Posix::print_siginfo_brief(st, (const siginfo_t*) siginfo); st->cr(); } static void print_signal_handler(outputStream* st, int sig, char* buf, size_t buflen); void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { st->print_cr("Signal Handlers:"); print_signal_handler(st, SIGSEGV, buf, buflen); print_signal_handler(st, SIGBUS , buf, buflen); print_signal_handler(st, SIGFPE , buf, buflen); print_signal_handler(st, SIGPIPE, buf, buflen); print_signal_handler(st, SIGXFSZ, buf, buflen); print_signal_handler(st, SIGILL , buf, buflen); print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); print_signal_handler(st, SR_signum, buf, buflen); print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); print_signal_handler(st, BREAK_SIGNAL, buf, buflen); print_signal_handler(st, SIGTRAP, buf, buflen); print_signal_handler(st, SIGDANGER, buf, buflen); } static char saved_jvm_path[MAXPATHLEN] = {0}; // Find the full path to the current module, libjvm.so or libjvm_g.so void os::jvm_path(char *buf, jint buflen) { // Error checking. if (buflen < MAXPATHLEN) { assert(false, "must use a large-enough buffer"); buf[0] = '\0'; return; } // Lazy resolve the path to current module. if (saved_jvm_path[0] != 0) { strcpy(buf, saved_jvm_path); return; } Dl_info dlinfo; int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo); assert(ret != 0, "cannot locate libjvm"); char* rp = realpath((char *)dlinfo.dli_fname, buf); assert(rp != NULL, "error in realpath(): maybe the 'path' argument is too long?"); strcpy(saved_jvm_path, buf); } void os::print_jni_name_prefix_on(outputStream* st, int args_size) { // no prefix required, not even "_" } void os::print_jni_name_suffix_on(outputStream* st, int args_size) { // no suffix required } //////////////////////////////////////////////////////////////////////////////// // sun.misc.Signal support static volatile jint sigint_count = 0; static void UserHandler(int sig, void *siginfo, void *context) { // 4511530 - sem_post is serialized and handled by the manager thread. When // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We // don't want to flood the manager thread with sem_post requests. if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) return; // Ctrl-C is pressed during error reporting, likely because the error // handler fails to abort. Let VM die immediately. if (sig == SIGINT && is_error_reported()) { os::die(); } os::signal_notify(sig); } void* os::user_handler() { return CAST_FROM_FN_PTR(void*, UserHandler); } extern "C" { typedef void (*sa_handler_t)(int); typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); } void* os::signal(int signal_number, void* handler) { struct sigaction sigAct, oldSigAct; sigfillset(&(sigAct.sa_mask)); // Do not block out synchronous signals in the signal handler. // Blocking synchronous signals only makes sense if you can really // be sure that those signals won't happen during signal handling, // when the blocking applies. Normal signal handlers are lean and // do not cause signals. But our signal handlers tend to be "risky" // - secondary SIGSEGV, SIGILL, SIGBUS' may and do happen. // On AIX, PASE there was a case where a SIGSEGV happened, followed // by a SIGILL, which was blocked due to the signal mask. The process // just hung forever. Better to crash from a secondary signal than to hang. sigdelset(&(sigAct.sa_mask), SIGSEGV); sigdelset(&(sigAct.sa_mask), SIGBUS); sigdelset(&(sigAct.sa_mask), SIGILL); sigdelset(&(sigAct.sa_mask), SIGFPE); sigdelset(&(sigAct.sa_mask), SIGTRAP); sigAct.sa_flags = SA_RESTART|SA_SIGINFO; sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); if (sigaction(signal_number, &sigAct, &oldSigAct)) { // -1 means registration failed return (void *)-1; } return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); } void os::signal_raise(int signal_number) { ::raise(signal_number); } // // The following code is moved from os.cpp for making this // code platform specific, which it is by its very nature. // // Will be modified when max signal is changed to be dynamic int os::sigexitnum_pd() { return NSIG; } // a counter for each possible signal value static volatile jint pending_signals[NSIG+1] = { 0 }; // Linux(POSIX) specific hand shaking semaphore. static sem_t sig_sem; void os::signal_init_pd() { // Initialize signal structures ::memset((void*)pending_signals, 0, sizeof(pending_signals)); // Initialize signal semaphore int rc = ::sem_init(&sig_sem, 0, 0); guarantee(rc != -1, "sem_init failed"); } void os::signal_notify(int sig) { Atomic::inc(&pending_signals[sig]); ::sem_post(&sig_sem); } static int check_pending_signals(bool wait) { Atomic::store(0, &sigint_count); for (;;) { for (int i = 0; i < NSIG + 1; i++) { jint n = pending_signals[i]; if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { return i; } } if (!wait) { return -1; } JavaThread *thread = JavaThread::current(); ThreadBlockInVM tbivm(thread); bool threadIsSuspended; do { thread->set_suspend_equivalent(); // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() ::sem_wait(&sig_sem); // were we externally suspended while we were waiting? threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); if (threadIsSuspended) { // // The semaphore has been incremented, but while we were waiting // another thread suspended us. We don't want to continue running // while suspended because that would surprise the thread that // suspended us. // ::sem_post(&sig_sem); thread->java_suspend_self(); } } while (threadIsSuspended); } } int os::signal_lookup() { return check_pending_signals(false); } int os::signal_wait() { return check_pending_signals(true); } //////////////////////////////////////////////////////////////////////////////// // Virtual Memory // AddrRange describes an immutable address range // // This is a helper class for the 'shared memory bookkeeping' below. class AddrRange { friend class ShmBkBlock; char* _start; size_t _size; public: AddrRange(char* start, size_t size) : _start(start), _size(size) {} AddrRange(const AddrRange& r) : _start(r.start()), _size(r.size()) {} char* start() const { return _start; } size_t size() const { return _size; } char* end() const { return _start + _size; } bool is_empty() const { return _size == 0 ? true : false; } static AddrRange empty_range() { return AddrRange(NULL, 0); } bool contains(const char* p) const { return start() <= p && end() > p; } bool contains(const AddrRange& range) const { return start() <= range.start() && end() >= range.end(); } bool intersects(const AddrRange& range) const { return (range.start() <= start() && range.end() > start()) || (range.start() < end() && range.end() >= end()) || contains(range); } bool is_same_range(const AddrRange& range) const { return start() == range.start() && size() == range.size(); } // return the closest inside range consisting of whole pages AddrRange find_closest_aligned_range(size_t pagesize) const { if (pagesize == 0 || is_empty()) { return empty_range(); } char* const from = (char*)align_size_up((intptr_t)_start, pagesize); char* const to = (char*)align_size_down((intptr_t)end(), pagesize); if (from > to) { return empty_range(); } return AddrRange(from, to - from); } }; //////////////////////////////////////////////////////////////////////////// // shared memory bookkeeping // // the os::reserve_memory() API and friends hand out different kind of memory, depending // on need and circumstances. Memory may be allocated with mmap() or with shmget/shmat. // // But these memory types have to be treated differently. For example, to uncommit // mmap-based memory, msync(MS_INVALIDATE) is needed, to uncommit shmat-based memory, // disclaim64() is needed. // // Therefore we need to keep track of the allocated memory segments and their // properties. // ShmBkBlock: base class for all blocks in the shared memory bookkeeping class ShmBkBlock { ShmBkBlock* _next; protected: AddrRange _range; const size_t _pagesize; const bool _pinned; public: ShmBkBlock(AddrRange range, size_t pagesize, bool pinned) : _range(range), _pagesize(pagesize), _pinned(pinned) , _next(NULL) { assert(_pagesize == SIZE_4K || _pagesize == SIZE_64K || _pagesize == SIZE_16M, "invalid page size"); assert(!_range.is_empty(), "invalid range"); } virtual void print(outputStream* st) const { st->print("0x%p ... 0x%p (%llu) - %d %s pages - %s", _range.start(), _range.end(), _range.size(), _range.size() / _pagesize, describe_pagesize(_pagesize), _pinned ? "pinned" : ""); } enum Type { MMAP, SHMAT }; virtual Type getType() = 0; char* base() const { return _range.start(); } size_t size() const { return _range.size(); } void setAddrRange(AddrRange range) { _range = range; } bool containsAddress(const char* p) const { return _range.contains(p); } bool containsRange(const char* p, size_t size) const { return _range.contains(AddrRange((char*)p, size)); } bool isSameRange(const char* p, size_t size) const { return _range.is_same_range(AddrRange((char*)p, size)); } virtual bool disclaim(char* p, size_t size) = 0; virtual bool release() = 0; // blocks live in a list. ShmBkBlock* next() const { return _next; } void set_next(ShmBkBlock* blk) { _next = blk; } }; // end: ShmBkBlock // ShmBkMappedBlock: describes an block allocated with mmap() class ShmBkMappedBlock : public ShmBkBlock { public: ShmBkMappedBlock(AddrRange range) : ShmBkBlock(range, SIZE_4K, false) {} // mmap: always 4K, never pinned void print(outputStream* st) const { ShmBkBlock::print(st); st->print_cr(" - mmap'ed"); } Type getType() { return MMAP; } bool disclaim(char* p, size_t size) { AddrRange r(p, size); guarantee(_range.contains(r), "invalid disclaim"); // only disclaim whole ranges. const AddrRange r2 = r.find_closest_aligned_range(_pagesize); if (r2.is_empty()) { return true; } const int rc = ::msync(r2.start(), r2.size(), MS_INVALIDATE); if (rc != 0) { warning("msync(0x%p, %llu, MS_INVALIDATE) failed (%d)\n", r2.start(), r2.size(), errno); } return rc == 0 ? true : false; } bool release() { // mmap'ed blocks are released using munmap if (::munmap(_range.start(), _range.size()) != 0) { warning("munmap(0x%p, %llu) failed (%d)\n", _range.start(), _range.size(), errno); return false; } return true; } }; // end: ShmBkMappedBlock // ShmBkShmatedBlock: describes an block allocated with shmget/shmat() class ShmBkShmatedBlock : public ShmBkBlock { public: ShmBkShmatedBlock(AddrRange range, size_t pagesize, bool pinned) : ShmBkBlock(range, pagesize, pinned) {} void print(outputStream* st) const { ShmBkBlock::print(st); st->print_cr(" - shmat'ed"); } Type getType() { return SHMAT; } bool disclaim(char* p, size_t size) { AddrRange r(p, size); if (_pinned) { return true; } // shmat'ed blocks are disclaimed using disclaim64 guarantee(_range.contains(r), "invalid disclaim"); // only disclaim whole ranges. const AddrRange r2 = r.find_closest_aligned_range(_pagesize); if (r2.is_empty()) { return true; } const bool rc = my_disclaim64(r2.start(), r2.size()); if (Verbose && !rc) { warning("failed to disclaim shm %p-%p\n", r2.start(), r2.end()); } return rc; } bool release() { bool rc = false; if (::shmdt(_range.start()) != 0) { warning("shmdt(0x%p) failed (%d)\n", _range.start(), errno); } else { rc = true; } return rc; } }; // end: ShmBkShmatedBlock static ShmBkBlock* g_shmbk_list = NULL; static volatile jint g_shmbk_table_lock = 0; // keep some usage statistics static struct { int nodes; // number of nodes in list size_t bytes; // reserved - not committed - bytes. int reserves; // how often reserve was called int lookups; // how often a lookup was made } g_shmbk_stats = { 0, 0, 0, 0 }; // add information about a shared memory segment to the bookkeeping static void shmbk_register(ShmBkBlock* p_block) { guarantee(p_block, "logic error"); p_block->set_next(g_shmbk_list); g_shmbk_list = p_block; g_shmbk_stats.reserves ++; g_shmbk_stats.bytes += p_block->size(); g_shmbk_stats.nodes ++; } // remove information about a shared memory segment by its starting address static void shmbk_unregister(ShmBkBlock* p_block) { ShmBkBlock* p = g_shmbk_list; ShmBkBlock* prev = NULL; while (p) { if (p == p_block) { if (prev) { prev->set_next(p->next()); } else { g_shmbk_list = p->next(); } g_shmbk_stats.nodes --; g_shmbk_stats.bytes -= p->size(); return; } prev = p; p = p->next(); } assert(false, "should not happen"); } // given a pointer, return shared memory bookkeeping record for the segment it points into // using the returned block info must happen under lock protection static ShmBkBlock* shmbk_find_by_containing_address(const char* addr) { g_shmbk_stats.lookups ++; ShmBkBlock* p = g_shmbk_list; while (p) { if (p->containsAddress(addr)) { return p; } p = p->next(); } return NULL; } // dump all information about all memory segments allocated with os::reserve_memory() void shmbk_dump_info() { tty->print_cr("-- shared mem bookkeeping (alive: %d segments, %llu bytes, " "total reserves: %d total lookups: %d)", g_shmbk_stats.nodes, g_shmbk_stats.bytes, g_shmbk_stats.reserves, g_shmbk_stats.lookups); const ShmBkBlock* p = g_shmbk_list; int i = 0; while (p) { p->print(tty); p = p->next(); i ++; } } #define LOCK_SHMBK { ThreadCritical _LOCK_SHMBK; #define UNLOCK_SHMBK } // End: shared memory bookkeeping //////////////////////////////////////////////////////////////////////////////////////////////////// int os::vm_page_size() { // Seems redundant as all get out assert(os::Aix::page_size() != -1, "must call os::init"); return os::Aix::page_size(); } // Aix allocates memory by pages. int os::vm_allocation_granularity() { assert(os::Aix::page_size() != -1, "must call os::init"); return os::Aix::page_size(); } int os::Aix::commit_memory_impl(char* addr, size_t size, bool exec) { // Commit is a noop. There is no explicit commit // needed on AIX. Memory is committed when touched. // // Debug : check address range for validity #ifdef ASSERT LOCK_SHMBK ShmBkBlock* const block = shmbk_find_by_containing_address(addr); if (!block) { fprintf(stderr, "invalid pointer: " INTPTR_FORMAT "\n", addr); shmbk_dump_info(); assert(false, "invalid pointer"); return false; } else if (!block->containsRange(addr, size)) { fprintf(stderr, "invalid range: " INTPTR_FORMAT " .. " INTPTR_FORMAT "\n", addr, addr + size); shmbk_dump_info(); assert(false, "invalid range"); return false; } UNLOCK_SHMBK #endif // ASSERT return 0; } bool os::pd_commit_memory(char* addr, size_t size, bool exec) { return os::Aix::commit_memory_impl(addr, size, exec) == 0; } void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec, const char* mesg) { assert(mesg != NULL, "mesg must be specified"); os::Aix::commit_memory_impl(addr, size, exec); } int os::Aix::commit_memory_impl(char* addr, size_t size, size_t alignment_hint, bool exec) { return os::Aix::commit_memory_impl(addr, size, exec); } bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint, bool exec) { return os::Aix::commit_memory_impl(addr, size, alignment_hint, exec) == 0; } void os::pd_commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint, bool exec, const char* mesg) { os::Aix::commit_memory_impl(addr, size, alignment_hint, exec); } bool os::pd_uncommit_memory(char* addr, size_t size) { // Delegate to ShmBkBlock class which knows how to uncommit its memory. bool rc = false; LOCK_SHMBK ShmBkBlock* const block = shmbk_find_by_containing_address(addr); if (!block) { fprintf(stderr, "invalid pointer: 0x%p.\n", addr); shmbk_dump_info(); assert(false, "invalid pointer"); return false; } else if (!block->containsRange(addr, size)) { fprintf(stderr, "invalid range: 0x%p .. 0x%p.\n", addr, addr + size); shmbk_dump_info(); assert(false, "invalid range"); return false; } rc = block->disclaim(addr, size); UNLOCK_SHMBK if (Verbose && !rc) { warning("failed to disclaim 0x%p .. 0x%p (0x%llX bytes).", addr, addr + size, size); } return rc; } bool os::pd_create_stack_guard_pages(char* addr, size_t size) { return os::guard_memory(addr, size); } bool os::remove_stack_guard_pages(char* addr, size_t size) { return os::unguard_memory(addr, size); } void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { } void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) { } void os::numa_make_global(char *addr, size_t bytes) { } void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { } bool os::numa_topology_changed() { return false; } size_t os::numa_get_groups_num() { return 1; } int os::numa_get_group_id() { return 0; } size_t os::numa_get_leaf_groups(int *ids, size_t size) { if (size > 0) { ids[0] = 0; return 1; } return 0; } bool os::get_page_info(char *start, page_info* info) { return false; } char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { return end; } // Flags for reserve_shmatted_memory: #define RESSHM_WISHADDR_OR_FAIL 1 #define RESSHM_TRY_16M_PAGES 2 #define RESSHM_16M_PAGES_OR_FAIL 4 // Result of reserve_shmatted_memory: struct shmatted_memory_info_t { char* addr; size_t pagesize; bool pinned; }; // Reserve a section of shmatted memory. // params: // bytes [in]: size of memory, in bytes // requested_addr [in]: wish address. // NULL = no wish. // If RESSHM_WISHADDR_OR_FAIL is set in flags and wish address cannot // be obtained, function will fail. Otherwise wish address is treated as hint and // another pointer is returned. // flags [in]: some flags. Valid flags are: // RESSHM_WISHADDR_OR_FAIL - fail if wish address is given and cannot be obtained. // RESSHM_TRY_16M_PAGES - try to allocate from 16M page pool // (requires UseLargePages and Use16MPages) // RESSHM_16M_PAGES_OR_FAIL - if you cannot allocate from 16M page pool, fail. // Otherwise any other page size will do. // p_info [out] : holds information about the created shared memory segment. static bool reserve_shmatted_memory(size_t bytes, char* requested_addr, int flags, shmatted_memory_info_t* p_info) { assert(p_info, "parameter error"); // init output struct. p_info->addr = NULL; // neither should we be here for EXTSHM=ON. if (os::Aix::extshm()) { ShouldNotReachHere(); } // extract flags. sanity checks. const bool wishaddr_or_fail = flags & RESSHM_WISHADDR_OR_FAIL; const bool try_16M_pages = flags & RESSHM_TRY_16M_PAGES; const bool f16M_pages_or_fail = flags & RESSHM_16M_PAGES_OR_FAIL; // first check: if a wish address is given and it is mandatory, but not aligned to segment boundary, // shmat will fail anyway, so save some cycles by failing right away if (requested_addr && ((uintptr_t)requested_addr % SIZE_256M == 0)) { if (wishaddr_or_fail) { return false; } else { requested_addr = NULL; } } char* addr = NULL; // Align size of shm up to the largest possible page size, to avoid errors later on when we try to change // pagesize dynamically. const size_t size = align_size_up(bytes, SIZE_16M); // reserve the shared segment int shmid = shmget(IPC_PRIVATE, size, IPC_CREAT | S_IRUSR | S_IWUSR); if (shmid == -1) { warning("shmget(.., %lld, ..) failed (errno: %d).", size, errno); return false; } // Important note: // It is very important that we, upon leaving this function, do not leave a shm segment alive. // We must right after attaching it remove it from the system. System V shm segments are global and // survive the process. // So, from here on: Do not assert. Do not return. Always do a "goto cleanup_shm". // try forcing the page size size_t pagesize = -1; // unknown so far if (UseLargePages) { struct shmid_ds shmbuf; memset(&shmbuf, 0, sizeof(shmbuf)); // First, try to take from 16M page pool if... if (os::Aix::can_use_16M_pages() // we can ... && Use16MPages // we are not explicitly forbidden to do so (-XX:-Use16MPages).. && try_16M_pages) { // caller wants us to. shmbuf.shm_pagesize = SIZE_16M; if (shmctl(shmid, SHM_PAGESIZE, &shmbuf) == 0) { pagesize = SIZE_16M; } else { warning("Failed to allocate %d 16M pages. 16M page pool might be exhausted. (shmctl failed with %d)", size / SIZE_16M, errno); if (f16M_pages_or_fail) { goto cleanup_shm; } } } // Nothing yet? Try setting 64K pages. Note that I never saw this fail, but in theory it might, // because the 64K page pool may also be exhausted. if (pagesize == -1) { shmbuf.shm_pagesize = SIZE_64K; if (shmctl(shmid, SHM_PAGESIZE, &shmbuf) == 0) { pagesize = SIZE_64K; } else { warning("Failed to allocate %d 64K pages. (shmctl failed with %d)", size / SIZE_64K, errno); // here I give up. leave page_size -1 - later, after attaching, we will query the // real page size of the attached memory. (in theory, it may be something different // from 4K if LDR_CNTRL SHM_PSIZE is set) } } } // sanity point assert(pagesize == -1 || pagesize == SIZE_16M || pagesize == SIZE_64K, "wrong page size"); // Now attach the shared segment. addr = (char*) shmat(shmid, requested_addr, 0); if (addr == (char*)-1) { // How to handle attach failure: // If it failed for a specific wish address, tolerate this: in that case, if wish address was // mandatory, fail, if not, retry anywhere. // If it failed for any other reason, treat that as fatal error. addr = NULL; if (requested_addr) { if (wishaddr_or_fail) { goto cleanup_shm; } else { addr = (char*) shmat(shmid, NULL, 0); if (addr == (char*)-1) { // fatal addr = NULL; warning("shmat failed (errno: %d)", errno); goto cleanup_shm; } } } else { // fatal addr = NULL; warning("shmat failed (errno: %d)", errno); goto cleanup_shm; } } // sanity point assert(addr && addr != (char*) -1, "wrong address"); // after successful Attach remove the segment - right away. if (::shmctl(shmid, IPC_RMID, NULL) == -1) { warning("shmctl(%u, IPC_RMID) failed (%d)\n", shmid, errno); guarantee(false, "failed to remove shared memory segment!"); } shmid = -1; // query the real page size. In case setting the page size did not work (see above), the system // may have given us something other then 4K (LDR_CNTRL) { const size_t real_pagesize = os::Aix::query_pagesize(addr); if (pagesize != -1) { assert(pagesize == real_pagesize, "unexpected pagesize after shmat"); } else { pagesize = real_pagesize; } } // Now register the reserved block with internal book keeping. LOCK_SHMBK const bool pinned = pagesize >= SIZE_16M ? true : false; ShmBkShmatedBlock* const p_block = new ShmBkShmatedBlock(AddrRange(addr, size), pagesize, pinned); assert(p_block, ""); shmbk_register(p_block); UNLOCK_SHMBK cleanup_shm: // if we have not done so yet, remove the shared memory segment. This is very important. if (shmid != -1) { if (::shmctl(shmid, IPC_RMID, NULL) == -1) { warning("shmctl(%u, IPC_RMID) failed (%d)\n", shmid, errno); guarantee(false, "failed to remove shared memory segment!"); } shmid = -1; } // trace if (Verbose && !addr) { if (requested_addr != NULL) { warning("failed to shm-allocate 0x%llX bytes at with address 0x%p.", size, requested_addr); } else { warning("failed to shm-allocate 0x%llX bytes at any address.", size); } } // hand info to caller if (addr) { p_info->addr = addr; p_info->pagesize = pagesize; p_info->pinned = pagesize == SIZE_16M ? true : false; } // sanity test: if (requested_addr && addr && wishaddr_or_fail) { guarantee(addr == requested_addr, "shmat error"); } // just one more test to really make sure we have no dangling shm segments. guarantee(shmid == -1, "dangling shm segments"); return addr ? true : false; } // end: reserve_shmatted_memory // Reserve memory using mmap. Behaves the same as reserve_shmatted_memory(): // will return NULL in case of an error. static char* reserve_mmaped_memory(size_t bytes, char* requested_addr) { // if a wish address is given, but not aligned to 4K page boundary, mmap will fail. if (requested_addr && ((uintptr_t)requested_addr % os::vm_page_size() != 0)) { warning("Wish address 0x%p not aligned to page boundary.", requested_addr); return NULL; } const size_t size = align_size_up(bytes, SIZE_4K); // Note: MAP_SHARED (instead of MAP_PRIVATE) needed to be able to // msync(MS_INVALIDATE) (see os::uncommit_memory) int flags = MAP_ANONYMOUS | MAP_SHARED; // MAP_FIXED is needed to enforce requested_addr - manpage is vague about what // it means if wishaddress is given but MAP_FIXED is not set. // // Note however that this changes semantics in SPEC1170 mode insofar as MAP_FIXED // clobbers the address range, which is probably not what the caller wants. That's // why I assert here (again) that the SPEC1170 compat mode is off. // If we want to be able to run under SPEC1170, we have to do some porting and // testing. if (requested_addr != NULL) { assert(!os::Aix::xpg_sus_mode(), "SPEC1170 mode not allowed."); flags |= MAP_FIXED; } char* addr = (char*)::mmap(requested_addr, size, PROT_READ|PROT_WRITE|PROT_EXEC, flags, -1, 0); if (addr == MAP_FAILED) { // attach failed: tolerate for specific wish addresses. Not being able to attach // anywhere is a fatal error. if (requested_addr == NULL) { // It's ok to fail here if the machine has not enough memory. warning("mmap(NULL, 0x%llX, ..) failed (%d)", size, errno); } addr = NULL; goto cleanup_mmap; } // If we did request a specific address and that address was not available, fail. if (addr && requested_addr) { guarantee(addr == requested_addr, "unexpected"); } // register this mmap'ed segment with book keeping LOCK_SHMBK ShmBkMappedBlock* const p_block = new ShmBkMappedBlock(AddrRange(addr, size)); assert(p_block, ""); shmbk_register(p_block); UNLOCK_SHMBK cleanup_mmap: if (addr) { if (Verbose) { fprintf(stderr, "mmap-allocated 0x%p .. 0x%p (0x%llX bytes)\n", addr, addr + bytes, bytes); } } else { if (requested_addr != NULL) { warning("failed to mmap-allocate 0x%llX bytes at wish address 0x%p.", bytes, requested_addr); } else { warning("failed to mmap-allocate 0x%llX bytes at any address.", bytes); } } return addr; } // end: reserve_mmaped_memory // Reserves and attaches a shared memory segment. // Will assert if a wish address is given and could not be obtained. char* os::pd_reserve_memory(size_t bytes, char* requested_addr, size_t alignment_hint) { return os::attempt_reserve_memory_at(bytes, requested_addr); } bool os::pd_release_memory(char* addr, size_t size) { // delegate to ShmBkBlock class which knows how to uncommit its memory. bool rc = false; LOCK_SHMBK ShmBkBlock* const block = shmbk_find_by_containing_address(addr); if (!block) { fprintf(stderr, "invalid pointer: 0x%p.\n", addr); shmbk_dump_info(); assert(false, "invalid pointer"); return false; } else if (!block->isSameRange(addr, size)) { if (block->getType() == ShmBkBlock::MMAP) { // Release only the same range or a the beginning or the end of a range. if (block->base() == addr && size < block->size()) { ShmBkMappedBlock* const b = new ShmBkMappedBlock(AddrRange(block->base() + size, block->size() - size)); assert(b, ""); shmbk_register(b); block->setAddrRange(AddrRange(addr, size)); } else if (addr > block->base() && addr + size == block->base() + block->size()) { ShmBkMappedBlock* const b = new ShmBkMappedBlock(AddrRange(block->base(), block->size() - size)); assert(b, ""); shmbk_register(b); block->setAddrRange(AddrRange(addr, size)); } else { fprintf(stderr, "invalid mmap range: 0x%p .. 0x%p.\n", addr, addr + size); shmbk_dump_info(); assert(false, "invalid mmap range"); return false; } } else { // Release only the same range. No partial release allowed. // Soften the requirement a bit, because the user may think he owns a smaller size // than the block is due to alignment etc. if (block->base() != addr || block->size() < size) { fprintf(stderr, "invalid shmget range: 0x%p .. 0x%p.\n", addr, addr + size); shmbk_dump_info(); assert(false, "invalid shmget range"); return false; } } } rc = block->release(); assert(rc, "release failed"); // remove block from bookkeeping shmbk_unregister(block); delete block; UNLOCK_SHMBK if (!rc) { warning("failed to released %lu bytes at 0x%p", size, addr); } return rc; } static bool checked_mprotect(char* addr, size_t size, int prot) { // Little problem here: if SPEC1170 behaviour is off, mprotect() on AIX will // not tell me if protection failed when trying to protect an un-protectable range. // // This means if the memory was allocated using shmget/shmat, protection wont work // but mprotect will still return 0: // // See http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf1/mprotect.htm bool rc = ::mprotect(addr, size, prot) == 0 ? true : false; if (!rc) { const char* const s_errno = strerror(errno); warning("mprotect(" PTR_FORMAT "-" PTR_FORMAT ", 0x%X) failed (%s).", addr, addr + size, prot, s_errno); return false; } // mprotect success check // // Mprotect said it changed the protection but can I believe it? // // To be sure I need to check the protection afterwards. Try to // read from protected memory and check whether that causes a segfault. // if (!os::Aix::xpg_sus_mode()) { if (StubRoutines::SafeFetch32_stub()) { const bool read_protected = (SafeFetch32((int*)addr, 0x12345678) == 0x12345678 && SafeFetch32((int*)addr, 0x76543210) == 0x76543210) ? true : false; if (prot & PROT_READ) { rc = !read_protected; } else { rc = read_protected; } } } if (!rc) { assert(false, "mprotect failed."); } return rc; } // Set protections specified bool os::protect_memory(char* addr, size_t size, ProtType prot, bool is_committed) { unsigned int p = 0; switch (prot) { case MEM_PROT_NONE: p = PROT_NONE; break; case MEM_PROT_READ: p = PROT_READ; break; case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; default: ShouldNotReachHere(); } // is_committed is unused. return checked_mprotect(addr, size, p); } bool os::guard_memory(char* addr, size_t size) { return checked_mprotect(addr, size, PROT_NONE); } bool os::unguard_memory(char* addr, size_t size) { return checked_mprotect(addr, size, PROT_READ|PROT_WRITE|PROT_EXEC); } // Large page support static size_t _large_page_size = 0; // Enable large page support if OS allows that. void os::large_page_init() { // Note: os::Aix::query_multipage_support must run first. if (!UseLargePages) { return; } if (!Aix::can_use_64K_pages()) { assert(!Aix::can_use_16M_pages(), "64K is a precondition for 16M."); UseLargePages = false; return; } if (!Aix::can_use_16M_pages() && Use16MPages) { fprintf(stderr, "Cannot use 16M pages. Please ensure that there is a 16M page pool " " and that the VM runs with CAP_BYPASS_RAC_VMM and CAP_PROPAGATE capabilities.\n"); } // Do not report 16M page alignment as part of os::_page_sizes if we are // explicitly forbidden from using 16M pages. Doing so would increase the // alignment the garbage collector calculates with, slightly increasing // heap usage. We should only pay for 16M alignment if we really want to // use 16M pages. if (Use16MPages && Aix::can_use_16M_pages()) { _large_page_size = SIZE_16M; _page_sizes[0] = SIZE_16M; _page_sizes[1] = SIZE_64K; _page_sizes[2] = SIZE_4K; _page_sizes[3] = 0; } else if (Aix::can_use_64K_pages()) { _large_page_size = SIZE_64K; _page_sizes[0] = SIZE_64K; _page_sizes[1] = SIZE_4K; _page_sizes[2] = 0; } if (Verbose) { ("Default large page size is 0x%llX.", _large_page_size); } } // end: os::large_page_init() char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) { // "exec" is passed in but not used. Creating the shared image for // the code cache doesn't have an SHM_X executable permission to check. Unimplemented(); return 0; } bool os::release_memory_special(char* base, size_t bytes) { // detaching the SHM segment will also delete it, see reserve_memory_special() Unimplemented(); return false; } size_t os::large_page_size() { return _large_page_size; } bool os::can_commit_large_page_memory() { // Well, sadly we cannot commit anything at all (see comment in // os::commit_memory) but we claim to so we can make use of large pages return true; } bool os::can_execute_large_page_memory() { // We can do that return true; } // Reserve memory at an arbitrary address, only if that area is // available (and not reserved for something else). char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { bool use_mmap = false; // mmap: smaller graining, no large page support // shm: large graining (256M), large page support, limited number of shm segments // // Prefer mmap wherever we either do not need large page support or have OS limits if (!UseLargePages || bytes < SIZE_16M) { use_mmap = true; } char* addr = NULL; if (use_mmap) { addr = reserve_mmaped_memory(bytes, requested_addr); } else { // shmat: wish address is mandatory, and do not try 16M pages here. shmatted_memory_info_t info; const int flags = RESSHM_WISHADDR_OR_FAIL; if (reserve_shmatted_memory(bytes, requested_addr, flags, &info)) { addr = info.addr; } } return addr; } size_t os::read(int fd, void *buf, unsigned int nBytes) { return ::read(fd, buf, nBytes); } #define NANOSECS_PER_MILLISEC 1000000 int os::sleep(Thread* thread, jlong millis, bool interruptible) { assert(thread == Thread::current(), "thread consistency check"); // Prevent nasty overflow in deadline calculation // by handling long sleeps similar to solaris or windows. const jlong limit = INT_MAX; int result; while (millis > limit) { if ((result = os::sleep(thread, limit, interruptible)) != OS_OK) { return result; } millis -= limit; } ParkEvent * const slp = thread->_SleepEvent; slp->reset(); OrderAccess::fence(); if (interruptible) { jlong prevtime = javaTimeNanos(); // Prevent precision loss and too long sleeps jlong deadline = prevtime + millis * NANOSECS_PER_MILLISEC; for (;;) { if (os::is_interrupted(thread, true)) { return OS_INTRPT; } jlong newtime = javaTimeNanos(); assert(newtime >= prevtime, "time moving backwards"); // Doing prevtime and newtime in microseconds doesn't help precision, // and trying to round up to avoid lost milliseconds can result in a // too-short delay. millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; if (millis <= 0) { return OS_OK; } // Stop sleeping if we passed the deadline if (newtime >= deadline) { return OS_OK; } prevtime = newtime; { assert(thread->is_Java_thread(), "sanity check"); JavaThread *jt = (JavaThread *) thread; ThreadBlockInVM tbivm(jt); OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */); jt->set_suspend_equivalent(); slp->park(millis); // were we externally suspended while we were waiting? jt->check_and_wait_while_suspended(); } } } else { OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); jlong prevtime = javaTimeNanos(); // Prevent precision loss and too long sleeps jlong deadline = prevtime + millis * NANOSECS_PER_MILLISEC; for (;;) { // It'd be nice to avoid the back-to-back javaTimeNanos() calls on // the 1st iteration ... jlong newtime = javaTimeNanos(); if (newtime - prevtime < 0) { // time moving backwards, should only happen if no monotonic clock // not a guarantee() because JVM should not abort on kernel/glibc bugs // - HS14 Commented out as not implemented. // - TODO Maybe we should implement it? //assert(!Aix::supports_monotonic_clock(), "time moving backwards"); } else { millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; } if (millis <= 0) break; if (newtime >= deadline) { break; } prevtime = newtime; slp->park(millis); } return OS_OK; } } int os::naked_sleep() { // %% make the sleep time an integer flag. for now use 1 millisec. return os::sleep(Thread::current(), 1, false); } // Sleep forever; naked call to OS-specific sleep; use with CAUTION void os::infinite_sleep() { while (true) { // sleep forever ... ::sleep(100); // ... 100 seconds at a time } } // Used to convert frequent JVM_Yield() to nops bool os::dont_yield() { return DontYieldALot; } void os::yield() { sched_yield(); } os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; } void os::yield_all(int attempts) { // Yields to all threads, including threads with lower priorities // Threads on Linux are all with same priority. The Solaris style // os::yield_all() with nanosleep(1ms) is not necessary. sched_yield(); } // Called from the tight loops to possibly influence time-sharing heuristics void os::loop_breaker(int attempts) { os::yield_all(attempts); } //////////////////////////////////////////////////////////////////////////////// // thread priority support // From AIX manpage to pthread_setschedparam // (see: http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp? // topic=/com.ibm.aix.basetechref/doc/basetrf1/pthread_setschedparam.htm): // // "If schedpolicy is SCHED_OTHER, then sched_priority must be in the // range from 40 to 80, where 40 is the least favored priority and 80 // is the most favored." // // (Actually, I doubt this even has an impact on AIX, as we do kernel // scheduling there; however, this still leaves iSeries.) // // We use the same values for AIX and PASE. int os::java_to_os_priority[CriticalPriority + 1] = { 54, // 0 Entry should never be used 55, // 1 MinPriority 55, // 2 56, // 3 56, // 4 57, // 5 NormPriority 57, // 6 58, // 7 58, // 8 59, // 9 NearMaxPriority 60, // 10 MaxPriority 60 // 11 CriticalPriority }; OSReturn os::set_native_priority(Thread* thread, int newpri) { if (!UseThreadPriorities) return OS_OK; pthread_t thr = thread->osthread()->pthread_id(); int policy = SCHED_OTHER; struct sched_param param; param.sched_priority = newpri; int ret = pthread_setschedparam(thr, policy, &param); if (Verbose) { if (ret == 0) { fprintf(stderr, "changed priority of thread %d to %d\n", (int)thr, newpri); } else { fprintf(stderr, "Could not changed priority for thread %d to %d (error %d, %s)\n", (int)thr, newpri, ret, strerror(ret)); } } return (ret == 0) ? OS_OK : OS_ERR; } OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { if (!UseThreadPriorities) { *priority_ptr = java_to_os_priority[NormPriority]; return OS_OK; } pthread_t thr = thread->osthread()->pthread_id(); int policy = SCHED_OTHER; struct sched_param param; int ret = pthread_getschedparam(thr, &policy, &param); *priority_ptr = param.sched_priority; return (ret == 0) ? OS_OK : OS_ERR; } // Hint to the underlying OS that a task switch would not be good. // Void return because it's a hint and can fail. void os::hint_no_preempt() {} //////////////////////////////////////////////////////////////////////////////// // suspend/resume support // the low-level signal-based suspend/resume support is a remnant from the // old VM-suspension that used to be for java-suspension, safepoints etc, // within hotspot. Now there is a single use-case for this: // - calling get_thread_pc() on the VMThread by the flat-profiler task // that runs in the watcher thread. // The remaining code is greatly simplified from the more general suspension // code that used to be used. // // The protocol is quite simple: // - suspend: // - sends a signal to the target thread // - polls the suspend state of the osthread using a yield loop // - target thread signal handler (SR_handler) sets suspend state // and blocks in sigsuspend until continued // - resume: // - sets target osthread state to continue // - sends signal to end the sigsuspend loop in the SR_handler // // Note that the SR_lock plays no role in this suspend/resume protocol. // static void resume_clear_context(OSThread *osthread) { osthread->set_ucontext(NULL); osthread->set_siginfo(NULL); } static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) { osthread->set_ucontext(context); osthread->set_siginfo(siginfo); } // // Handler function invoked when a thread's execution is suspended or // resumed. We have to be careful that only async-safe functions are // called here (Note: most pthread functions are not async safe and // should be avoided.) // // Note: sigwait() is a more natural fit than sigsuspend() from an // interface point of view, but sigwait() prevents the signal hander // from being run. libpthread would get very confused by not having // its signal handlers run and prevents sigwait()'s use with the // mutex granting granting signal. // // Currently only ever called on the VMThread and JavaThreads (PC sampling). // static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { // Save and restore errno to avoid confusing native code with EINTR // after sigsuspend. int old_errno = errno; Thread* thread = Thread::current(); OSThread* osthread = thread->osthread(); assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); os::SuspendResume::State current = osthread->sr.state(); if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { suspend_save_context(osthread, siginfo, context); // attempt to switch the state, we assume we had a SUSPEND_REQUEST os::SuspendResume::State state = osthread->sr.suspended(); if (state == os::SuspendResume::SR_SUSPENDED) { sigset_t suspend_set; // signals for sigsuspend() // get current set of blocked signals and unblock resume signal pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); sigdelset(&suspend_set, SR_signum); // wait here until we are resumed while (1) { sigsuspend(&suspend_set); os::SuspendResume::State result = osthread->sr.running(); if (result == os::SuspendResume::SR_RUNNING) { break; } } } else if (state == os::SuspendResume::SR_RUNNING) { // request was cancelled, continue } else { ShouldNotReachHere(); } resume_clear_context(osthread); } else if (current == os::SuspendResume::SR_RUNNING) { // request was cancelled, continue } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { // ignore } else { ShouldNotReachHere(); } errno = old_errno; } static int SR_initialize() { struct sigaction act; char *s; // Get signal number to use for suspend/resume if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { int sig = ::strtol(s, 0, 10); if (sig > 0 || sig < NSIG) { SR_signum = sig; } } assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); sigemptyset(&SR_sigset); sigaddset(&SR_sigset, SR_signum); // Set up signal handler for suspend/resume. act.sa_flags = SA_RESTART|SA_SIGINFO; act.sa_handler = (void (*)(int)) SR_handler; // SR_signum is blocked by default. // 4528190 - We also need to block pthread restart signal (32 on all // supported Linux platforms). Note that LinuxThreads need to block // this signal for all threads to work properly. So we don't have // to use hard-coded signal number when setting up the mask. pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); if (sigaction(SR_signum, &act, 0) == -1) { return -1; } // Save signal flag os::Aix::set_our_sigflags(SR_signum, act.sa_flags); return 0; } static int SR_finalize() { return 0; } static int sr_notify(OSThread* osthread) { int status = pthread_kill(osthread->pthread_id(), SR_signum); assert_status(status == 0, status, "pthread_kill"); return status; } // "Randomly" selected value for how long we want to spin // before bailing out on suspending a thread, also how often // we send a signal to a thread we want to resume static const int RANDOMLY_LARGE_INTEGER = 1000000; static const int RANDOMLY_LARGE_INTEGER2 = 100; // returns true on success and false on error - really an error is fatal // but this seems the normal response to library errors static bool do_suspend(OSThread* osthread) { assert(osthread->sr.is_running(), "thread should be running"); // mark as suspended and send signal if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { // failed to switch, state wasn't running? ShouldNotReachHere(); return false; } if (sr_notify(osthread) != 0) { // try to cancel, switch to running os::SuspendResume::State result = osthread->sr.cancel_suspend(); if (result == os::SuspendResume::SR_RUNNING) { // cancelled return false; } else if (result == os::SuspendResume::SR_SUSPENDED) { // somehow managed to suspend return true; } else { ShouldNotReachHere(); return false; } } // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED for (int n = 0; !osthread->sr.is_suspended(); n++) { for (int i = 0; i < RANDOMLY_LARGE_INTEGER2 && !osthread->sr.is_suspended(); i++) { os::yield_all(i); } // timeout, try to cancel the request if (n >= RANDOMLY_LARGE_INTEGER) { os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); if (cancelled == os::SuspendResume::SR_RUNNING) { return false; } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { return true; } else { ShouldNotReachHere(); return false; } } } guarantee(osthread->sr.is_suspended(), "Must be suspended"); return true; } static void do_resume(OSThread* osthread) { //assert(osthread->sr.is_suspended(), "thread should be suspended"); if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { // failed to switch to WAKEUP_REQUEST ShouldNotReachHere(); return; } while (!osthread->sr.is_running()) { if (sr_notify(osthread) == 0) { for (int n = 0; n < RANDOMLY_LARGE_INTEGER && !osthread->sr.is_running(); n++) { for (int i = 0; i < 100 && !osthread->sr.is_running(); i++) { os::yield_all(i); } } } else { ShouldNotReachHere(); } } guarantee(osthread->sr.is_running(), "Must be running!"); } //////////////////////////////////////////////////////////////////////////////// // interrupt support void os::interrupt(Thread* thread) { assert(Thread::current() == thread || Threads_lock->owned_by_self(), "possibility of dangling Thread pointer"); OSThread* osthread = thread->osthread(); if (!osthread->interrupted()) { osthread->set_interrupted(true); // More than one thread can get here with the same value of osthread, // resulting in multiple notifications. We do, however, want the store // to interrupted() to be visible to other threads before we execute unpark(). OrderAccess::fence(); ParkEvent * const slp = thread->_SleepEvent; if (slp != NULL) slp->unpark(); } // For JSR166. Unpark even if interrupt status already was set if (thread->is_Java_thread()) ((JavaThread*)thread)->parker()->unpark(); ParkEvent * ev = thread->_ParkEvent; if (ev != NULL) ev->unpark(); } bool os::is_interrupted(Thread* thread, bool clear_interrupted) { assert(Thread::current() == thread || Threads_lock->owned_by_self(), "possibility of dangling Thread pointer"); OSThread* osthread = thread->osthread(); bool interrupted = osthread->interrupted(); if (interrupted && clear_interrupted) { osthread->set_interrupted(false); // consider thread->_SleepEvent->reset() ... optional optimization } return interrupted; } /////////////////////////////////////////////////////////////////////////////////// // signal handling (except suspend/resume) // This routine may be used by user applications as a "hook" to catch signals. // The user-defined signal handler must pass unrecognized signals to this // routine, and if it returns true (non-zero), then the signal handler must // return immediately. If the flag "abort_if_unrecognized" is true, then this // routine will never retun false (zero), but instead will execute a VM panic // routine kill the process. // // If this routine returns false, it is OK to call it again. This allows // the user-defined signal handler to perform checks either before or after // the VM performs its own checks. Naturally, the user code would be making // a serious error if it tried to handle an exception (such as a null check // or breakpoint) that the VM was generating for its own correct operation. // // This routine may recognize any of the following kinds of signals: // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. // It should be consulted by handlers for any of those signals. // // The caller of this routine must pass in the three arguments supplied // to the function referred to in the "sa_sigaction" (not the "sa_handler") // field of the structure passed to sigaction(). This routine assumes that // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. // // Note that the VM will print warnings if it detects conflicting signal // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". // extern "C" JNIEXPORT int JVM_handle_aix_signal(int signo, siginfo_t* siginfo, void* ucontext, int abort_if_unrecognized); // Set thread signal mask (for some reason on AIX sigthreadmask() seems // to be the thing to call; documentation is not terribly clear about whether // pthread_sigmask also works, and if it does, whether it does the same. bool set_thread_signal_mask(int how, const sigset_t* set, sigset_t* oset) { const int rc = ::pthread_sigmask(how, set, oset); // return value semantics differ slightly for error case: // pthread_sigmask returns error number, sigthreadmask -1 and sets global errno // (so, pthread_sigmask is more theadsafe for error handling) // But success is always 0. return rc == 0 ? true : false; } // Function to unblock all signals which are, according // to POSIX, typical program error signals. If they happen while being blocked, // they typically will bring down the process immediately. bool unblock_program_error_signals() { sigset_t set; ::sigemptyset(&set); ::sigaddset(&set, SIGILL); ::sigaddset(&set, SIGBUS); ::sigaddset(&set, SIGFPE); ::sigaddset(&set, SIGSEGV); return set_thread_signal_mask(SIG_UNBLOCK, &set, NULL); } // Renamed from 'signalHandler' to avoid collision with other shared libs. void javaSignalHandler(int sig, siginfo_t* info, void* uc) { assert(info != NULL && uc != NULL, "it must be old kernel"); // Never leave program error signals blocked; // on all our platforms they would bring down the process immediately when // getting raised while being blocked. unblock_program_error_signals(); JVM_handle_aix_signal(sig, info, uc, true); } // This boolean allows users to forward their own non-matching signals // to JVM_handle_aix_signal, harmlessly. bool os::Aix::signal_handlers_are_installed = false; // For signal-chaining struct sigaction os::Aix::sigact[MAXSIGNUM]; unsigned int os::Aix::sigs = 0; bool os::Aix::libjsig_is_loaded = false; typedef struct sigaction *(*get_signal_t)(int); get_signal_t os::Aix::get_signal_action = NULL; struct sigaction* os::Aix::get_chained_signal_action(int sig) { struct sigaction *actp = NULL; if (libjsig_is_loaded) { // Retrieve the old signal handler from libjsig actp = (*get_signal_action)(sig); } if (actp == NULL) { // Retrieve the preinstalled signal handler from jvm actp = get_preinstalled_handler(sig); } return actp; } static bool call_chained_handler(struct sigaction *actp, int sig, siginfo_t *siginfo, void *context) { Unimplemented(); return true; } bool os::Aix::chained_handler(int sig, siginfo_t* siginfo, void* context) { bool chained = false; // signal-chaining if (UseSignalChaining) { struct sigaction *actp = get_chained_signal_action(sig); if (actp != NULL) { chained = call_chained_handler(actp, sig, siginfo, context); } } return chained; } struct sigaction* os::Aix::get_preinstalled_handler(int sig) { if ((((unsigned int)1 << sig) & sigs) != 0) { return &sigact[sig]; } return NULL; } void os::Aix::save_preinstalled_handler(int sig, struct sigaction& oldAct) { assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); sigact[sig] = oldAct; sigs |= (unsigned int)1 << sig; } // for diagnostic int os::Aix::sigflags[MAXSIGNUM]; int os::Aix::get_our_sigflags(int sig) { assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); return sigflags[sig]; } void os::Aix::set_our_sigflags(int sig, int flags) { assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); sigflags[sig] = flags; } void os::Aix::set_signal_handler(int sig, bool set_installed) { // Check for overwrite. struct sigaction oldAct; sigaction(sig, (struct sigaction*)NULL, &oldAct); void* oldhand = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); // Renamed 'signalHandler' to avoid collision with other shared libs. if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)javaSignalHandler)) { if (AllowUserSignalHandlers || !set_installed) { // Do not overwrite; user takes responsibility to forward to us. return; } else if (UseSignalChaining) { // save the old handler in jvm save_preinstalled_handler(sig, oldAct); // libjsig also interposes the sigaction() call below and saves the // old sigaction on it own. } else { fatal(err_msg("Encountered unexpected pre-existing sigaction handler " "%#lx for signal %d.", (long)oldhand, sig)); } } struct sigaction sigAct; sigfillset(&(sigAct.sa_mask)); if (!set_installed) { sigAct.sa_handler = SIG_DFL; sigAct.sa_flags = SA_RESTART; } else { // Renamed 'signalHandler' to avoid collision with other shared libs. sigAct.sa_sigaction = javaSignalHandler; sigAct.sa_flags = SA_SIGINFO|SA_RESTART; } // Save flags, which are set by ours assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); sigflags[sig] = sigAct.sa_flags; int ret = sigaction(sig, &sigAct, &oldAct); assert(ret == 0, "check"); void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); assert(oldhand2 == oldhand, "no concurrent signal handler installation"); } // install signal handlers for signals that HotSpot needs to // handle in order to support Java-level exception handling. void os::Aix::install_signal_handlers() { if (!signal_handlers_are_installed) { signal_handlers_are_installed = true; // signal-chaining typedef void (*signal_setting_t)(); signal_setting_t begin_signal_setting = NULL; signal_setting_t end_signal_setting = NULL; begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); if (begin_signal_setting != NULL) { end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); get_signal_action = CAST_TO_FN_PTR(get_signal_t, dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); libjsig_is_loaded = true; assert(UseSignalChaining, "should enable signal-chaining"); } if (libjsig_is_loaded) { // Tell libjsig jvm is setting signal handlers (*begin_signal_setting)(); } set_signal_handler(SIGSEGV, true); set_signal_handler(SIGPIPE, true); set_signal_handler(SIGBUS, true); set_signal_handler(SIGILL, true); set_signal_handler(SIGFPE, true); set_signal_handler(SIGTRAP, true); set_signal_handler(SIGXFSZ, true); set_signal_handler(SIGDANGER, true); if (libjsig_is_loaded) { // Tell libjsig jvm finishes setting signal handlers (*end_signal_setting)(); } // We don't activate signal checker if libjsig is in place, we trust ourselves // and if UserSignalHandler is installed all bets are off. // Log that signal checking is off only if -verbose:jni is specified. if (CheckJNICalls) { if (libjsig_is_loaded) { tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); check_signals = false; } if (AllowUserSignalHandlers) { tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); check_signals = false; } // need to initialize check_signal_done ::sigemptyset(&check_signal_done); } } } static const char* get_signal_handler_name(address handler, char* buf, int buflen) { int offset; bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); if (found) { // skip directory names const char *p1, *p2; p1 = buf; size_t len = strlen(os::file_separator()); while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; // The way os::dll_address_to_library_name is implemented on Aix // right now, it always returns -1 for the offset which is not // terribly informative. // Will fix that. For now, omit the offset. jio_snprintf(buf, buflen, "%s", p1); } else { jio_snprintf(buf, buflen, PTR_FORMAT, handler); } return buf; } static void print_signal_handler(outputStream* st, int sig, char* buf, size_t buflen) { struct sigaction sa; sigaction(sig, NULL, &sa); st->print("%s: ", os::exception_name(sig, buf, buflen)); address handler = (sa.sa_flags & SA_SIGINFO) ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) : CAST_FROM_FN_PTR(address, sa.sa_handler); if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { st->print("SIG_DFL"); } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { st->print("SIG_IGN"); } else { st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); } // Print readable mask. st->print(", sa_mask[0]="); os::Posix::print_signal_set_short(st, &sa.sa_mask); address rh = VMError::get_resetted_sighandler(sig); // May be, handler was resetted by VMError? if (rh != NULL) { handler = rh; sa.sa_flags = VMError::get_resetted_sigflags(sig); } // Print textual representation of sa_flags. st->print(", sa_flags="); os::Posix::print_sa_flags(st, sa.sa_flags); // Check: is it our handler? if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)javaSignalHandler) || handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { // It is our signal handler. // Check for flags, reset system-used one! if ((int)sa.sa_flags != os::Aix::get_our_sigflags(sig)) { st->print(", flags was changed from " PTR32_FORMAT ", consider using jsig library", os::Aix::get_our_sigflags(sig)); } } st->cr(); } #define DO_SIGNAL_CHECK(sig) \ if (!sigismember(&check_signal_done, sig)) \ os::Aix::check_signal_handler(sig) // This method is a periodic task to check for misbehaving JNI applications // under CheckJNI, we can add any periodic checks here void os::run_periodic_checks() { if (check_signals == false) return; // SEGV and BUS if overridden could potentially prevent // generation of hs*.log in the event of a crash, debugging // such a case can be very challenging, so we absolutely // check the following for a good measure: DO_SIGNAL_CHECK(SIGSEGV); DO_SIGNAL_CHECK(SIGILL); DO_SIGNAL_CHECK(SIGFPE); DO_SIGNAL_CHECK(SIGBUS); DO_SIGNAL_CHECK(SIGPIPE); DO_SIGNAL_CHECK(SIGXFSZ); if (UseSIGTRAP) { DO_SIGNAL_CHECK(SIGTRAP); } DO_SIGNAL_CHECK(SIGDANGER); // ReduceSignalUsage allows the user to override these handlers // see comments at the very top and jvm_solaris.h if (!ReduceSignalUsage) { DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); DO_SIGNAL_CHECK(BREAK_SIGNAL); } DO_SIGNAL_CHECK(SR_signum); DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); } typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); static os_sigaction_t os_sigaction = NULL; void os::Aix::check_signal_handler(int sig) { char buf[O_BUFLEN]; address jvmHandler = NULL; struct sigaction act; if (os_sigaction == NULL) { // only trust the default sigaction, in case it has been interposed os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); if (os_sigaction == NULL) return; } os_sigaction(sig, (struct sigaction*)NULL, &act); address thisHandler = (act.sa_flags & SA_SIGINFO) ? CAST_FROM_FN_PTR(address, act.sa_sigaction) : CAST_FROM_FN_PTR(address, act.sa_handler); switch(sig) { case SIGSEGV: case SIGBUS: case SIGFPE: case SIGPIPE: case SIGILL: case SIGXFSZ: // Renamed 'signalHandler' to avoid collision with other shared libs. jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)javaSignalHandler); break; case SHUTDOWN1_SIGNAL: case SHUTDOWN2_SIGNAL: case SHUTDOWN3_SIGNAL: case BREAK_SIGNAL: jvmHandler = (address)user_handler(); break; case INTERRUPT_SIGNAL: jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); break; default: if (sig == SR_signum) { jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); } else { return; } break; } if (thisHandler != jvmHandler) { tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); // No need to check this sig any longer sigaddset(&check_signal_done, sig); } else if (os::Aix::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Aix::get_our_sigflags(sig)) { tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); tty->print("expected:" PTR32_FORMAT, os::Aix::get_our_sigflags(sig)); tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); // No need to check this sig any longer sigaddset(&check_signal_done, sig); } // Dump all the signal if (sigismember(&check_signal_done, sig)) { print_signal_handlers(tty, buf, O_BUFLEN); } } extern bool signal_name(int signo, char* buf, size_t len); const char* os::exception_name(int exception_code, char* buf, size_t size) { if (0 < exception_code && exception_code <= SIGRTMAX) { // signal if (!signal_name(exception_code, buf, size)) { jio_snprintf(buf, size, "SIG%d", exception_code); } return buf; } else { return NULL; } } // To install functions for atexit system call extern "C" { static void perfMemory_exit_helper() { perfMemory_exit(); } } // This is called _before_ the most of global arguments have been parsed. void os::init(void) { // This is basic, we want to know if that ever changes. // (shared memory boundary is supposed to be a 256M aligned) assert(SHMLBA == ((uint64_t)0x10000000ULL)/*256M*/, "unexpected"); // First off, we need to know whether we run on AIX or PASE, and // the OS level we run on. os::Aix::initialize_os_info(); // Scan environment (SPEC1170 behaviour, etc) os::Aix::scan_environment(); // Check which pages are supported by AIX. os::Aix::query_multipage_support(); // Next, we need to initialize libo4 and libperfstat libraries. if (os::Aix::on_pase()) { os::Aix::initialize_libo4(); } else { os::Aix::initialize_libperfstat(); } // Reset the perfstat information provided by ODM. if (os::Aix::on_aix()) { libperfstat::perfstat_reset(); } // Now initialze basic system properties. Note that for some of the values we // need libperfstat etc. os::Aix::initialize_system_info(); // Initialize large page support. if (UseLargePages) { os::large_page_init(); if (!UseLargePages) { // initialize os::_page_sizes _page_sizes[0] = Aix::page_size(); _page_sizes[1] = 0; if (Verbose) { fprintf(stderr, "Large Page initialization failed: setting UseLargePages=0.\n"); } } } else { // initialize os::_page_sizes _page_sizes[0] = Aix::page_size(); _page_sizes[1] = 0; } // debug trace if (Verbose) { fprintf(stderr, "os::vm_page_size 0x%llX\n", os::vm_page_size()); fprintf(stderr, "os::large_page_size 0x%llX\n", os::large_page_size()); fprintf(stderr, "os::_page_sizes = ( "); for (int i = 0; _page_sizes[i]; i ++) { fprintf(stderr, " %s ", describe_pagesize(_page_sizes[i])); } fprintf(stderr, ")\n"); } _initial_pid = getpid(); clock_tics_per_sec = sysconf(_SC_CLK_TCK); init_random(1234567); ThreadCritical::initialize(); // Main_thread points to the aboriginal thread. Aix::_main_thread = pthread_self(); initial_time_count = os::elapsed_counter(); pthread_mutex_init(&dl_mutex, NULL); } // this is called _after_ the global arguments have been parsed jint os::init_2(void) { if (Verbose) { fprintf(stderr, "processor count: %d\n", os::_processor_count); fprintf(stderr, "physical memory: %lu\n", Aix::_physical_memory); } // initially build up the loaded dll map LoadedLibraries::reload(); const int page_size = Aix::page_size(); const int map_size = page_size; address map_address = (address) MAP_FAILED; const int prot = PROT_READ; const int flags = MAP_PRIVATE|MAP_ANONYMOUS; // use optimized addresses for the polling page, // e.g. map it to a special 32-bit address. if (OptimizePollingPageLocation) { // architecture-specific list of address wishes: address address_wishes[] = { // AIX: addresses lower than 0x30000000 don't seem to work on AIX. // PPC64: all address wishes are non-negative 32 bit values where // the lower 16 bits are all zero. we can load these addresses // with a single ppc_lis instruction. (address) 0x30000000, (address) 0x31000000, (address) 0x32000000, (address) 0x33000000, (address) 0x40000000, (address) 0x41000000, (address) 0x42000000, (address) 0x43000000, (address) 0x50000000, (address) 0x51000000, (address) 0x52000000, (address) 0x53000000, (address) 0x60000000, (address) 0x61000000, (address) 0x62000000, (address) 0x63000000 }; int address_wishes_length = sizeof(address_wishes)/sizeof(address); // iterate over the list of address wishes: for (int i=0; i<address_wishes_length; i++) { // try to map with current address wish. // AIX: AIX needs MAP_FIXED if we provide an address and mmap will // fail if the address is already mapped. map_address = (address) ::mmap(address_wishes[i] - (ssize_t)page_size, map_size, prot, flags | MAP_FIXED, -1, 0); if (Verbose) { fprintf(stderr, "SafePoint Polling Page address: %p (wish) => %p\n", address_wishes[i], map_address + (ssize_t)page_size); } if (map_address + (ssize_t)page_size == address_wishes[i]) { // map succeeded and map_address is at wished address, exit loop. break; } if (map_address != (address) MAP_FAILED) { // map succeeded, but polling_page is not at wished address, unmap and continue. ::munmap(map_address, map_size); map_address = (address) MAP_FAILED; } // map failed, continue loop. } } // end OptimizePollingPageLocation if (map_address == (address) MAP_FAILED) { map_address = (address) ::mmap(NULL, map_size, prot, flags, -1, 0); } guarantee(map_address != MAP_FAILED, "os::init_2: failed to allocate polling page"); os::set_polling_page(map_address); if (!UseMembar) { address mem_serialize_page = (address) ::mmap(NULL, Aix::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); guarantee(mem_serialize_page != NULL, "mmap Failed for memory serialize page"); os::set_memory_serialize_page(mem_serialize_page); #ifndef PRODUCT if (Verbose && PrintMiscellaneous) tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); #endif } // initialize suspend/resume support - must do this before signal_sets_init() if (SR_initialize() != 0) { perror("SR_initialize failed"); return JNI_ERR; } Aix::signal_sets_init(); Aix::install_signal_handlers(); // Check minimum allowable stack size for thread creation and to initialize // the java system classes, including StackOverflowError - depends on page // size. Add a page for compiler2 recursion in main thread. // Add in 2*BytesPerWord times page size to account for VM stack during // class initialization depending on 32 or 64 bit VM. os::Aix::min_stack_allowed = MAX2(os::Aix::min_stack_allowed, (size_t)(StackYellowPages+StackRedPages+StackShadowPages + 2*BytesPerWord COMPILER2_PRESENT(+1)) * Aix::page_size()); size_t threadStackSizeInBytes = ThreadStackSize * K; if (threadStackSizeInBytes != 0 && threadStackSizeInBytes < os::Aix::min_stack_allowed) { tty->print_cr("\nThe stack size specified is too small, " "Specify at least %dk", os::Aix::min_stack_allowed / K); return JNI_ERR; } // Make the stack size a multiple of the page size so that // the yellow/red zones can be guarded. // note that this can be 0, if no default stacksize was set JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, vm_page_size())); Aix::libpthread_init(); if (MaxFDLimit) { // set the number of file descriptors to max. print out error // if getrlimit/setrlimit fails but continue regardless. struct rlimit nbr_files; int status = getrlimit(RLIMIT_NOFILE, &nbr_files); if (status != 0) { if (PrintMiscellaneous && (Verbose || WizardMode)) perror("os::init_2 getrlimit failed"); } else { nbr_files.rlim_cur = nbr_files.rlim_max; status = setrlimit(RLIMIT_NOFILE, &nbr_files); if (status != 0) { if (PrintMiscellaneous && (Verbose || WizardMode)) perror("os::init_2 setrlimit failed"); } } } if (PerfAllowAtExitRegistration) { // only register atexit functions if PerfAllowAtExitRegistration is set. // atexit functions can be delayed until process exit time, which // can be problematic for embedded VM situations. Embedded VMs should // call DestroyJavaVM() to assure that VM resources are released. // note: perfMemory_exit_helper atexit function may be removed in // the future if the appropriate cleanup code can be added to the // VM_Exit VMOperation's doit method. if (atexit(perfMemory_exit_helper) != 0) { warning("os::init_2 atexit(perfMemory_exit_helper) failed"); } } return JNI_OK; } // this is called at the end of vm_initialization void os::init_3(void) { return; } // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { if (!guard_memory((char*)_polling_page, Aix::page_size())) { fatal("Could not disable polling page"); } }; // Mark the polling page as readable void os::make_polling_page_readable(void) { // Changed according to os_linux.cpp. if (!checked_mprotect((char *)_polling_page, Aix::page_size(), PROT_READ)) { fatal(err_msg("Could not enable polling page at " PTR_FORMAT, _polling_page)); } }; int os::active_processor_count() { int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN); assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check"); return online_cpus; } void os::set_native_thread_name(const char *name) { // Not yet implemented. return; } bool os::distribute_processes(uint length, uint* distribution) { // Not yet implemented. return false; } bool os::bind_to_processor(uint processor_id) { // Not yet implemented. return false; } void os::SuspendedThreadTask::internal_do_task() { if (do_suspend(_thread->osthread())) { SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); do_task(context); do_resume(_thread->osthread()); } } class PcFetcher : public os::SuspendedThreadTask { public: PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {} ExtendedPC result(); protected: void do_task(const os::SuspendedThreadTaskContext& context); private: ExtendedPC _epc; }; ExtendedPC PcFetcher::result() { guarantee(is_done(), "task is not done yet."); return _epc; } void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) { Thread* thread = context.thread(); OSThread* osthread = thread->osthread(); if (osthread->ucontext() != NULL) { _epc = os::Aix::ucontext_get_pc((ucontext_t *) context.ucontext()); } else { // NULL context is unexpected, double-check this is the VMThread. guarantee(thread->is_VM_thread(), "can only be called for VMThread"); } } // Suspends the target using the signal mechanism and then grabs the PC before // resuming the target. Used by the flat-profiler only ExtendedPC os::get_thread_pc(Thread* thread) { // Make sure that it is called by the watcher for the VMThread. assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); assert(thread->is_VM_thread(), "Can only be called for VMThread"); PcFetcher fetcher(thread); fetcher.run(); return fetcher.result(); } // Not neede on Aix. // int os::Aix::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime) { // } //////////////////////////////////////////////////////////////////////////////// // debug support static address same_page(address x, address y) { intptr_t page_bits = -os::vm_page_size(); if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits)) return x; else if (x > y) return (address)(intptr_t(y) | ~page_bits) + 1; else return (address)(intptr_t(y) & page_bits); } bool os::find(address addr, outputStream* st) { Unimplemented(); return false; } //////////////////////////////////////////////////////////////////////////////// // misc // This does not do anything on Aix. This is basically a hook for being // able to use structured exception handling (thread-local exception filters) // on, e.g., Win32. void os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, JavaCallArguments* args, Thread* thread) { f(value, method, args, thread); } void os::print_statistics() { } int os::message_box(const char* title, const char* message) { int i; fdStream err(defaultStream::error_fd()); for (i = 0; i < 78; i++) err.print_raw("="); err.cr(); err.print_raw_cr(title); for (i = 0; i < 78; i++) err.print_raw("-"); err.cr(); err.print_raw_cr(message); for (i = 0; i < 78; i++) err.print_raw("="); err.cr(); char buf[16]; // Prevent process from exiting upon "read error" without consuming all CPU while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } return buf[0] == 'y' || buf[0] == 'Y'; } int os::stat(const char *path, struct stat *sbuf) { char pathbuf[MAX_PATH]; if (strlen(path) > MAX_PATH - 1) { errno = ENAMETOOLONG; return -1; } os::native_path(strcpy(pathbuf, path)); return ::stat(pathbuf, sbuf); } bool os::check_heap(bool force) { return true; } // int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) { // return ::vsnprintf(buf, count, format, args); // } // Is a (classpath) directory empty? bool os::dir_is_empty(const char* path) { Unimplemented(); return false; } // This code originates from JDK's sysOpen and open64_w // from src/solaris/hpi/src/system_md.c #ifndef O_DELETE #define O_DELETE 0x10000 #endif // Open a file. Unlink the file immediately after open returns // if the specified oflag has the O_DELETE flag set. // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c int os::open(const char *path, int oflag, int mode) { if (strlen(path) > MAX_PATH - 1) { errno = ENAMETOOLONG; return -1; } int fd; int o_delete = (oflag & O_DELETE); oflag = oflag & ~O_DELETE; fd = ::open64(path, oflag, mode); if (fd == -1) return -1; //If the open succeeded, the file might still be a directory { struct stat64 buf64; int ret = ::fstat64(fd, &buf64); int st_mode = buf64.st_mode; if (ret != -1) { if ((st_mode & S_IFMT) == S_IFDIR) { errno = EISDIR; ::close(fd); return -1; } } else { ::close(fd); return -1; } } // All file descriptors that are opened in the JVM and not // specifically destined for a subprocess should have the // close-on-exec flag set. If we don't set it, then careless 3rd // party native code might fork and exec without closing all // appropriate file descriptors (e.g. as we do in closeDescriptors in // UNIXProcess.c), and this in turn might: // // - cause end-of-file to fail to be detected on some file // descriptors, resulting in mysterious hangs, or // // - might cause an fopen in the subprocess to fail on a system // suffering from bug 1085341. // // (Yes, the default setting of the close-on-exec flag is a Unix // design flaw.) // // See: // 1085341: 32-bit stdio routines should support file descriptors >255 // 4843136: (process) pipe file descriptor from Runtime.exec not being closed // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 #ifdef FD_CLOEXEC { int flags = ::fcntl(fd, F_GETFD); if (flags != -1) ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); } #endif if (o_delete != 0) { ::unlink(path); } return fd; } // create binary file, rewriting existing file if required int os::create_binary_file(const char* path, bool rewrite_existing) { Unimplemented(); return 0; } // return current position of file pointer jlong os::current_file_offset(int fd) { return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR); } // move file pointer to the specified offset jlong os::seek_to_file_offset(int fd, jlong offset) { return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET); } // This code originates from JDK's sysAvailable // from src/solaris/hpi/src/native_threads/src/sys_api_td.c int os::available(int fd, jlong *bytes) { jlong cur, end; int mode; struct stat64 buf64; if (::fstat64(fd, &buf64) >= 0) { mode = buf64.st_mode; if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { // XXX: is the following call interruptible? If so, this might // need to go through the INTERRUPT_IO() wrapper as for other // blocking, interruptible calls in this file. int n; if (::ioctl(fd, FIONREAD, &n) >= 0) { *bytes = n; return 1; } } } if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) { return 0; } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) { return 0; } else if (::lseek64(fd, cur, SEEK_SET) == -1) { return 0; } *bytes = end - cur; return 1; } int os::socket_available(int fd, jint *pbytes) { // Linux doc says EINTR not returned, unlike Solaris int ret = ::ioctl(fd, FIONREAD, pbytes); //%% note ioctl can return 0 when successful, JVM_SocketAvailable // is expected to return 0 on failure and 1 on success to the jdk. return (ret < 0) ? 0 : 1; } // Map a block of memory. char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, char *addr, size_t bytes, bool read_only, bool allow_exec) { Unimplemented(); return NULL; } // Remap a block of memory. char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, char *addr, size_t bytes, bool read_only, bool allow_exec) { // same as map_memory() on this OS return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec); } // Unmap a block of memory. bool os::pd_unmap_memory(char* addr, size_t bytes) { return munmap(addr, bytes) == 0; } // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) // are used by JVM M&M and JVMTI to get user+sys or user CPU time // of a thread. // // current_thread_cpu_time() and thread_cpu_time(Thread*) returns // the fast estimate available on the platform. jlong os::current_thread_cpu_time() { // return user + sys since the cost is the same const jlong n = os::thread_cpu_time(Thread::current(), true /* user + sys */); assert(n >= 0, "negative CPU time"); return n; } jlong os::thread_cpu_time(Thread* thread) { // consistent with what current_thread_cpu_time() returns const jlong n = os::thread_cpu_time(thread, true /* user + sys */); assert(n >= 0, "negative CPU time"); return n; } jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { const jlong n = os::thread_cpu_time(Thread::current(), user_sys_cpu_time); assert(n >= 0, "negative CPU time"); return n; } static bool thread_cpu_time_unchecked(Thread* thread, jlong* p_sys_time, jlong* p_user_time) { bool error = false; jlong sys_time = 0; jlong user_time = 0; // reimplemented using getthrds64(). // // goes like this: // For the thread in question, get the kernel thread id. Then get the // kernel thread statistics using that id. // // This only works of course when no pthread scheduling is used, // ie there is a 1:1 relationship to kernel threads. // On AIX, see AIXTHREAD_SCOPE variable. pthread_t pthtid = thread->osthread()->pthread_id(); // retrieve kernel thread id for the pthread: tid64_t tid = 0; struct __pthrdsinfo pinfo; // I just love those otherworldly IBM APIs which force me to hand down // dummy buffers for stuff I dont care for... char dummy[1]; int dummy_size = sizeof(dummy); if (pthread_getthrds_np(&pthtid, PTHRDSINFO_QUERY_TID, &pinfo, sizeof(pinfo), dummy, &dummy_size) == 0) { tid = pinfo.__pi_tid; } else { tty->print_cr("pthread_getthrds_np failed."); error = true; } // retrieve kernel timing info for that kernel thread if (!error) { struct thrdentry64 thrdentry; if (getthrds64(getpid(), &thrdentry, sizeof(thrdentry), &tid, 1) == 1) { sys_time = thrdentry.ti_ru.ru_stime.tv_sec * 1000000000LL + thrdentry.ti_ru.ru_stime.tv_usec * 1000LL; user_time = thrdentry.ti_ru.ru_utime.tv_sec * 1000000000LL + thrdentry.ti_ru.ru_utime.tv_usec * 1000LL; } else { tty->print_cr("pthread_getthrds_np failed."); error = true; } } if (p_sys_time) { *p_sys_time = sys_time; } if (p_user_time) { *p_user_time = user_time; } if (error) { return false; } return true; } jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { jlong sys_time; jlong user_time; if (!thread_cpu_time_unchecked(thread, &sys_time, &user_time)) { return -1; } return user_sys_cpu_time ? sys_time + user_time : user_time; } void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits info_ptr->may_skip_backward = false; // elapsed time not wall time info_ptr->may_skip_forward = false; // elapsed time not wall time info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned } void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits info_ptr->may_skip_backward = false; // elapsed time not wall time info_ptr->may_skip_forward = false; // elapsed time not wall time info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned } bool os::is_thread_cpu_time_supported() { return true; } // System loadavg support. Returns -1 if load average cannot be obtained. // For now just return the system wide load average (no processor sets). int os::loadavg(double values[], int nelem) { // Implemented using libperfstat on AIX. guarantee(nelem >= 0 && nelem <= 3, "argument error"); guarantee(values, "argument error"); if (os::Aix::on_pase()) { Unimplemented(); return -1; } else { // AIX: use libperfstat // // See also: // http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf1/perfstat_cputot.htm // /usr/include/libperfstat.h: // Use the already AIX version independent get_cpuinfo. os::Aix::cpuinfo_t ci; if (os::Aix::get_cpuinfo(&ci)) { for (int i = 0; i < nelem; i++) { values[i] = ci.loadavg[i]; } } else { return -1; } return nelem; } } void os::pause() { char filename[MAX_PATH]; if (PauseAtStartupFile && PauseAtStartupFile[0]) { jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); } else { jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); } int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd != -1) { struct stat buf; ::close(fd); while (::stat(filename, &buf) == 0) { (void)::poll(NULL, 0, 100); } } else { jio_fprintf(stderr, "Could not open pause file '%s', continuing immediately.\n", filename); } } bool os::Aix::is_primordial_thread() { if (pthread_self() == (pthread_t)1) { return true; } else { return false; } } // OS recognitions (PASE/AIX, OS level) call this before calling any // one of Aix::on_pase(), Aix::os_version() static void os::Aix::initialize_os_info() { assert(_on_pase == -1 && _os_version == -1, "already called."); struct utsname uts; memset(&uts, 0, sizeof(uts)); strcpy(uts.sysname, "?"); if (::uname(&uts) == -1) { fprintf(stderr, "uname failed (%d)\n", errno); guarantee(0, "Could not determine whether we run on AIX or PASE"); } else { if (Verbose) { fprintf(stderr,"uname says: sysname \"%s\" version \"%s\" release \"%s\" " "node \"%s\" machine \"%s\"\n", uts.sysname, uts.version, uts.release, uts.nodename, uts.machine); } const int major = atoi(uts.version); assert(major > 0, "invalid OS version"); const int minor = atoi(uts.release); assert(minor > 0, "invalid OS release"); _os_version = (major << 8) | minor; if (strcmp(uts.sysname, "OS400") == 0) { Unimplemented(); } else if (strcmp(uts.sysname, "AIX") == 0) { // We run on AIX. We do not support versions older than AIX 5.3. _on_pase = 0; if (_os_version < 0x0503) { fprintf(stderr, "AIX release older than AIX 5.3 not supported.\n"); assert(false, "AIX release too old."); } else { if (Verbose) { fprintf(stderr, "We run on AIX %d.%d\n", major, minor); } } } else { assert(false, "unknown OS"); } } guarantee(_on_pase != -1 && _os_version, "Could not determine AIX/OS400 release"); } // end: os::Aix::initialize_os_info() // Scan environment for important settings which might effect the VM. // Trace out settings. Warn about invalid settings and/or correct them. // // Must run after os::Aix::initialue_os_info(). void os::Aix::scan_environment() { char* p; int rc; // Warn explicity if EXTSHM=ON is used. That switch changes how // System V shared memory behaves. One effect is that page size of // shared memory cannot be change dynamically, effectivly preventing // large pages from working. // This switch was needed on AIX 32bit, but on AIX 64bit the general // recommendation is (in OSS notes) to switch it off. p = ::getenv("EXTSHM"); if (Verbose) { fprintf(stderr, "EXTSHM=%s.\n", p ? p : "<unset>"); } if (p && strcmp(p, "ON") == 0) { fprintf(stderr, "Unsupported setting: EXTSHM=ON. Large Page support will be disabled.\n"); _extshm = 1; } else { _extshm = 0; } // SPEC1170 behaviour: will change the behaviour of a number of POSIX APIs. // Not tested, not supported. // // Note that it might be worth the trouble to test and to require it, if only to // get useful return codes for mprotect. // // Note: Setting XPG_SUS_ENV in the process is too late. Must be set earlier (before // exec() ? before loading the libjvm ? ....) p = ::getenv("XPG_SUS_ENV"); if (Verbose) { fprintf(stderr, "XPG_SUS_ENV=%s.\n", p ? p : "<unset>"); } if (p && strcmp(p, "ON") == 0) { _xpg_sus_mode = 1; fprintf(stderr, "Unsupported setting: XPG_SUS_ENV=ON\n"); // This is not supported. Worst of all, it changes behaviour of mmap MAP_FIXED to // clobber address ranges. If we ever want to support that, we have to do some // testing first. guarantee(false, "XPG_SUS_ENV=ON not supported"); } else { _xpg_sus_mode = 0; } // Switch off AIX internal (pthread) guard pages. This has // immediate effect for any pthread_create calls which follow. p = ::getenv("AIXTHREAD_GUARDPAGES"); if (Verbose) { fprintf(stderr, "AIXTHREAD_GUARDPAGES=%s.\n", p ? p : "<unset>"); fprintf(stderr, "setting AIXTHREAD_GUARDPAGES=0.\n"); } rc = ::putenv("AIXTHREAD_GUARDPAGES=0"); guarantee(rc == 0, ""); } // end: os::Aix::scan_environment() // PASE: initialize the libo4 library (AS400 PASE porting library). void os::Aix::initialize_libo4() { Unimplemented(); } // AIX: initialize the libperfstat library (we load this dynamically // because it is only available on AIX. void os::Aix::initialize_libperfstat() { assert(os::Aix::on_aix(), "AIX only"); if (!libperfstat::init()) { fprintf(stderr, "libperfstat initialization failed.\n"); assert(false, "libperfstat initialization failed"); } else { if (Verbose) { fprintf(stderr, "libperfstat initialized.\n"); } } } // end: os::Aix::initialize_libperfstat ///////////////////////////////////////////////////////////////////////////// // thread stack // function to query the current stack size using pthread_getthrds_np // // ! do not change anything here unless you know what you are doing ! static void query_stack_dimensions(address* p_stack_base, size_t* p_stack_size) { // This only works when invoked on a pthread. As we agreed not to use // primordial threads anyway, I assert here guarantee(!os::Aix::is_primordial_thread(), "not allowed on the primordial thread"); // information about this api can be found (a) in the pthread.h header and // (b) in http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf1/pthread_getthrds_np.htm // // The use of this API to find out the current stack is kind of undefined. // But after a lot of tries and asking IBM about it, I concluded that it is safe // enough for cases where I let the pthread library create its stacks. For cases // where I create an own stack and pass this to pthread_create, it seems not to // work (the returned stack size in that case is 0). pthread_t tid = pthread_self(); struct __pthrdsinfo pinfo; char dummy[1]; // we only need this to satisfy the api and to not get E int dummy_size = sizeof(dummy); memset(&pinfo, 0, sizeof(pinfo)); const int rc = pthread_getthrds_np (&tid, PTHRDSINFO_QUERY_ALL, &pinfo, sizeof(pinfo), dummy, &dummy_size); if (rc != 0) { fprintf(stderr, "pthread_getthrds_np failed (%d)\n", rc); guarantee(0, "pthread_getthrds_np failed"); } guarantee(pinfo.__pi_stackend, "returned stack base invalid"); // the following can happen when invoking pthread_getthrds_np on a pthread running on a user provided stack // (when handing down a stack to pthread create, see pthread_attr_setstackaddr). // Not sure what to do here - I feel inclined to forbid this use case completely. guarantee(pinfo.__pi_stacksize, "returned stack size invalid"); // On AIX, stacks are not necessarily page aligned so round the base and size accordingly if (p_stack_base) { (*p_stack_base) = (address) align_size_up((intptr_t)pinfo.__pi_stackend, os::Aix::stack_page_size()); } if (p_stack_size) { (*p_stack_size) = pinfo.__pi_stacksize - os::Aix::stack_page_size(); } #ifndef PRODUCT if (Verbose) { fprintf(stderr, "query_stack_dimensions() -> real stack_base=" INTPTR_FORMAT ", real stack_addr=" INTPTR_FORMAT ", real stack_size=" INTPTR_FORMAT ", stack_base=" INTPTR_FORMAT ", stack_size=" INTPTR_FORMAT "\n", (intptr_t)pinfo.__pi_stackend, (intptr_t)pinfo.__pi_stackaddr, pinfo.__pi_stacksize, (intptr_t)align_size_up((intptr_t)pinfo.__pi_stackend, os::Aix::stack_page_size()), pinfo.__pi_stacksize - os::Aix::stack_page_size()); } #endif } // end query_stack_dimensions // get the current stack base from the OS (actually, the pthread library) address os::current_stack_base() { address p; query_stack_dimensions(&p, 0); return p; } // get the current stack size from the OS (actually, the pthread library) size_t os::current_stack_size() { size_t s; query_stack_dimensions(0, &s); return s; } // Refer to the comments in os_solaris.cpp park-unpark. // // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. // For specifics regarding the bug see GLIBC BUGID 261237 : // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar // is used. (The simple C test-case provided in the GLIBC bug report manifests the // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() // and monitorenter when we're using 1-0 locking. All those operations may result in // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version // of libpthread avoids the problem, but isn't practical. // // Possible remedies: // // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. // This is palliative and probabilistic, however. If the thread is preempted // between the call to compute_abstime() and pthread_cond_timedwait(), more // than the minimum period may have passed, and the abstime may be stale (in the // past) resultin in a hang. Using this technique reduces the odds of a hang // but the JVM is still vulnerable, particularly on heavily loaded systems. // // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead // of the usual flag-condvar-mutex idiom. The write side of the pipe is set // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) // reduces to poll()+read(). This works well, but consumes 2 FDs per extant // thread. // // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing // a timeout request to the chron thread and then blocking via pthread_cond_wait(). // This also works well. In fact it avoids kernel-level scalability impediments // on certain platforms that don't handle lots of active pthread_cond_timedwait() // timers in a graceful fashion. // // 4. When the abstime value is in the past it appears that control returns // correctly from pthread_cond_timedwait(), but the condvar is left corrupt. // Subsequent timedwait/wait calls may hang indefinitely. Given that, we // can avoid the problem by reinitializing the condvar -- by cond_destroy() // followed by cond_init() -- after all calls to pthread_cond_timedwait(). // It may be possible to avoid reinitialization by checking the return // value from pthread_cond_timedwait(). In addition to reinitializing the // condvar we must establish the invariant that cond_signal() is only called // within critical sections protected by the adjunct mutex. This prevents // cond_signal() from "seeing" a condvar that's in the midst of being // reinitialized or that is corrupt. Sadly, this invariant obviates the // desirable signal-after-unlock optimization that avoids futile context switching. // // I'm also concerned that some versions of NTPL might allocate an auxilliary // structure when a condvar is used or initialized. cond_destroy() would // release the helper structure. Our reinitialize-after-timedwait fix // put excessive stress on malloc/free and locks protecting the c-heap. // // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. // It may be possible to refine (4) by checking the kernel and NTPL verisons // and only enabling the work-around for vulnerable environments. // utility to compute the abstime argument to timedwait: // millis is the relative timeout time // abstime will be the absolute timeout time // TODO: replace compute_abstime() with unpackTime() static struct timespec* compute_abstime(timespec* abstime, jlong millis) { if (millis < 0) millis = 0; struct timeval now; int status = gettimeofday(&now, NULL); assert(status == 0, "gettimeofday"); jlong seconds = millis / 1000; millis %= 1000; if (seconds > 50000000) { // see man cond_timedwait(3T) seconds = 50000000; } abstime->tv_sec = now.tv_sec + seconds; long usec = now.tv_usec + millis * 1000; if (usec >= 1000000) { abstime->tv_sec += 1; usec -= 1000000; } abstime->tv_nsec = usec * 1000; return abstime; } // Test-and-clear _Event, always leaves _Event set to 0, returns immediately. // Conceptually TryPark() should be equivalent to park(0). int os::PlatformEvent::TryPark() { for (;;) { const int v = _Event; guarantee ((v == 0) || (v == 1), "invariant"); if (Atomic::cmpxchg (0, &_Event, v) == v) return v; } } void os::PlatformEvent::park() { // AKA "down()" // Invariant: Only the thread associated with the Event/PlatformEvent // may call park(). // TODO: assert that _Assoc != NULL or _Assoc == Self int v; for (;;) { v = _Event; if (Atomic::cmpxchg (v-1, &_Event, v) == v) break; } guarantee (v >= 0, "invariant"); if (v == 0) { // Do this the hard way by blocking ... int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); guarantee (_nParked == 0, "invariant"); ++ _nParked; while (_Event < 0) { status = pthread_cond_wait(_cond, _mutex); assert_status(status == 0 || status == ETIMEDOUT, status, "cond_timedwait"); } -- _nParked; // In theory we could move the ST of 0 into _Event past the unlock(), // but then we'd need a MEMBAR after the ST. _Event = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); } guarantee (_Event >= 0, "invariant"); } int os::PlatformEvent::park(jlong millis) { guarantee (_nParked == 0, "invariant"); int v; for (;;) { v = _Event; if (Atomic::cmpxchg (v-1, &_Event, v) == v) break; } guarantee (v >= 0, "invariant"); if (v != 0) return OS_OK; // We do this the hard way, by blocking the thread. // Consider enforcing a minimum timeout value. struct timespec abst; compute_abstime(&abst, millis); int ret = OS_TIMEOUT; int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); guarantee (_nParked == 0, "invariant"); ++_nParked; // Object.wait(timo) will return because of // (a) notification // (b) timeout // (c) thread.interrupt // // Thread.interrupt and object.notify{All} both call Event::set. // That is, we treat thread.interrupt as a special case of notification. // The underlying Solaris implementation, cond_timedwait, admits // spurious/premature wakeups, but the JLS/JVM spec prevents the // JVM from making those visible to Java code. As such, we must // filter out spurious wakeups. We assume all ETIME returns are valid. // // TODO: properly differentiate simultaneous notify+interrupt. // In that case, we should propagate the notify to another waiter. while (_Event < 0) { status = pthread_cond_timedwait(_cond, _mutex, &abst); assert_status(status == 0 || status == ETIMEDOUT, status, "cond_timedwait"); if (!FilterSpuriousWakeups) break; // previous semantics if (status == ETIMEDOUT) break; // We consume and ignore EINTR and spurious wakeups. } --_nParked; if (_Event >= 0) { ret = OS_OK; } _Event = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); assert (_nParked == 0, "invariant"); return ret; } void os::PlatformEvent::unpark() { int v, AnyWaiters; for (;;) { v = _Event; if (v > 0) { // The LD of _Event could have reordered or be satisfied // by a read-aside from this processor's write buffer. // To avoid problems execute a barrier and then // ratify the value. OrderAccess::fence(); if (_Event == v) return; continue; } if (Atomic::cmpxchg (v+1, &_Event, v) == v) break; } if (v < 0) { // Wait for the thread associated with the event to vacate int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); AnyWaiters = _nParked; if (AnyWaiters != 0) { // We intentional signal *after* dropping the lock // to avoid a common class of futile wakeups. status = pthread_cond_signal(_cond); assert_status(status == 0, status, "cond_signal"); } // Mutex should be locked for pthread_cond_signal(_cond). status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); } // Note that we signal() _after dropping the lock for "immortal" Events. // This is safe and avoids a common class of futile wakeups. In rare // circumstances this can cause a thread to return prematurely from // cond_{timed}wait() but the spurious wakeup is benign and the victim will // simply re-test the condition and re-park itself. } // JSR166 // ------------------------------------------------------- // // The solaris and linux implementations of park/unpark are fairly // conservative for now, but can be improved. They currently use a // mutex/condvar pair, plus a a count. // Park decrements count if > 0, else does a condvar wait. Unpark // sets count to 1 and signals condvar. Only one thread ever waits // on the condvar. Contention seen when trying to park implies that someone // is unparking you, so don't wait. And spurious returns are fine, so there // is no need to track notifications. // #define MAX_SECS 100000000 // // This code is common to linux and solaris and will be moved to a // common place in dolphin. // // The passed in time value is either a relative time in nanoseconds // or an absolute time in milliseconds. Either way it has to be unpacked // into suitable seconds and nanoseconds components and stored in the // given timespec structure. // Given time is a 64-bit value and the time_t used in the timespec is only // a signed-32-bit value (except on 64-bit Linux) we have to watch for // overflow if times way in the future are given. Further on Solaris versions // prior to 10 there is a restriction (see cond_timedwait) that the specified // number of seconds, in abstime, is less than current_time + 100,000,000. // As it will be 28 years before "now + 100000000" will overflow we can // ignore overflow and just impose a hard-limit on seconds using the value // of "now + 100,000,000". This places a limit on the timeout of about 3.17 // years from "now". // static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { assert (time > 0, "convertTime"); struct timeval now; int status = gettimeofday(&now, NULL); assert(status == 0, "gettimeofday"); time_t max_secs = now.tv_sec + MAX_SECS; if (isAbsolute) { jlong secs = time / 1000; if (secs > max_secs) { absTime->tv_sec = max_secs; } else { absTime->tv_sec = secs; } absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; } else { jlong secs = time / NANOSECS_PER_SEC; if (secs >= MAX_SECS) { absTime->tv_sec = max_secs; absTime->tv_nsec = 0; } else { absTime->tv_sec = now.tv_sec + secs; absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; if (absTime->tv_nsec >= NANOSECS_PER_SEC) { absTime->tv_nsec -= NANOSECS_PER_SEC; ++absTime->tv_sec; // note: this must be <= max_secs } } } assert(absTime->tv_sec >= 0, "tv_sec < 0"); assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); } void Parker::park(bool isAbsolute, jlong time) { // Optional fast-path check: // Return immediately if a permit is available. if (_counter > 0) { _counter = 0; OrderAccess::fence(); return; } Thread* thread = Thread::current(); assert(thread->is_Java_thread(), "Must be JavaThread"); JavaThread *jt = (JavaThread *)thread; // Optional optimization -- avoid state transitions if there's an interrupt pending. // Check interrupt before trying to wait if (Thread::is_interrupted(thread, false)) { return; } // Next, demultiplex/decode time arguments timespec absTime; if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all return; } if (time > 0) { unpackTime(&absTime, isAbsolute, time); } // Enter safepoint region // Beware of deadlocks such as 6317397. // The per-thread Parker:: mutex is a classic leaf-lock. // In particular a thread must never block on the Threads_lock while // holding the Parker:: mutex. If safepoints are pending both the // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. ThreadBlockInVM tbivm(jt); // Don't wait if cannot get lock since interference arises from // unblocking. Also. check interrupt before trying wait if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { return; } int status; if (_counter > 0) { // no wait needed _counter = 0; status = pthread_mutex_unlock(_mutex); assert (status == 0, "invariant"); OrderAccess::fence(); return; } #ifdef ASSERT // Don't catch signals while blocked; let the running threads have the signals. // (This allows a debugger to break into the running thread.) sigset_t oldsigs; sigset_t* allowdebug_blocked = os::Aix::allowdebug_blocked_signals(); pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); #endif OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); jt->set_suspend_equivalent(); // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() if (time == 0) { status = pthread_cond_wait (_cond, _mutex); } else { status = pthread_cond_timedwait (_cond, _mutex, &absTime); if (status != 0 && WorkAroundNPTLTimedWaitHang) { pthread_cond_destroy (_cond); pthread_cond_init (_cond, NULL); } } assert_status(status == 0 || status == EINTR || status == ETIME || status == ETIMEDOUT, status, "cond_timedwait"); #ifdef ASSERT pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); #endif _counter = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "invariant"); // If externally suspended while waiting, re-suspend if (jt->handle_special_suspend_equivalent_condition()) { jt->java_suspend_self(); } OrderAccess::fence(); } void Parker::unpark() { int s, status; status = pthread_mutex_lock(_mutex); assert (status == 0, "invariant"); s = _counter; _counter = 1; if (s < 1) { if (WorkAroundNPTLTimedWaitHang) { status = pthread_cond_signal (_cond); assert (status == 0, "invariant"); status = pthread_mutex_unlock(_mutex); assert (status == 0, "invariant"); } else { status = pthread_mutex_unlock(_mutex); assert (status == 0, "invariant"); status = pthread_cond_signal (_cond); assert (status == 0, "invariant"); } } else { pthread_mutex_unlock(_mutex); assert (status == 0, "invariant"); } } extern char** environ; // Run the specified command in a separate process. Return its exit value, // or -1 on failure (e.g. can't fork a new process). // Unlike system(), this function can be called from signal handler. It // doesn't block SIGINT et al. int os::fork_and_exec(char* cmd) { char * argv[4] = {"sh", "-c", cmd, NULL}; pid_t pid = fork(); if (pid < 0) { // fork failed return -1; } else if (pid == 0) { // child process // try to be consistent with system(), which uses "/usr/bin/sh" on AIX execve("/usr/bin/sh", argv, environ); // execve failed _exit(-1); } else { // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't // care about the actual exit code, for now. int status; // Wait for the child process to exit. This returns immediately if // the child has already exited. */ while (waitpid(pid, &status, 0) < 0) { switch (errno) { case ECHILD: return 0; case EINTR: break; default: return -1; } } if (WIFEXITED(status)) { // The child exited normally; get its exit code. return WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { // The child exited because of a signal // The best value to return is 0x80 + signal number, // because that is what all Unix shells do, and because // it allows callers to distinguish between process exit and // process death by signal. return 0x80 + WTERMSIG(status); } else { // Unknown exit code; pass it through return status; } } // Remove warning. return -1; } // is_headless_jre() // // Test for the existence of xawt/libmawt.so or libawt_xawt.so // in order to report if we are running in a headless jre. // // Since JDK8 xawt/libmawt.so is moved into the same directory // as libawt.so, and renamed libawt_xawt.so bool os::is_headless_jre() { struct stat statbuf; char buf[MAXPATHLEN]; char libmawtpath[MAXPATHLEN]; const char *xawtstr = "/xawt/libmawt.so"; const char *new_xawtstr = "/libawt_xawt.so"; char *p; // Get path to libjvm.so os::jvm_path(buf, sizeof(buf)); // Get rid of libjvm.so p = strrchr(buf, '/'); if (p == NULL) return false; else *p = '\0'; // Get rid of client or server p = strrchr(buf, '/'); if (p == NULL) return false; else *p = '\0'; // check xawt/libmawt.so strcpy(libmawtpath, buf); strcat(libmawtpath, xawtstr); if (::stat(libmawtpath, &statbuf) == 0) return false; // check libawt_xawt.so strcpy(libmawtpath, buf); strcat(libmawtpath, new_xawtstr); if (::stat(libmawtpath, &statbuf) == 0) return false; return true; } // Get the default path to the core file // Returns the length of the string int os::get_core_path(char* buffer, size_t bufferSize) { const char* p = get_current_directory(buffer, bufferSize); if (p == NULL) { assert(p != NULL, "failed to get current directory"); return 0; } return strlen(buffer); } #ifndef PRODUCT void TestReserveMemorySpecial_test() { // No tests available for this platform } #endif
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "ValueExtractionSynthesizer.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Interpreter/Value.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/StmtVisitor.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { ValueExtractionSynthesizer::ValueExtractionSynthesizer(clang::Sema* S) : TransactionTransformer(S), m_Context(&S->getASTContext()), m_gClingVD(0), m_UnresolvedNoAlloc(0), m_UnresolvedWithAlloc(0), m_UnresolvedCopyArray(0) { } // pin the vtable here. ValueExtractionSynthesizer::~ValueExtractionSynthesizer() { } namespace { class ReturnStmtCollector : public StmtVisitor<ReturnStmtCollector> { private: llvm::SmallVectorImpl<Stmt**>& m_Stmts; public: ReturnStmtCollector(llvm::SmallVectorImpl<Stmt**>& S) : m_Stmts(S) {} void VisitStmt(Stmt* S) { for(Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E; ++I) { if (!*I) continue; Visit(*I); if (isa<ReturnStmt>(*I)) m_Stmts.push_back(&*I); } } }; } void ValueExtractionSynthesizer::Transform() { const CompilationOptions& CO = getTransaction()->getCompilationOpts(); // If we do not evaluate the result, or printing out the result return. if (!(CO.ResultEvaluation || CO.ValuePrinting)) return; FunctionDecl* FD = getTransaction()->getWrapperFD(); int foundAtPos = -1; Expr* lastExpr = utils::Analyze::GetOrCreateLastExpr(FD, &foundAtPos, /*omitDS*/false, m_Sema); if (foundAtPos < 0) return; typedef llvm::SmallVector<Stmt**, 4> StmtIters; StmtIters returnStmts; ReturnStmtCollector collector(returnStmts); CompoundStmt* CS = cast<CompoundStmt>(FD->getBody()); collector.VisitStmt(CS); if (isa<Expr>(*(CS->body_begin() + foundAtPos))) returnStmts.push_back(CS->body_begin() + foundAtPos); // We want to support cases such as: // gCling->evaluate("if() return 'A' else return 12", V), that puts in V, // either A or 12. // In this case the void wrapper is compiled with the stmts returning // values. Sema would cast them to void, but the code will still be // executed. For example: // int g(); void f () { return g(); } will still call g(). // for (StmtIters::iterator I = returnStmts.begin(), E = returnStmts.end(); I != E; ++I) { ReturnStmt* RS = dyn_cast<ReturnStmt>(**I); if (RS) { // When we are handling a return stmt, the last expression must be the // return stmt value. Ignore the calculation of the lastStmt because it // might be wrong, in cases where the return is not in the end of the // function. lastExpr = RS->getRetValue(); if (lastExpr) { assert (lastExpr->getType()->isVoidType() && "Must be void type."); // Any return statement will have been "healed" by Sema // to correspond to the original void return type of the // wrapper, using a ImplicitCastExpr 'void' <ToVoid>. // Remove that. if (ImplicitCastExpr* VoidCast = dyn_cast<ImplicitCastExpr>(lastExpr)) { lastExpr = VoidCast->getSubExpr(); } } // if no value assume void else { // We can't PushDeclContext, because we don't have scope. Sema::ContextRAII pushedDC(*m_Sema, FD); RS->setRetValue(SynthesizeSVRInit(0)); } } else lastExpr = cast<Expr>(**I); if (lastExpr) { QualType lastExprTy = lastExpr->getType(); // May happen on auto types which resolve to dependent. if (lastExprTy->isDependentType()) continue; // Set up lastExpr properly. // Change the void function's return type // We can't PushDeclContext, because we don't have scope. Sema::ContextRAII pushedDC(*m_Sema, FD); if (lastExprTy->isFunctionType()) { // A return type of function needs to be converted to // pointer to function. lastExprTy = m_Context->getPointerType(lastExprTy); lastExpr = m_Sema->ImpCastExprToType(lastExpr, lastExprTy, CK_FunctionToPointerDecay, VK_RValue).take(); } // // Here we don't want to depend on the JIT runFunction, because of its // limitations, when it comes to return value handling. There it is // not clear who provides the storage and who cleans it up in a // platform independent way. // // Depending on the type we need to synthesize a call to cling: // 0) void : set the value's type to void; // 1) enum, integral, float, double, referece, pointer types : // call to cling::internal::setValueNoAlloc(...); // 2) object type (alloc on the stack) : // cling::internal::setValueWithAlloc // 2.1) constant arrays: // call to cling::runtime::internal::copyArray(...) // // We need to synthesize later: // Wrapper has signature: void w(cling::Value SVR) // case 1): // setValueNoAlloc(gCling, &SVR, lastExprTy, lastExpr()) // case 2): // new (setValueWithAlloc(gCling, &SVR, lastExprTy)) (lastExpr) // case 2.1): // copyArray(src, placement, size) Expr* SVRInit = SynthesizeSVRInit(lastExpr); // if we had return stmt update to execute the SVR init, even if the // wrapper returns void. if (RS) { if (ImplicitCastExpr* VoidCast = dyn_cast<ImplicitCastExpr>(RS->getRetValue())) VoidCast->setSubExpr(SVRInit); } else **I = SVRInit; } } } Expr* ValueExtractionSynthesizer::SynthesizeSVRInit(Expr* E) { if (!m_gClingVD) FindAndCacheRuntimeDecls(); // Build a reference to gCling ExprResult gClingDRE = m_Sema->BuildDeclRefExpr(m_gClingVD, m_Context->VoidPtrTy, VK_RValue, SourceLocation()); // We have the wrapper as Sema's CurContext FunctionDecl* FD = cast<FunctionDecl>(m_Sema->CurContext); ExprWithCleanups* Cleanups = 0; // In case of ExprWithCleanups we need to extend its 'scope' to the call. if (E && isa<ExprWithCleanups>(E)) { Cleanups = cast<ExprWithCleanups>(E); E = Cleanups->getSubExpr(); } // Build a reference to Value* in the wrapper, should be // the only argument of the wrapper. SourceLocation locStart = (E) ? E->getLocStart() : FD->getLocStart(); SourceLocation locEnd = (E) ? E->getLocEnd() : FD->getLocEnd(); ExprResult wrapperSVRDRE = m_Sema->BuildDeclRefExpr(FD->getParamDecl(0), m_Context->VoidPtrTy, VK_RValue, locStart); QualType ETy = (E) ? E->getType() : m_Context->VoidTy; QualType desugaredTy = ETy.getDesugaredType(*m_Context); // The expr result is transported as reference, pointer, array, float etc // based on the desugared type. We should still expose the typedef'ed // (sugared) type to the cling::Value. if (desugaredTy->isRecordType() && !Cleanups) { // returning a lvalue (not a temporary): the value should contain // a reference to the lvalue instead of copying it. desugaredTy = m_Context->getLValueReferenceType(desugaredTy); ETy = m_Context->getLValueReferenceType(ETy); } Expr* ETyVP = utils::Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy, (uint64_t)ETy.getAsOpaquePtr()); llvm::SmallVector<Expr*, 4> CallArgs; CallArgs.push_back(gClingDRE.take()); CallArgs.push_back(wrapperSVRDRE.take()); CallArgs.push_back(ETyVP); ExprResult Call; SourceLocation noLoc; if (desugaredTy->isVoidType()) { // In cases where the cling::Value gets reused we need to reset the // previous settings to void. // We need to synthesize setValueNoAlloc(...), E, because we still need // to run E. Call = m_Sema->ActOnCallExpr(/*Scope*/0, m_UnresolvedNoAlloc, locStart, CallArgs, locEnd); if (E) Call = m_Sema->CreateBuiltinBinOp(locStart, BO_Comma, Call.take(), E); } else if (desugaredTy->isRecordType() || desugaredTy->isConstantArrayType()){ // 2) object types : // call new (setValueWithAlloc(gCling, &SVR, ETy)) (E) Call = m_Sema->ActOnCallExpr(/*Scope*/0, m_UnresolvedWithAlloc, locStart, CallArgs, locEnd); Expr* placement = Call.take(); if (const ConstantArrayType* constArray = dyn_cast<ConstantArrayType>(desugaredTy.getTypePtr())) { CallArgs.clear(); CallArgs.push_back(E); CallArgs.push_back(placement); uint64_t arrSize = m_Context->getConstantArrayElementCount(constArray); Expr* arrSizeExpr = utils::Synthesize::IntegerLiteralExpr(*m_Context, arrSize); CallArgs.push_back(arrSizeExpr); // 2.1) arrays: // call copyArray(T* src, void* placement, int size) Call = m_Sema->ActOnCallExpr(/*Scope*/0, m_UnresolvedCopyArray, locStart, CallArgs, locEnd); } else { TypeSourceInfo* ETSI = m_Context->getTrivialTypeSourceInfo(ETy, noLoc); Call = m_Sema->BuildCXXNew(E->getSourceRange(), /*useGlobal ::*/true, /*placementLParen*/ noLoc, MultiExprArg(placement), /*placementRParen*/ noLoc, /*TypeIdParens*/ SourceRange(), /*allocType*/ ETSI->getType(), /*allocTypeInfo*/ETSI, /*arraySize*/0, /*directInitRange*/E->getSourceRange(), /*initializer*/E, /*mayContainAuto*/false ); } } else if (desugaredTy->isIntegralOrEnumerationType() || desugaredTy->isReferenceType() || desugaredTy->isPointerType() || desugaredTy->isFloatingType()) { if (desugaredTy->isIntegralOrEnumerationType()) { // 1) enum, integral, float, double, referece, pointer types : // call to cling::internal::setValueNoAlloc(...); // If the type is enum or integral we need to force-cast it into // uint64 in order to pick up the correct overload. if (desugaredTy->isIntegralOrEnumerationType()) { QualType UInt64Ty = m_Context->UnsignedLongLongTy; TypeSourceInfo* TSI = m_Context->getTrivialTypeSourceInfo(UInt64Ty, noLoc); Expr* castedE = m_Sema->BuildCStyleCastExpr(noLoc, TSI, noLoc, E).take(); CallArgs.push_back(castedE); } } else if (desugaredTy->isReferenceType()) { // we need to get the address of the references Expr* AddrOfE = m_Sema->BuildUnaryOp(/*Scope*/0, noLoc, UO_AddrOf, E).take(); CallArgs.push_back(AddrOfE); } else if (desugaredTy->isPointerType()) { // function pointers need explicit void* cast. QualType VoidPtrTy = m_Context->VoidPtrTy; TypeSourceInfo* TSI = m_Context->getTrivialTypeSourceInfo(VoidPtrTy, noLoc); Expr* castedE = m_Sema->BuildCStyleCastExpr(noLoc, TSI, noLoc, E).take(); CallArgs.push_back(castedE); } else if (desugaredTy->isFloatingType()) { // floats and double will fall naturally in the correct // case, because of the overload resolution. CallArgs.push_back(E); } Call = m_Sema->ActOnCallExpr(/*Scope*/0, m_UnresolvedNoAlloc, locStart, CallArgs, locEnd); } else assert(0 && "Unhandled code path?"); assert(!Call.isInvalid() && "Invalid Call"); // Extend the scope of the temporary cleaner if applicable. if (Cleanups) { Cleanups->setSubExpr(Call.take()); Cleanups->setValueKind(Call.take()->getValueKind()); Cleanups->setType(Call.take()->getType()); return Cleanups; } return Call.take(); } void ValueExtractionSynthesizer::FindAndCacheRuntimeDecls() { assert(!m_gClingVD && "Called multiple times!?"); DeclContext* NSD = m_Context->getTranslationUnitDecl(); if (m_Sema->getLangOpts().CPlusPlus) { NSD = utils::Lookup::Namespace(m_Sema, "cling"); NSD = utils::Lookup::Namespace(m_Sema, "runtime", NSD); m_gClingVD = cast<VarDecl>(utils::Lookup::Named(m_Sema, "gCling", NSD)); NSD = utils::Lookup::Namespace(m_Sema, "internal",NSD); } LookupResult R(*m_Sema, &m_Context->Idents.get("setValueNoAlloc"), SourceLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(R, NSD); assert(!R.empty() && "Cannot find cling::runtime::internal::setValueNoAlloc"); CXXScopeSpec CSS; m_UnresolvedNoAlloc = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); R.clear(); R.setLookupName(&m_Context->Idents.get("setValueWithAlloc")); m_Sema->LookupQualifiedName(R, NSD); assert(!R.empty() && "Cannot find cling::runtime::internal::setValueWithAlloc"); m_UnresolvedWithAlloc = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); R.clear(); R.setLookupName(&m_Context->Idents.get("copyArray")); m_Sema->LookupQualifiedName(R, NSD); assert(!R.empty() && "Cannot find cling::runtime::internal::copyArray"); m_UnresolvedCopyArray = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); } } // end namespace cling // Provide implementation of the functions that ValueExtractionSynthesizer calls namespace { static void dumpIfNoStorage(void* vpI, void* vpV) { cling::Interpreter* I = (cling::Interpreter*)vpI; const cling::Value& V = *(cling::Value*)vpV; //const cling::Transaction& T = *(cling::Transaction*)vpT); // If the value copies over the temporary we must delay the printing until // the temporary gets copied over. For the rest of the temporaries we *must* // dump here because their lifetime will be gone otherwise. Eg. // // std::string f(); f().c_str() // have to dump during the same stmt. // assert(!V.needsManagedAllocation() && "Must contain non managed temporary"); // FIXME: We should pass in the 'right' transaction when we requested the // code. This should happen with extra parameter. const cling::CompilationOptions& CO = I->getLastTransaction()->getCompilationOpts(); if (CO.ValuePrinting != cling::CompilationOptions::VPDisabled) V.dump(); } ///\brief Allocate the Value and return the Value /// for an expression evaluated at the prompt. /// ///\param [in] interp - The cling::Interpreter to allocate the SToredValueRef. ///\param [in] vpQT - The opaque ptr for the clang::QualType of value stored. ///\param [out] vpStoredValRef - The Value that is allocated. static cling::Value& allocateStoredRefValueAndGetGV(void* vpI, void* vpSVR, void* vpQT) { cling::Interpreter* i = (cling::Interpreter*)vpI; clang::QualType QT = clang::QualType::getFromOpaquePtr(vpQT); cling::Value& SVR = *(cling::Value*)vpSVR; // Here the copy keeps the refcounted value alive. SVR = cling::Value(QT, *i); return SVR; } } namespace cling { namespace runtime { namespace internal { void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT) { // In cases of void we 'just' need to change the type of the value. allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT); dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, float value) { allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<float>() = value; dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, double value) { allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<double>() = value; dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, long double value) { allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<long double>() = value; dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, unsigned long long value) { allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT) .getAs<unsigned long long>() = value; dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, const void* value){ allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<void*>() = const_cast<void*>(value); dumpIfNoStorage(vpI, vpSVR); } void* setValueWithAlloc(void* vpI, void* vpSVR, void* vpQT) { return allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<void*>(); } } // end namespace internal } // end namespace runtime } // end namespace cling Do not dump for void, resetting the value of the value. //------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "ValueExtractionSynthesizer.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Interpreter/Value.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/StmtVisitor.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { ValueExtractionSynthesizer::ValueExtractionSynthesizer(clang::Sema* S) : TransactionTransformer(S), m_Context(&S->getASTContext()), m_gClingVD(0), m_UnresolvedNoAlloc(0), m_UnresolvedWithAlloc(0), m_UnresolvedCopyArray(0) { } // pin the vtable here. ValueExtractionSynthesizer::~ValueExtractionSynthesizer() { } namespace { class ReturnStmtCollector : public StmtVisitor<ReturnStmtCollector> { private: llvm::SmallVectorImpl<Stmt**>& m_Stmts; public: ReturnStmtCollector(llvm::SmallVectorImpl<Stmt**>& S) : m_Stmts(S) {} void VisitStmt(Stmt* S) { for(Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E; ++I) { if (!*I) continue; Visit(*I); if (isa<ReturnStmt>(*I)) m_Stmts.push_back(&*I); } } }; } void ValueExtractionSynthesizer::Transform() { const CompilationOptions& CO = getTransaction()->getCompilationOpts(); // If we do not evaluate the result, or printing out the result return. if (!(CO.ResultEvaluation || CO.ValuePrinting)) return; FunctionDecl* FD = getTransaction()->getWrapperFD(); int foundAtPos = -1; Expr* lastExpr = utils::Analyze::GetOrCreateLastExpr(FD, &foundAtPos, /*omitDS*/false, m_Sema); if (foundAtPos < 0) return; typedef llvm::SmallVector<Stmt**, 4> StmtIters; StmtIters returnStmts; ReturnStmtCollector collector(returnStmts); CompoundStmt* CS = cast<CompoundStmt>(FD->getBody()); collector.VisitStmt(CS); if (isa<Expr>(*(CS->body_begin() + foundAtPos))) returnStmts.push_back(CS->body_begin() + foundAtPos); // We want to support cases such as: // gCling->evaluate("if() return 'A' else return 12", V), that puts in V, // either A or 12. // In this case the void wrapper is compiled with the stmts returning // values. Sema would cast them to void, but the code will still be // executed. For example: // int g(); void f () { return g(); } will still call g(). // for (StmtIters::iterator I = returnStmts.begin(), E = returnStmts.end(); I != E; ++I) { ReturnStmt* RS = dyn_cast<ReturnStmt>(**I); if (RS) { // When we are handling a return stmt, the last expression must be the // return stmt value. Ignore the calculation of the lastStmt because it // might be wrong, in cases where the return is not in the end of the // function. lastExpr = RS->getRetValue(); if (lastExpr) { assert (lastExpr->getType()->isVoidType() && "Must be void type."); // Any return statement will have been "healed" by Sema // to correspond to the original void return type of the // wrapper, using a ImplicitCastExpr 'void' <ToVoid>. // Remove that. if (ImplicitCastExpr* VoidCast = dyn_cast<ImplicitCastExpr>(lastExpr)) { lastExpr = VoidCast->getSubExpr(); } } // if no value assume void else { // We can't PushDeclContext, because we don't have scope. Sema::ContextRAII pushedDC(*m_Sema, FD); RS->setRetValue(SynthesizeSVRInit(0)); } } else lastExpr = cast<Expr>(**I); if (lastExpr) { QualType lastExprTy = lastExpr->getType(); // May happen on auto types which resolve to dependent. if (lastExprTy->isDependentType()) continue; // Set up lastExpr properly. // Change the void function's return type // We can't PushDeclContext, because we don't have scope. Sema::ContextRAII pushedDC(*m_Sema, FD); if (lastExprTy->isFunctionType()) { // A return type of function needs to be converted to // pointer to function. lastExprTy = m_Context->getPointerType(lastExprTy); lastExpr = m_Sema->ImpCastExprToType(lastExpr, lastExprTy, CK_FunctionToPointerDecay, VK_RValue).take(); } // // Here we don't want to depend on the JIT runFunction, because of its // limitations, when it comes to return value handling. There it is // not clear who provides the storage and who cleans it up in a // platform independent way. // // Depending on the type we need to synthesize a call to cling: // 0) void : set the value's type to void; // 1) enum, integral, float, double, referece, pointer types : // call to cling::internal::setValueNoAlloc(...); // 2) object type (alloc on the stack) : // cling::internal::setValueWithAlloc // 2.1) constant arrays: // call to cling::runtime::internal::copyArray(...) // // We need to synthesize later: // Wrapper has signature: void w(cling::Value SVR) // case 1): // setValueNoAlloc(gCling, &SVR, lastExprTy, lastExpr()) // case 2): // new (setValueWithAlloc(gCling, &SVR, lastExprTy)) (lastExpr) // case 2.1): // copyArray(src, placement, size) Expr* SVRInit = SynthesizeSVRInit(lastExpr); // if we had return stmt update to execute the SVR init, even if the // wrapper returns void. if (RS) { if (ImplicitCastExpr* VoidCast = dyn_cast<ImplicitCastExpr>(RS->getRetValue())) VoidCast->setSubExpr(SVRInit); } else **I = SVRInit; } } } Expr* ValueExtractionSynthesizer::SynthesizeSVRInit(Expr* E) { if (!m_gClingVD) FindAndCacheRuntimeDecls(); // Build a reference to gCling ExprResult gClingDRE = m_Sema->BuildDeclRefExpr(m_gClingVD, m_Context->VoidPtrTy, VK_RValue, SourceLocation()); // We have the wrapper as Sema's CurContext FunctionDecl* FD = cast<FunctionDecl>(m_Sema->CurContext); ExprWithCleanups* Cleanups = 0; // In case of ExprWithCleanups we need to extend its 'scope' to the call. if (E && isa<ExprWithCleanups>(E)) { Cleanups = cast<ExprWithCleanups>(E); E = Cleanups->getSubExpr(); } // Build a reference to Value* in the wrapper, should be // the only argument of the wrapper. SourceLocation locStart = (E) ? E->getLocStart() : FD->getLocStart(); SourceLocation locEnd = (E) ? E->getLocEnd() : FD->getLocEnd(); ExprResult wrapperSVRDRE = m_Sema->BuildDeclRefExpr(FD->getParamDecl(0), m_Context->VoidPtrTy, VK_RValue, locStart); QualType ETy = (E) ? E->getType() : m_Context->VoidTy; QualType desugaredTy = ETy.getDesugaredType(*m_Context); // The expr result is transported as reference, pointer, array, float etc // based on the desugared type. We should still expose the typedef'ed // (sugared) type to the cling::Value. if (desugaredTy->isRecordType() && !Cleanups) { // returning a lvalue (not a temporary): the value should contain // a reference to the lvalue instead of copying it. desugaredTy = m_Context->getLValueReferenceType(desugaredTy); ETy = m_Context->getLValueReferenceType(ETy); } Expr* ETyVP = utils::Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy, (uint64_t)ETy.getAsOpaquePtr()); llvm::SmallVector<Expr*, 4> CallArgs; CallArgs.push_back(gClingDRE.take()); CallArgs.push_back(wrapperSVRDRE.take()); CallArgs.push_back(ETyVP); ExprResult Call; SourceLocation noLoc; if (desugaredTy->isVoidType()) { // In cases where the cling::Value gets reused we need to reset the // previous settings to void. // We need to synthesize setValueNoAlloc(...), E, because we still need // to run E. Call = m_Sema->ActOnCallExpr(/*Scope*/0, m_UnresolvedNoAlloc, locStart, CallArgs, locEnd); if (E) Call = m_Sema->CreateBuiltinBinOp(locStart, BO_Comma, Call.take(), E); } else if (desugaredTy->isRecordType() || desugaredTy->isConstantArrayType()){ // 2) object types : // call new (setValueWithAlloc(gCling, &SVR, ETy)) (E) Call = m_Sema->ActOnCallExpr(/*Scope*/0, m_UnresolvedWithAlloc, locStart, CallArgs, locEnd); Expr* placement = Call.take(); if (const ConstantArrayType* constArray = dyn_cast<ConstantArrayType>(desugaredTy.getTypePtr())) { CallArgs.clear(); CallArgs.push_back(E); CallArgs.push_back(placement); uint64_t arrSize = m_Context->getConstantArrayElementCount(constArray); Expr* arrSizeExpr = utils::Synthesize::IntegerLiteralExpr(*m_Context, arrSize); CallArgs.push_back(arrSizeExpr); // 2.1) arrays: // call copyArray(T* src, void* placement, int size) Call = m_Sema->ActOnCallExpr(/*Scope*/0, m_UnresolvedCopyArray, locStart, CallArgs, locEnd); } else { TypeSourceInfo* ETSI = m_Context->getTrivialTypeSourceInfo(ETy, noLoc); Call = m_Sema->BuildCXXNew(E->getSourceRange(), /*useGlobal ::*/true, /*placementLParen*/ noLoc, MultiExprArg(placement), /*placementRParen*/ noLoc, /*TypeIdParens*/ SourceRange(), /*allocType*/ ETSI->getType(), /*allocTypeInfo*/ETSI, /*arraySize*/0, /*directInitRange*/E->getSourceRange(), /*initializer*/E, /*mayContainAuto*/false ); } } else if (desugaredTy->isIntegralOrEnumerationType() || desugaredTy->isReferenceType() || desugaredTy->isPointerType() || desugaredTy->isFloatingType()) { if (desugaredTy->isIntegralOrEnumerationType()) { // 1) enum, integral, float, double, referece, pointer types : // call to cling::internal::setValueNoAlloc(...); // If the type is enum or integral we need to force-cast it into // uint64 in order to pick up the correct overload. if (desugaredTy->isIntegralOrEnumerationType()) { QualType UInt64Ty = m_Context->UnsignedLongLongTy; TypeSourceInfo* TSI = m_Context->getTrivialTypeSourceInfo(UInt64Ty, noLoc); Expr* castedE = m_Sema->BuildCStyleCastExpr(noLoc, TSI, noLoc, E).take(); CallArgs.push_back(castedE); } } else if (desugaredTy->isReferenceType()) { // we need to get the address of the references Expr* AddrOfE = m_Sema->BuildUnaryOp(/*Scope*/0, noLoc, UO_AddrOf, E).take(); CallArgs.push_back(AddrOfE); } else if (desugaredTy->isPointerType()) { // function pointers need explicit void* cast. QualType VoidPtrTy = m_Context->VoidPtrTy; TypeSourceInfo* TSI = m_Context->getTrivialTypeSourceInfo(VoidPtrTy, noLoc); Expr* castedE = m_Sema->BuildCStyleCastExpr(noLoc, TSI, noLoc, E).take(); CallArgs.push_back(castedE); } else if (desugaredTy->isFloatingType()) { // floats and double will fall naturally in the correct // case, because of the overload resolution. CallArgs.push_back(E); } Call = m_Sema->ActOnCallExpr(/*Scope*/0, m_UnresolvedNoAlloc, locStart, CallArgs, locEnd); } else assert(0 && "Unhandled code path?"); assert(!Call.isInvalid() && "Invalid Call"); // Extend the scope of the temporary cleaner if applicable. if (Cleanups) { Cleanups->setSubExpr(Call.take()); Cleanups->setValueKind(Call.take()->getValueKind()); Cleanups->setType(Call.take()->getType()); return Cleanups; } return Call.take(); } void ValueExtractionSynthesizer::FindAndCacheRuntimeDecls() { assert(!m_gClingVD && "Called multiple times!?"); DeclContext* NSD = m_Context->getTranslationUnitDecl(); if (m_Sema->getLangOpts().CPlusPlus) { NSD = utils::Lookup::Namespace(m_Sema, "cling"); NSD = utils::Lookup::Namespace(m_Sema, "runtime", NSD); m_gClingVD = cast<VarDecl>(utils::Lookup::Named(m_Sema, "gCling", NSD)); NSD = utils::Lookup::Namespace(m_Sema, "internal",NSD); } LookupResult R(*m_Sema, &m_Context->Idents.get("setValueNoAlloc"), SourceLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(R, NSD); assert(!R.empty() && "Cannot find cling::runtime::internal::setValueNoAlloc"); CXXScopeSpec CSS; m_UnresolvedNoAlloc = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); R.clear(); R.setLookupName(&m_Context->Idents.get("setValueWithAlloc")); m_Sema->LookupQualifiedName(R, NSD); assert(!R.empty() && "Cannot find cling::runtime::internal::setValueWithAlloc"); m_UnresolvedWithAlloc = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); R.clear(); R.setLookupName(&m_Context->Idents.get("copyArray")); m_Sema->LookupQualifiedName(R, NSD); assert(!R.empty() && "Cannot find cling::runtime::internal::copyArray"); m_UnresolvedCopyArray = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); } } // end namespace cling // Provide implementation of the functions that ValueExtractionSynthesizer calls namespace { static void dumpIfNoStorage(void* vpI, void* vpV) { cling::Interpreter* I = (cling::Interpreter*)vpI; const cling::Value& V = *(cling::Value*)vpV; //const cling::Transaction& T = *(cling::Transaction*)vpT); // If the value copies over the temporary we must delay the printing until // the temporary gets copied over. For the rest of the temporaries we *must* // dump here because their lifetime will be gone otherwise. Eg. // // std::string f(); f().c_str() // have to dump during the same stmt. // assert(!V.needsManagedAllocation() && "Must contain non managed temporary"); // FIXME: We should pass in the 'right' transaction when we requested the // code. This should happen with extra parameter. const cling::CompilationOptions& CO = I->getLastTransaction()->getCompilationOpts(); if (CO.ValuePrinting != cling::CompilationOptions::VPDisabled) V.dump(); } ///\brief Allocate the Value and return the Value /// for an expression evaluated at the prompt. /// ///\param [in] interp - The cling::Interpreter to allocate the SToredValueRef. ///\param [in] vpQT - The opaque ptr for the clang::QualType of value stored. ///\param [out] vpStoredValRef - The Value that is allocated. static cling::Value& allocateStoredRefValueAndGetGV(void* vpI, void* vpSVR, void* vpQT) { cling::Interpreter* i = (cling::Interpreter*)vpI; clang::QualType QT = clang::QualType::getFromOpaquePtr(vpQT); cling::Value& SVR = *(cling::Value*)vpSVR; // Here the copy keeps the refcounted value alive. SVR = cling::Value(QT, *i); return SVR; } } namespace cling { namespace runtime { namespace internal { void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, void* vpT) { // In cases of void we 'just' need to change the type of the value. allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, float value) { allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<float>() = value; dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, double value) { allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<double>() = value; dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, long double value) { allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<long double>() = value; dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, unsigned long long value) { allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT) .getAs<unsigned long long>() = value; dumpIfNoStorage(vpI, vpSVR); } void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, const void* value){ allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<void*>() = const_cast<void*>(value); dumpIfNoStorage(vpI, vpSVR); } void* setValueWithAlloc(void* vpI, void* vpSVR, void* vpQT) { return allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs<void*>(); } } // end namespace internal } // end namespace runtime } // end namespace cling
//===-- ASTReader.cpp - AST File Reader -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTReader class, which reads AST files. // //===----------------------------------------------------------------------===// #include "clang/Serialization/ASTReader.h" #include "ASTCommon.h" #include "ASTReaderInternals.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/ASTUnresolvedSet.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/ODRHash.h" #include "clang/AST/RawCommentList.h" #include "clang/AST/Type.h" #include "clang/AST/TypeLocVisitor.h" #include "clang/AST/UnresolvedSet.h" #include "clang/Basic/CommentOptions.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/ExceptionSpecificationType.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/MemoryBufferCache.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/Sanitizers.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/SourceManagerInternals.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/TokenKinds.h" #include "clang/Basic/Version.h" #include "clang/Basic/VersionTuple.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/ModuleMap.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Sema/Scope.h" #include "clang/Sema/Sema.h" #include "clang/Sema/Weak.h" #include "clang/Serialization/ASTDeserializationListener.h" #include "clang/Serialization/GlobalModuleIndex.h" #include "clang/Serialization/ModuleManager.h" #include "clang/Serialization/SerializationDiagnostic.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/Support/Compression.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Error.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/SaveAndRestore.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <iterator> #include <limits> #include <map> #include <memory> #include <new> #include <string> #include <system_error> #include <tuple> #include <utility> #include <vector> using namespace clang; using namespace clang::serialization; using namespace clang::serialization::reader; using llvm::BitstreamCursor; //===----------------------------------------------------------------------===// // ChainedASTReaderListener implementation //===----------------------------------------------------------------------===// bool ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) { return First->ReadFullVersionInformation(FullVersion) || Second->ReadFullVersionInformation(FullVersion); } void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) { First->ReadModuleName(ModuleName); Second->ReadModuleName(ModuleName); } void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) { First->ReadModuleMapFile(ModuleMapPath); Second->ReadModuleMapFile(ModuleMapPath); } bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) { return First->ReadLanguageOptions(LangOpts, Complain, AllowCompatibleDifferences) || Second->ReadLanguageOptions(LangOpts, Complain, AllowCompatibleDifferences); } bool ChainedASTReaderListener::ReadTargetOptions( const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) { return First->ReadTargetOptions(TargetOpts, Complain, AllowCompatibleDifferences) || Second->ReadTargetOptions(TargetOpts, Complain, AllowCompatibleDifferences); } bool ChainedASTReaderListener::ReadDiagnosticOptions( IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { return First->ReadDiagnosticOptions(DiagOpts, Complain) || Second->ReadDiagnosticOptions(DiagOpts, Complain); } bool ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) { return First->ReadFileSystemOptions(FSOpts, Complain) || Second->ReadFileSystemOptions(FSOpts, Complain); } bool ChainedASTReaderListener::ReadHeaderSearchOptions( const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) { return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, Complain) || Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, Complain); } bool ChainedASTReaderListener::ReadPreprocessorOptions( const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) { return First->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines) || Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines); } void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M, unsigned Value) { First->ReadCounter(M, Value); Second->ReadCounter(M, Value); } bool ChainedASTReaderListener::needsInputFileVisitation() { return First->needsInputFileVisitation() || Second->needsInputFileVisitation(); } bool ChainedASTReaderListener::needsSystemInputFileVisitation() { return First->needsSystemInputFileVisitation() || Second->needsSystemInputFileVisitation(); } void ChainedASTReaderListener::visitModuleFile(StringRef Filename, ModuleKind Kind) { First->visitModuleFile(Filename, Kind); Second->visitModuleFile(Filename, Kind); } bool ChainedASTReaderListener::visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) { bool Continue = false; if (First->needsInputFileVisitation() && (!isSystem || First->needsSystemInputFileVisitation())) Continue |= First->visitInputFile(Filename, isSystem, isOverridden, isExplicitModule); if (Second->needsInputFileVisitation() && (!isSystem || Second->needsSystemInputFileVisitation())) Continue |= Second->visitInputFile(Filename, isSystem, isOverridden, isExplicitModule); return Continue; } void ChainedASTReaderListener::readModuleFileExtension( const ModuleFileExtensionMetadata &Metadata) { First->readModuleFileExtension(Metadata); Second->readModuleFileExtension(Metadata); } //===----------------------------------------------------------------------===// // PCH validator implementation //===----------------------------------------------------------------------===// ASTReaderListener::~ASTReaderListener() {} /// \brief Compare the given set of language options against an existing set of /// language options. /// /// \param Diags If non-NULL, diagnostics will be emitted via this engine. /// \param AllowCompatibleDifferences If true, differences between compatible /// language options will be permitted. /// /// \returns true if the languagae options mis-match, false otherwise. static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences = true) { #define LANGOPT(Name, Bits, Default, Description) \ if (ExistingLangOpts.Name != LangOpts.Name) { \ if (Diags) \ Diags->Report(diag::err_pch_langopt_mismatch) \ << Description << LangOpts.Name << ExistingLangOpts.Name; \ return true; \ } #define VALUE_LANGOPT(Name, Bits, Default, Description) \ if (ExistingLangOpts.Name != LangOpts.Name) { \ if (Diags) \ Diags->Report(diag::err_pch_langopt_value_mismatch) \ << Description; \ return true; \ } #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \ if (Diags) \ Diags->Report(diag::err_pch_langopt_value_mismatch) \ << Description; \ return true; \ } #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \ if (!AllowCompatibleDifferences) \ LANGOPT(Name, Bits, Default, Description) #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \ if (!AllowCompatibleDifferences) \ ENUM_LANGOPT(Name, Bits, Default, Description) #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \ if (!AllowCompatibleDifferences) \ VALUE_LANGOPT(Name, Bits, Default, Description) #define BENIGN_LANGOPT(Name, Bits, Default, Description) #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description) #include "clang/Basic/LangOptions.def" if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) { if (Diags) Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features"; return true; } if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) { if (Diags) Diags->Report(diag::err_pch_langopt_value_mismatch) << "target Objective-C runtime"; return true; } if (ExistingLangOpts.CommentOpts.BlockCommandNames != LangOpts.CommentOpts.BlockCommandNames) { if (Diags) Diags->Report(diag::err_pch_langopt_value_mismatch) << "block command names"; return true; } // Sanitizer feature mismatches are treated as compatible differences. If // compatible differences aren't allowed, we still only want to check for // mismatches of non-modular sanitizers (the only ones which can affect AST // generation). if (!AllowCompatibleDifferences) { SanitizerMask ModularSanitizers = getPPTransparentSanitizers(); SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize; SanitizerSet ImportedSanitizers = LangOpts.Sanitize; ExistingSanitizers.clear(ModularSanitizers); ImportedSanitizers.clear(ModularSanitizers); if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) { const std::string Flag = "-fsanitize="; if (Diags) { #define SANITIZER(NAME, ID) \ { \ bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \ bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \ if (InExistingModule != InImportedModule) \ Diags->Report(diag::err_pch_targetopt_feature_mismatch) \ << InExistingModule << (Flag + NAME); \ } #include "clang/Basic/Sanitizers.def" } return true; } } return false; } /// \brief Compare the given set of target options against an existing set of /// target options. /// /// \param Diags If non-NULL, diagnostics will be emitted via this engine. /// /// \returns true if the target options mis-match, false otherwise. static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences = true) { #define CHECK_TARGET_OPT(Field, Name) \ if (TargetOpts.Field != ExistingTargetOpts.Field) { \ if (Diags) \ Diags->Report(diag::err_pch_targetopt_mismatch) \ << Name << TargetOpts.Field << ExistingTargetOpts.Field; \ return true; \ } // The triple and ABI must match exactly. CHECK_TARGET_OPT(Triple, "target"); CHECK_TARGET_OPT(ABI, "target ABI"); // We can tolerate different CPUs in many cases, notably when one CPU // supports a strict superset of another. When allowing compatible // differences skip this check. if (!AllowCompatibleDifferences) CHECK_TARGET_OPT(CPU, "target CPU"); #undef CHECK_TARGET_OPT // Compare feature sets. SmallVector<StringRef, 4> ExistingFeatures( ExistingTargetOpts.FeaturesAsWritten.begin(), ExistingTargetOpts.FeaturesAsWritten.end()); SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(), TargetOpts.FeaturesAsWritten.end()); std::sort(ExistingFeatures.begin(), ExistingFeatures.end()); std::sort(ReadFeatures.begin(), ReadFeatures.end()); // We compute the set difference in both directions explicitly so that we can // diagnose the differences differently. SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures; std::set_difference( ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(), ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures)); std::set_difference(ReadFeatures.begin(), ReadFeatures.end(), ExistingFeatures.begin(), ExistingFeatures.end(), std::back_inserter(UnmatchedReadFeatures)); // If we are allowing compatible differences and the read feature set is // a strict subset of the existing feature set, there is nothing to diagnose. if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty()) return false; if (Diags) { for (StringRef Feature : UnmatchedReadFeatures) Diags->Report(diag::err_pch_targetopt_feature_mismatch) << /* is-existing-feature */ false << Feature; for (StringRef Feature : UnmatchedExistingFeatures) Diags->Report(diag::err_pch_targetopt_feature_mismatch) << /* is-existing-feature */ true << Feature; } return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty(); } bool PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) { const LangOptions &ExistingLangOpts = PP.getLangOpts(); return checkLanguageOptions(LangOpts, ExistingLangOpts, Complain ? &Reader.Diags : nullptr, AllowCompatibleDifferences); } bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) { const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts(); return checkTargetOptions(TargetOpts, ExistingTargetOpts, Complain ? &Reader.Diags : nullptr, AllowCompatibleDifferences); } namespace { typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> > MacroDefinitionsMap; typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > DeclsMap; } // end anonymous namespace static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool Complain) { typedef DiagnosticsEngine::Level Level; // Check current mappings for new -Werror mappings, and the stored mappings // for cases that were explicitly mapped to *not* be errors that are now // errors because of options like -Werror. DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags }; for (DiagnosticsEngine *MappingSource : MappingSources) { for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) { diag::kind DiagID = DiagIDMappingPair.first; Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation()); if (CurLevel < DiagnosticsEngine::Error) continue; // not significant Level StoredLevel = StoredDiags.getDiagnosticLevel(DiagID, SourceLocation()); if (StoredLevel < DiagnosticsEngine::Error) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" + Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str(); return true; } } } return false; } static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) { diag::Severity Ext = Diags.getExtensionHandlingBehavior(); if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors()) return true; return Ext >= diag::Severity::Error; } static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool IsSystem, bool Complain) { // Top-level options if (IsSystem) { if (Diags.getSuppressSystemWarnings()) return false; // If -Wsystem-headers was not enabled before, be conservative if (StoredDiags.getSuppressSystemWarnings()) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers"; return true; } } if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror"; return true; } if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() && !StoredDiags.getEnableAllWarnings()) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror"; return true; } if (isExtHandlingFromDiagsError(Diags) && !isExtHandlingFromDiagsError(StoredDiags)) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors"; return true; } return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain); } /// Return the top import module if it is implicit, nullptr otherwise. static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP) { // If the original import came from a file explicitly generated by the user, // don't check the diagnostic mappings. // FIXME: currently this is approximated by checking whether this is not a // module import of an implicitly-loaded module file. // Note: ModuleMgr.rbegin() may not be the current module, but it must be in // the transitive closure of its imports, since unrelated modules cannot be // imported until after this module finishes validation. ModuleFile *TopImport = &*ModuleMgr.rbegin(); while (!TopImport->ImportedBy.empty()) TopImport = TopImport->ImportedBy[0]; if (TopImport->Kind != MK_ImplicitModule) return nullptr; StringRef ModuleName = TopImport->ModuleName; assert(!ModuleName.empty() && "diagnostic options read before module name"); Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName); assert(M && "missing module"); return M; } bool PCHValidator::ReadDiagnosticOptions( IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs()); IntrusiveRefCntPtr<DiagnosticsEngine> Diags( new DiagnosticsEngine(DiagIDs, DiagOpts.get())); // This should never fail, because we would have processed these options // before writing them to an ASTFile. ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false); ModuleManager &ModuleMgr = Reader.getModuleManager(); assert(ModuleMgr.size() >= 1 && "what ASTFile is this then"); Module *TopM = getTopImportImplicitModule(ModuleMgr, PP); if (!TopM) return false; // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that // contains the union of their flags. return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem, Complain); } /// \brief Collect the macro definitions provided by the given preprocessor /// options. static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl<StringRef> *MacroNames = nullptr) { for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { StringRef Macro = PPOpts.Macros[I].first; bool IsUndef = PPOpts.Macros[I].second; std::pair<StringRef, StringRef> MacroPair = Macro.split('='); StringRef MacroName = MacroPair.first; StringRef MacroBody = MacroPair.second; // For an #undef'd macro, we only care about the name. if (IsUndef) { if (MacroNames && !Macros.count(MacroName)) MacroNames->push_back(MacroName); Macros[MacroName] = std::make_pair("", true); continue; } // For a #define'd macro, figure out the actual definition. if (MacroName.size() == Macro.size()) MacroBody = "1"; else { // Note: GCC drops anything following an end-of-line character. StringRef::size_type End = MacroBody.find_first_of("\n\r"); MacroBody = MacroBody.substr(0, End); } if (MacroNames && !Macros.count(MacroName)) MacroNames->push_back(MacroName); Macros[MacroName] = std::make_pair(MacroBody, false); } } /// \brief Check the preprocessor options deserialized from the control block /// against the preprocessor options in an existing preprocessor. /// /// \param Diags If non-null, produce diagnostics for any mismatches incurred. /// \param Validate If true, validate preprocessor options. If false, allow /// macros defined by \p ExistingPPOpts to override those defined by /// \p PPOpts in SuggestedPredefines. static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts, bool Validate = true) { // Check macro definitions. MacroDefinitionsMap ASTFileMacros; collectMacroDefinitions(PPOpts, ASTFileMacros); MacroDefinitionsMap ExistingMacros; SmallVector<StringRef, 4> ExistingMacroNames; collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames); for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) { // Dig out the macro definition in the existing preprocessor options. StringRef MacroName = ExistingMacroNames[I]; std::pair<StringRef, bool> Existing = ExistingMacros[MacroName]; // Check whether we know anything about this macro name or not. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known = ASTFileMacros.find(MacroName); if (!Validate || Known == ASTFileMacros.end()) { // FIXME: Check whether this identifier was referenced anywhere in the // AST file. If so, we should reject the AST file. Unfortunately, this // information isn't in the control block. What shall we do about it? if (Existing.second) { SuggestedPredefines += "#undef "; SuggestedPredefines += MacroName.str(); SuggestedPredefines += '\n'; } else { SuggestedPredefines += "#define "; SuggestedPredefines += MacroName.str(); SuggestedPredefines += ' '; SuggestedPredefines += Existing.first.str(); SuggestedPredefines += '\n'; } continue; } // If the macro was defined in one but undef'd in the other, we have a // conflict. if (Existing.second != Known->second.second) { if (Diags) { Diags->Report(diag::err_pch_macro_def_undef) << MacroName << Known->second.second; } return true; } // If the macro was #undef'd in both, or if the macro bodies are identical, // it's fine. if (Existing.second || Existing.first == Known->second.first) continue; // The macro bodies differ; complain. if (Diags) { Diags->Report(diag::err_pch_macro_def_conflict) << MacroName << Known->second.first << Existing.first; } return true; } // Check whether we're using predefines. if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) { if (Diags) { Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines; } return true; } // Detailed record is important since it is used for the module cache hash. if (LangOpts.Modules && PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) { if (Diags) { Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord; } return true; } // Compute the #include and #include_macros lines we need. for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) { StringRef File = ExistingPPOpts.Includes[I]; if (File == ExistingPPOpts.ImplicitPCHInclude) continue; if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File) != PPOpts.Includes.end()) continue; SuggestedPredefines += "#include \""; SuggestedPredefines += File; SuggestedPredefines += "\"\n"; } for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) { StringRef File = ExistingPPOpts.MacroIncludes[I]; if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(), File) != PPOpts.MacroIncludes.end()) continue; SuggestedPredefines += "#__include_macros \""; SuggestedPredefines += File; SuggestedPredefines += "\"\n##\n"; } return false; } bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) { const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts(); return checkPreprocessorOptions(PPOpts, ExistingPPOpts, Complain? &Reader.Diags : nullptr, PP.getFileManager(), SuggestedPredefines, PP.getLangOpts()); } bool SimpleASTReaderListener::ReadPreprocessorOptions( const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) { return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), nullptr, PP.getFileManager(), SuggestedPredefines, PP.getLangOpts(), false); } /// Check the header search options deserialized from the control block /// against the header search options in an existing preprocessor. /// /// \param Diags If non-null, produce diagnostics for any mismatches incurred. static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, DiagnosticsEngine *Diags, const LangOptions &LangOpts) { if (LangOpts.Modules) { if (SpecificModuleCachePath != ExistingModuleCachePath) { if (Diags) Diags->Report(diag::err_pch_modulecache_mismatch) << SpecificModuleCachePath << ExistingModuleCachePath; return true; } } return false; } bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) { return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, PP.getHeaderSearchInfo().getModuleCachePath(), Complain ? &Reader.Diags : nullptr, PP.getLangOpts()); } void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) { PP.setCounterValue(Value); } //===----------------------------------------------------------------------===// // AST reader implementation //===----------------------------------------------------------------------===// void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership) { DeserializationListener = Listener; OwnsDeserializationListener = TakeOwnership; } unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) { return serialization::ComputeHash(Sel); } std::pair<unsigned, unsigned> ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) { using namespace llvm::support; unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); return std::make_pair(KeyLen, DataLen); } ASTSelectorLookupTrait::internal_key_type ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) { using namespace llvm::support; SelectorTable &SelTable = Reader.getContext().Selectors; unsigned N = endian::readNext<uint16_t, little, unaligned>(d); IdentifierInfo *FirstII = Reader.getLocalIdentifier( F, endian::readNext<uint32_t, little, unaligned>(d)); if (N == 0) return SelTable.getNullarySelector(FirstII); else if (N == 1) return SelTable.getUnarySelector(FirstII); SmallVector<IdentifierInfo *, 16> Args; Args.push_back(FirstII); for (unsigned I = 1; I != N; ++I) Args.push_back(Reader.getLocalIdentifier( F, endian::readNext<uint32_t, little, unaligned>(d))); return SelTable.getSelector(N, Args.data()); } ASTSelectorLookupTrait::data_type ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, unsigned DataLen) { using namespace llvm::support; data_type Result; Result.ID = Reader.getGlobalSelectorID( F, endian::readNext<uint32_t, little, unaligned>(d)); unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d); unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d); Result.InstanceBits = FullInstanceBits & 0x3; Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1; Result.FactoryBits = FullFactoryBits & 0x3; Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1; unsigned NumInstanceMethods = FullInstanceBits >> 3; unsigned NumFactoryMethods = FullFactoryBits >> 3; // Load instance methods for (unsigned I = 0; I != NumInstanceMethods; ++I) { if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( F, endian::readNext<uint32_t, little, unaligned>(d))) Result.Instance.push_back(Method); } // Load factory methods for (unsigned I = 0; I != NumFactoryMethods; ++I) { if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( F, endian::readNext<uint32_t, little, unaligned>(d))) Result.Factory.push_back(Method); } return Result; } unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) { return llvm::HashString(a); } std::pair<unsigned, unsigned> ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) { using namespace llvm::support; unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); return std::make_pair(KeyLen, DataLen); } ASTIdentifierLookupTraitBase::internal_key_type ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) { assert(n >= 2 && d[n-1] == '\0'); return StringRef((const char*) d, n-1); } /// \brief Whether the given identifier is "interesting". static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II, bool IsModule) { return II.hadMacroDefinition() || II.isPoisoned() || (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) || II.hasRevertedTokenIDToIdentifier() || (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) && II.getFETokenInfo<void>()); } static bool readBit(unsigned &Bits) { bool Value = Bits & 0x1; Bits >>= 1; return Value; } IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) { using namespace llvm::support; unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); return Reader.getGlobalIdentifierID(F, RawID >> 1); } static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) { if (!II.isFromAST()) { II.setIsFromAST(); bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr; if (isInterestingIdentifier(Reader, II, IsModule)) II.setChangedSinceDeserialization(); } } IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, const unsigned char* d, unsigned DataLen) { using namespace llvm::support; unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); bool IsInteresting = RawID & 0x01; // Wipe out the "is interesting" bit. RawID = RawID >> 1; // Build the IdentifierInfo and link the identifier ID with it. IdentifierInfo *II = KnownII; if (!II) { II = &Reader.getIdentifierTable().getOwn(k); KnownII = II; } markIdentifierFromAST(Reader, *II); Reader.markIdentifierUpToDate(II); IdentID ID = Reader.getGlobalIdentifierID(F, RawID); if (!IsInteresting) { // For uninteresting identifiers, there's nothing else to do. Just notify // the reader that we've finished loading this identifier. Reader.SetIdentifierInfo(ID, II); return II; } unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d); unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d); bool CPlusPlusOperatorKeyword = readBit(Bits); bool HasRevertedTokenIDToIdentifier = readBit(Bits); bool HasRevertedBuiltin = readBit(Bits); bool Poisoned = readBit(Bits); bool ExtensionToken = readBit(Bits); bool HadMacroDefinition = readBit(Bits); assert(Bits == 0 && "Extra bits in the identifier?"); DataLen -= 8; // Set or check the various bits in the IdentifierInfo structure. // Token IDs are read-only. if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) II->revertTokenIDToIdentifier(); if (!F.isModule()) II->setObjCOrBuiltinID(ObjCOrBuiltinID); else if (HasRevertedBuiltin && II->getBuiltinID()) { II->revertBuiltin(); assert((II->hasRevertedBuiltin() || II->getObjCOrBuiltinID() == ObjCOrBuiltinID) && "Incorrect ObjC keyword or builtin ID"); } assert(II->isExtensionToken() == ExtensionToken && "Incorrect extension token flag"); (void)ExtensionToken; if (Poisoned) II->setIsPoisoned(true); assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && "Incorrect C++ operator keyword flag"); (void)CPlusPlusOperatorKeyword; // If this identifier is a macro, deserialize the macro // definition. if (HadMacroDefinition) { uint32_t MacroDirectivesOffset = endian::readNext<uint32_t, little, unaligned>(d); DataLen -= 4; Reader.addPendingMacro(II, &F, MacroDirectivesOffset); } Reader.SetIdentifierInfo(ID, II); // Read all of the declarations visible at global scope with this // name. if (DataLen > 0) { SmallVector<uint32_t, 4> DeclIDs; for (; DataLen > 0; DataLen -= 4) DeclIDs.push_back(Reader.getGlobalDeclID( F, endian::readNext<uint32_t, little, unaligned>(d))); Reader.SetGloballyVisibleDecls(II, DeclIDs); } return II; } DeclarationNameKey::DeclarationNameKey(DeclarationName Name) : Kind(Name.getNameKind()) { switch (Kind) { case DeclarationName::Identifier: Data = (uint64_t)Name.getAsIdentifierInfo(); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); break; case DeclarationName::CXXOperatorName: Data = Name.getCXXOverloadedOperator(); break; case DeclarationName::CXXLiteralOperatorName: Data = (uint64_t)Name.getCXXLiteralIdentifier(); break; case DeclarationName::CXXDeductionGuideName: Data = (uint64_t)Name.getCXXDeductionGuideTemplate() ->getDeclName().getAsIdentifierInfo(); break; case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXUsingDirective: Data = 0; break; } } unsigned DeclarationNameKey::getHash() const { llvm::FoldingSetNodeID ID; ID.AddInteger(Kind); switch (Kind) { case DeclarationName::Identifier: case DeclarationName::CXXLiteralOperatorName: case DeclarationName::CXXDeductionGuideName: ID.AddString(((IdentifierInfo*)Data)->getName()); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: ID.AddInteger(serialization::ComputeHash(Selector(Data))); break; case DeclarationName::CXXOperatorName: ID.AddInteger((OverloadedOperatorKind)Data); break; case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXUsingDirective: break; } return ID.ComputeHash(); } ModuleFile * ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) { using namespace llvm::support; uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d); return Reader.getLocalModuleFile(F, ModuleFileID); } std::pair<unsigned, unsigned> ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) { using namespace llvm::support; unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); return std::make_pair(KeyLen, DataLen); } ASTDeclContextNameLookupTrait::internal_key_type ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { using namespace llvm::support; auto Kind = (DeclarationName::NameKind)*d++; uint64_t Data; switch (Kind) { case DeclarationName::Identifier: case DeclarationName::CXXLiteralOperatorName: case DeclarationName::CXXDeductionGuideName: Data = (uint64_t)Reader.getLocalIdentifier( F, endian::readNext<uint32_t, little, unaligned>(d)); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: Data = (uint64_t)Reader.getLocalSelector( F, endian::readNext<uint32_t, little, unaligned>( d)).getAsOpaquePtr(); break; case DeclarationName::CXXOperatorName: Data = *d++; // OverloadedOperatorKind break; case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXUsingDirective: Data = 0; break; } return DeclarationNameKey(Kind, Data); } void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val) { using namespace llvm::support; for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) { uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d); Val.insert(Reader.getGlobalDeclID(F, LocalID)); } } bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, DeclContext *DC) { assert(Offset != 0); SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(Offset); RecordData Record; StringRef Blob; unsigned Code = Cursor.ReadCode(); unsigned RecCode = Cursor.readRecord(Code, Record, &Blob); if (RecCode != DECL_CONTEXT_LEXICAL) { Error("Expected lexical block"); return true; } assert(!isa<TranslationUnitDecl>(DC) && "expected a TU_UPDATE_LEXICAL record for TU"); // If we are handling a C++ class template instantiation, we can see multiple // lexical updates for the same record. It's important that we select only one // of them, so that field numbering works properly. Just pick the first one we // see. auto &Lex = LexicalDecls[DC]; if (!Lex.first) { Lex = std::make_pair( &M, llvm::makeArrayRef( reinterpret_cast<const llvm::support::unaligned_uint32_t *>( Blob.data()), Blob.size() / 4)); } DC->setHasExternalLexicalStorage(true); return false; } bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, DeclID ID) { assert(Offset != 0); SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(Offset); RecordData Record; StringRef Blob; unsigned Code = Cursor.ReadCode(); unsigned RecCode = Cursor.readRecord(Code, Record, &Blob); if (RecCode != DECL_CONTEXT_VISIBLE) { Error("Expected visible lookup table block"); return true; } // We can't safely determine the primary context yet, so delay attaching the // lookup table until we're done with recursive deserialization. auto *Data = (const unsigned char*)Blob.data(); PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data}); return false; } void ASTReader::Error(StringRef Msg) const { Error(diag::err_fe_pch_malformed, Msg); if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { Diag(diag::note_module_cache_path) << PP.getHeaderSearchInfo().getModuleCachePath(); } } void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2) const { if (Diags.isDiagnosticInFlight()) Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2); else Diag(DiagID) << Arg1 << Arg2; } //===----------------------------------------------------------------------===// // Source Manager Deserialization //===----------------------------------------------------------------------===// /// \brief Read the line table in the source manager block. /// \returns true if there was an error. bool ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) { unsigned Idx = 0; LineTableInfo &LineTable = SourceMgr.getLineTable(); // Parse the file names std::map<int, int> FileIDs; FileIDs[-1] = -1; // For unspecified filenames. for (unsigned I = 0; Record[Idx]; ++I) { // Extract the file name auto Filename = ReadPath(F, Record, Idx); FileIDs[I] = LineTable.getLineTableFilenameID(Filename); } ++Idx; // Parse the line entries std::vector<LineEntry> Entries; while (Idx < Record.size()) { int FID = Record[Idx++]; assert(FID >= 0 && "Serialized line entries for non-local file."); // Remap FileID from 1-based old view. FID += F.SLocEntryBaseID - 1; // Extract the line entries unsigned NumEntries = Record[Idx++]; assert(NumEntries && "no line entries for file ID"); Entries.clear(); Entries.reserve(NumEntries); for (unsigned I = 0; I != NumEntries; ++I) { unsigned FileOffset = Record[Idx++]; unsigned LineNo = Record[Idx++]; int FilenameID = FileIDs[Record[Idx++]]; SrcMgr::CharacteristicKind FileKind = (SrcMgr::CharacteristicKind)Record[Idx++]; unsigned IncludeOffset = Record[Idx++]; Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, FileKind, IncludeOffset)); } LineTable.AddEntry(FileID::get(FID), Entries); } return false; } /// \brief Read a source manager block bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) { using namespace SrcMgr; BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; // Set the source-location entry cursor to the current position in // the stream. This cursor will be used to read the contents of the // source manager block initially, and then lazily read // source-location entries as needed. SLocEntryCursor = F.Stream; // The stream itself is going to skip over the source manager block. if (F.Stream.SkipBlock()) { Error("malformed block record in AST file"); return true; } // Enter the source manager block. if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) { Error("malformed source manager block record in AST file"); return true; } RecordData Record; while (true) { llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks(); switch (E.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return true; case llvm::BitstreamEntry::EndBlock: return false; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read a record. Record.clear(); StringRef Blob; switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) { default: // Default behavior: ignore. break; case SM_SLOC_FILE_ENTRY: case SM_SLOC_BUFFER_ENTRY: case SM_SLOC_EXPANSION_ENTRY: // Once we hit one of the source location entries, we're done. return false; } } } /// \brief If a header file is not found at the path that we expect it to be /// and the PCH file was moved from its original location, try to resolve the /// file by assuming that header+PCH were moved together and the header is in /// the same place relative to the PCH. static std::string resolveFileRelativeToOriginalDir(const std::string &Filename, const std::string &OriginalDir, const std::string &CurrDir) { assert(OriginalDir != CurrDir && "No point trying to resolve the file if the PCH dir didn't change"); using namespace llvm::sys; SmallString<128> filePath(Filename); fs::make_absolute(filePath); assert(path::is_absolute(OriginalDir)); SmallString<128> currPCHPath(CurrDir); path::const_iterator fileDirI = path::begin(path::parent_path(filePath)), fileDirE = path::end(path::parent_path(filePath)); path::const_iterator origDirI = path::begin(OriginalDir), origDirE = path::end(OriginalDir); // Skip the common path components from filePath and OriginalDir. while (fileDirI != fileDirE && origDirI != origDirE && *fileDirI == *origDirI) { ++fileDirI; ++origDirI; } for (; origDirI != origDirE; ++origDirI) path::append(currPCHPath, ".."); path::append(currPCHPath, fileDirI, fileDirE); path::append(currPCHPath, path::filename(Filename)); return currPCHPath.str(); } bool ASTReader::ReadSLocEntry(int ID) { if (ID == 0) return false; if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { Error("source location entry ID out-of-range for AST file"); return true; } // Local helper to read the (possibly-compressed) buffer data following the // entry record. auto ReadBuffer = [this]( BitstreamCursor &SLocEntryCursor, StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> { RecordData Record; StringRef Blob; unsigned Code = SLocEntryCursor.ReadCode(); unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob); if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { if (!llvm::zlib::isAvailable()) { Error("zlib is not available"); return nullptr; } SmallString<0> Uncompressed; if (llvm::Error E = llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) { Error("could not decompress embedded file contents: " + llvm::toString(std::move(E))); return nullptr; } return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name); } else if (RecCode == SM_SLOC_BUFFER_BLOB) { return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true); } else { Error("AST record has invalid code"); return nullptr; } }; ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second; F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]); BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; unsigned BaseOffset = F->SLocEntryBaseOffset; ++NumSLocEntriesRead; llvm::BitstreamEntry Entry = SLocEntryCursor.advance(); if (Entry.Kind != llvm::BitstreamEntry::Record) { Error("incorrectly-formatted source location entry in AST file"); return true; } RecordData Record; StringRef Blob; switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) { default: Error("incorrectly-formatted source location entry in AST file"); return true; case SM_SLOC_FILE_ENTRY: { // We will detect whether a file changed and return 'Failure' for it, but // we will also try to fail gracefully by setting up the SLocEntry. unsigned InputID = Record[4]; InputFile IF = getInputFile(*F, InputID, /*Complain=*/false); const FileEntry *File = IF.getFile(); bool OverriddenBuffer = IF.isOverridden(); // Note that we only check if a File was returned. If it was out-of-date // we have complained but we will continue creating a FileID to recover // gracefully. if (!File) return true; SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) { // This is the module's main file. IncludeLoc = getImportLocation(F); } SrcMgr::CharacteristicKind FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter, ID, BaseOffset + Record[0]); SrcMgr::FileInfo &FileInfo = const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile()); FileInfo.NumCreatedFIDs = Record[5]; if (Record[3]) FileInfo.setHasLineDirectives(); const DeclID *FirstDecl = F->FileSortedDecls + Record[6]; unsigned NumFileDecls = Record[7]; if (NumFileDecls && ContextObj) { assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?"); FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl, NumFileDecls)); } const SrcMgr::ContentCache *ContentCache = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter)); if (OverriddenBuffer && !ContentCache->BufferOverridden && ContentCache->ContentsEntry == ContentCache->OrigEntry && !ContentCache->getRawBuffer()) { auto Buffer = ReadBuffer(SLocEntryCursor, File->getName()); if (!Buffer) return true; SourceMgr.overrideFileContents(File, std::move(Buffer)); } break; } case SM_SLOC_BUFFER_ENTRY: { const char *Name = Blob.data(); unsigned Offset = Record[0]; SrcMgr::CharacteristicKind FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); if (IncludeLoc.isInvalid() && F->isModule()) { IncludeLoc = getImportLocation(F); } auto Buffer = ReadBuffer(SLocEntryCursor, Name); if (!Buffer) return true; SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID, BaseOffset + Offset, IncludeLoc); break; } case SM_SLOC_EXPANSION_ENTRY: { SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]); SourceMgr.createExpansionLoc(SpellingLoc, ReadSourceLocation(*F, Record[2]), ReadSourceLocation(*F, Record[3]), Record[4], ID, BaseOffset + Record[0]); break; } } return false; } std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) { if (ID == 0) return std::make_pair(SourceLocation(), ""); if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { Error("source location entry ID out-of-range for AST file"); return std::make_pair(SourceLocation(), ""); } // Find which module file this entry lands in. ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second; if (!M->isModule()) return std::make_pair(SourceLocation(), ""); // FIXME: Can we map this down to a particular submodule? That would be // ideal. return std::make_pair(M->ImportLoc, StringRef(M->ModuleName)); } /// \brief Find the location where the module F is imported. SourceLocation ASTReader::getImportLocation(ModuleFile *F) { if (F->ImportLoc.isValid()) return F->ImportLoc; // Otherwise we have a PCH. It's considered to be "imported" at the first // location of its includer. if (F->ImportedBy.empty() || !F->ImportedBy[0]) { // Main file is the importer. assert(SourceMgr.getMainFileID().isValid() && "missing main file"); return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); } return F->ImportedBy[0]->FirstLoc; } /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the /// specified cursor. Read the abbreviations that are at the top of the block /// and then leave the cursor pointing into the block. bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) { if (Cursor.EnterSubBlock(BlockID)) return true; while (true) { uint64_t Offset = Cursor.GetCurrentBitNo(); unsigned Code = Cursor.ReadCode(); // We expect all abbrevs to be at the start of the block. if (Code != llvm::bitc::DEFINE_ABBREV) { Cursor.JumpToBit(Offset); return false; } Cursor.ReadAbbrevRecord(); } } Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) { Token Tok; Tok.startToken(); Tok.setLocation(ReadSourceLocation(F, Record, Idx)); Tok.setLength(Record[Idx++]); if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++])) Tok.setIdentifierInfo(II); Tok.setKind((tok::TokenKind)Record[Idx++]); Tok.setFlag((Token::TokenFlags)Record[Idx++]); if (Tok.isLiteral()) { const RecordData& RD = reinterpret_cast<const RecordData&>(Record); std::string* Lit = new std::string(ReadString(RD, Idx)); TokenLiteralDataLoaded.push_back(Lit); Tok.setLiteralData(Lit->c_str()); } return Tok; } MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { BitstreamCursor &Stream = F.MacroCursor; // Keep track of where we are in the stream, then jump back there // after reading this macro. SavedStreamPosition SavedPosition(Stream); Stream.JumpToBit(Offset); RecordData Record; SmallVector<IdentifierInfo*, 16> MacroParams; MacroInfo *Macro = nullptr; while (true) { // Advance to the next record, but if we get to the end of the block, don't // pop it (removing all the abbreviations from the cursor) since we want to // be able to reseek within the block and read entries. unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd; llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return Macro; case llvm::BitstreamEntry::EndBlock: return Macro; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read a record. Record.clear(); PreprocessorRecordTypes RecType = (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record); switch (RecType) { case PP_MODULE_MACRO: case PP_MACRO_DIRECTIVE_HISTORY: return Macro; case PP_MACRO_OBJECT_LIKE: case PP_MACRO_FUNCTION_LIKE: { // If we already have a macro, that means that we've hit the end // of the definition of the macro we were looking for. We're // done. if (Macro) return Macro; unsigned NextIndex = 1; // Skip identifier ID. SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex); MacroInfo *MI = PP.AllocateMacroInfo(Loc); MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex)); MI->setIsUsed(Record[NextIndex++]); MI->setUsedForHeaderGuard(Record[NextIndex++]); if (RecType == PP_MACRO_FUNCTION_LIKE) { // Decode function-like macro info. bool isC99VarArgs = Record[NextIndex++]; bool isGNUVarArgs = Record[NextIndex++]; bool hasCommaPasting = Record[NextIndex++]; MacroParams.clear(); unsigned NumArgs = Record[NextIndex++]; for (unsigned i = 0; i != NumArgs; ++i) MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++])); // Install function-like macro info. MI->setIsFunctionLike(); if (isC99VarArgs) MI->setIsC99Varargs(); if (isGNUVarArgs) MI->setIsGNUVarargs(); if (hasCommaPasting) MI->setHasCommaPasting(); MI->setParameterList(MacroParams, PP.getPreprocessorAllocator()); } // Remember that we saw this macro last so that we add the tokens that // form its body to it. Macro = MI; if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() && Record[NextIndex]) { // We have a macro definition. Register the association PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]); PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); PreprocessingRecord::PPEntityID PPID = PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true); MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>( PPRec.getPreprocessedEntity(PPID)); if (PPDef) PPRec.RegisterMacroDefinition(Macro, PPDef); } ++NumMacrosRead; break; } case PP_TOKEN: { // If we see a TOKEN before a PP_MACRO_*, then the file is // erroneous, just pretend we didn't see this. if (!Macro) break; unsigned Idx = 0; Token Tok = ReadToken(F, Record, Idx); Macro->AddTokenToBody(Tok); break; } } } } PreprocessedEntityID ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const { if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::const_iterator I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS); assert(I != M.PreprocessedEntityRemap.end() && "Invalid index into preprocessed entity index remap"); return LocalID + I->second; } unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) { return llvm::hash_combine(ikey.Size, ikey.ModTime); } HeaderFileInfoTrait::internal_key_type HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) { internal_key_type ikey = {FE->getSize(), M.HasTimestamps ? FE->getModificationTime() : 0, FE->getName(), /*Imported*/ false}; return ikey; } bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) { if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime)) return false; if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename) return true; // Determine whether the actual files are equivalent. FileManager &FileMgr = Reader.getFileManager(); auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* { if (!Key.Imported) return FileMgr.getFile(Key.Filename); std::string Resolved = Key.Filename; Reader.ResolveImportedPath(M, Resolved); return FileMgr.getFile(Resolved); }; const FileEntry *FEA = GetFile(a); const FileEntry *FEB = GetFile(b); return FEA && FEA == FEB; } std::pair<unsigned, unsigned> HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) { using namespace llvm::support; unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d); unsigned DataLen = (unsigned) *d++; return std::make_pair(KeyLen, DataLen); } HeaderFileInfoTrait::internal_key_type HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) { using namespace llvm::support; internal_key_type ikey; ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d)); ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d)); ikey.Filename = (const char *)d; ikey.Imported = true; return ikey; } HeaderFileInfoTrait::data_type HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d, unsigned DataLen) { const unsigned char *End = d + DataLen; using namespace llvm::support; HeaderFileInfo HFI; unsigned Flags = *d++; // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. HFI.isImport |= (Flags >> 5) & 0x01; HFI.isPragmaOnce |= (Flags >> 4) & 0x01; HFI.DirInfo = (Flags >> 1) & 0x07; HFI.IndexHeaderMapHeader = Flags & 0x01; // FIXME: Find a better way to handle this. Maybe just store a // "has been included" flag? HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d), HFI.NumIncludes); HFI.ControllingMacroID = Reader.getGlobalIdentifierID( M, endian::readNext<uint32_t, little, unaligned>(d)); if (unsigned FrameworkOffset = endian::readNext<uint32_t, little, unaligned>(d)) { // The framework offset is 1 greater than the actual offset, // since 0 is used as an indicator for "no framework name". StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1); HFI.Framework = HS->getUniqueFrameworkName(FrameworkName); } assert((End - d) % 4 == 0 && "Wrong data length in HeaderFileInfo deserialization"); while (d != End) { uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d); auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3); LocalSMID >>= 2; // This header is part of a module. Associate it with the module to enable // implicit module import. SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID); Module *Mod = Reader.getSubmodule(GlobalSMID); FileManager &FileMgr = Reader.getFileManager(); ModuleMap &ModMap = Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap(); std::string Filename = key.Filename; if (key.Imported) Reader.ResolveImportedPath(M, Filename); // FIXME: This is not always the right filename-as-written, but we're not // going to use this information to rebuild the module, so it doesn't make // a lot of difference. Module::Header H = { key.Filename, FileMgr.getFile(Filename) }; ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true); HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader); } // This HeaderFileInfo was externally loaded. HFI.External = true; HFI.IsValid = true; return HFI; } void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint64_t MacroDirectivesOffset) { assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard"); PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset)); } void ASTReader::ReadDefinedMacros() { // Note that we are loading defined macros. Deserializing Macros(this); for (ModuleFile &I : llvm::reverse(ModuleMgr)) { BitstreamCursor &MacroCursor = I.MacroCursor; // If there was no preprocessor block, skip this file. if (MacroCursor.getBitcodeBytes().empty()) continue; BitstreamCursor Cursor = MacroCursor; Cursor.JumpToBit(I.MacroStartOffset); RecordData Record; while (true) { llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks(); switch (E.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return; case llvm::BitstreamEntry::EndBlock: goto NextCursor; case llvm::BitstreamEntry::Record: Record.clear(); switch (Cursor.readRecord(E.ID, Record)) { default: // Default behavior: ignore. break; case PP_MACRO_OBJECT_LIKE: case PP_MACRO_FUNCTION_LIKE: { IdentifierInfo *II = getLocalIdentifier(I, Record[0]); if (II->isOutOfDate()) updateOutOfDateIdentifier(*II); break; } case PP_TOKEN: // Ignore tokens. break; } break; } } NextCursor: ; } } namespace { /// \brief Visitor class used to look up identifirs in an AST file. class IdentifierLookupVisitor { StringRef Name; unsigned NameHash; unsigned PriorGeneration; unsigned &NumIdentifierLookups; unsigned &NumIdentifierLookupHits; IdentifierInfo *Found; public: IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, unsigned &NumIdentifierLookups, unsigned &NumIdentifierLookupHits) : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)), PriorGeneration(PriorGeneration), NumIdentifierLookups(NumIdentifierLookups), NumIdentifierLookupHits(NumIdentifierLookupHits), Found() { } bool operator()(ModuleFile &M) { // If we've already searched this module file, skip it now. if (M.Generation <= PriorGeneration) return true; ASTIdentifierLookupTable *IdTable = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; if (!IdTable) return false; ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, Found); ++NumIdentifierLookups; ASTIdentifierLookupTable::iterator Pos = IdTable->find_hashed(Name, NameHash, &Trait); if (Pos == IdTable->end()) return false; // Dereferencing the iterator has the effect of building the // IdentifierInfo node and populating it with the various // declarations it needs. ++NumIdentifierLookupHits; Found = *Pos; return true; } // \brief Retrieve the identifier info found within the module // files. IdentifierInfo *getIdentifierInfo() const { return Found; } }; } // end anonymous namespace void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) { // Note that we are loading an identifier. Deserializing AnIdentifier(this); unsigned PriorGeneration = 0; if (getContext().getLangOpts().Modules) PriorGeneration = IdentifierGeneration[&II]; // If there is a global index, look there first to determine which modules // provably do not have any results for this identifier. GlobalModuleIndex::HitSet Hits; GlobalModuleIndex::HitSet *HitsPtr = nullptr; if (!loadGlobalIndex()) { if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) { HitsPtr = &Hits; } } IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, NumIdentifierLookups, NumIdentifierLookupHits); ModuleMgr.visit(Visitor, HitsPtr); markIdentifierUpToDate(&II); } void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) { if (!II) return; II->setOutOfDate(false); // Update the generation for this identifier. if (getContext().getLangOpts().Modules) IdentifierGeneration[II] = getGenerationOrNull(); } void ASTReader::resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo) { ModuleFile &M = *PMInfo.M; BitstreamCursor &Cursor = M.MacroCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(PMInfo.MacroDirectivesOffset); struct ModuleMacroRecord { SubmoduleID SubModID; MacroInfo *MI; SmallVector<SubmoduleID, 8> Overrides; }; llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; // We expect to see a sequence of PP_MODULE_MACRO records listing exported // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete // macro histroy. RecordData Record; while (true) { llvm::BitstreamEntry Entry = Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); if (Entry.Kind != llvm::BitstreamEntry::Record) { Error("malformed block record in AST file"); return; } Record.clear(); switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) { case PP_MACRO_DIRECTIVE_HISTORY: break; case PP_MODULE_MACRO: { ModuleMacros.push_back(ModuleMacroRecord()); auto &Info = ModuleMacros.back(); Info.SubModID = getGlobalSubmoduleID(M, Record[0]); Info.MI = getMacro(getGlobalMacroID(M, Record[1])); for (int I = 2, N = Record.size(); I != N; ++I) Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I])); continue; } default: Error("malformed block record in AST file"); return; } // We found the macro directive history; that's the last record // for this macro. break; } // Module macros are listed in reverse dependency order. { std::reverse(ModuleMacros.begin(), ModuleMacros.end()); llvm::SmallVector<ModuleMacro*, 8> Overrides; for (auto &MMR : ModuleMacros) { Overrides.clear(); for (unsigned ModID : MMR.Overrides) { Module *Mod = getSubmodule(ModID); auto *Macro = PP.getModuleMacro(Mod, II); assert(Macro && "missing definition for overridden macro"); Overrides.push_back(Macro); } bool Inserted = false; Module *Owner = getSubmodule(MMR.SubModID); PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted); } } // Don't read the directive history for a module; we don't have anywhere // to put it. if (M.isModule()) return; // Deserialize the macro directives history in reverse source-order. MacroDirective *Latest = nullptr, *Earliest = nullptr; unsigned Idx = 0, N = Record.size(); while (Idx < N) { MacroDirective *MD = nullptr; SourceLocation Loc = ReadSourceLocation(M, Record, Idx); MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; switch (K) { case MacroDirective::MD_Define: { MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++])); MD = PP.AllocateDefMacroDirective(MI, Loc); break; } case MacroDirective::MD_Undefine: { MD = PP.AllocateUndefMacroDirective(Loc); break; } case MacroDirective::MD_Visibility: bool isPublic = Record[Idx++]; MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); break; } if (!Latest) Latest = MD; if (Earliest) Earliest->setPrevious(MD); Earliest = MD; } if (Latest) PP.setLoadedMacroDirective(II, Earliest, Latest); } ASTReader::InputFileInfo ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) { // Go find this input file. BitstreamCursor &Cursor = F.InputFilesCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(F.InputFileOffsets[ID-1]); unsigned Code = Cursor.ReadCode(); RecordData Record; StringRef Blob; unsigned Result = Cursor.readRecord(Code, Record, &Blob); assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE && "invalid record type for input file"); (void)Result; assert(Record[0] == ID && "Bogus stored ID or offset"); InputFileInfo R; R.StoredSize = static_cast<off_t>(Record[1]); R.StoredTime = static_cast<time_t>(Record[2]); R.Overridden = static_cast<bool>(Record[3]); R.Transient = static_cast<bool>(Record[4]); R.TopLevelModuleMap = static_cast<bool>(Record[5]); R.Filename = Blob; ResolveImportedPath(F, R.Filename); return R; } static unsigned moduleKindForDiagnostic(ModuleKind Kind); InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { // If this ID is bogus, just return an empty input file. if (ID == 0 || ID > F.InputFilesLoaded.size()) return InputFile(); // If we've already loaded this input file, return it. if (F.InputFilesLoaded[ID-1].getFile()) return F.InputFilesLoaded[ID-1]; if (F.InputFilesLoaded[ID-1].isNotFound()) return InputFile(); // Go find this input file. BitstreamCursor &Cursor = F.InputFilesCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(F.InputFileOffsets[ID-1]); InputFileInfo FI = readInputFileInfo(F, ID); off_t StoredSize = FI.StoredSize; time_t StoredTime = FI.StoredTime; bool Overridden = FI.Overridden; bool Transient = FI.Transient; StringRef Filename = FI.Filename; const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false); // If we didn't find the file, resolve it relative to the // original directory from which this AST file was created. if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() && F.OriginalDir != CurrentDir) { std::string Resolved = resolveFileRelativeToOriginalDir(Filename, F.OriginalDir, CurrentDir); if (!Resolved.empty()) File = FileMgr.getFile(Resolved); } // For an overridden file, create a virtual file with the stored // size/timestamp. if ((Overridden || Transient) && File == nullptr) File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime); if (File == nullptr) { if (Complain) { std::string ErrorStr = "could not find file '"; ErrorStr += Filename; ErrorStr += "' referenced by AST file '"; ErrorStr += F.FileName; ErrorStr += "'"; Error(ErrorStr); } // Record that we didn't find the file. F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); return InputFile(); } // Check if there was a request to override the contents of the file // that was part of the precompiled header. Overridding such a file // can lead to problems when lexing using the source locations from the // PCH. SourceManager &SM = getSourceManager(); // FIXME: Reject if the overrides are different. if ((!Overridden && !Transient) && SM.isFileOverridden(File)) { if (Complain) Error(diag::err_fe_pch_file_overridden, Filename); // After emitting the diagnostic, recover by disabling the override so // that the original file will be used. // // FIXME: This recovery is just as broken as the original state; there may // be another precompiled module that's using the overridden contents, or // we might be half way through parsing it. Instead, we should treat the // overridden contents as belonging to a separate FileEntry. SM.disableFileContentsOverride(File); // The FileEntry is a virtual file entry with the size of the contents // that would override the original contents. Set it to the original's // size/time. FileMgr.modifyFileEntry(const_cast<FileEntry*>(File), StoredSize, StoredTime); } bool IsOutOfDate = false; // For an overridden file, there is nothing to validate. if (!Overridden && // (StoredSize != File->getSize() || (StoredTime && StoredTime != File->getModificationTime() && !DisableValidation) )) { if (Complain) { // Build a list of the PCH imports that got us here (in reverse). SmallVector<ModuleFile *, 4> ImportStack(1, &F); while (ImportStack.back()->ImportedBy.size() > 0) ImportStack.push_back(ImportStack.back()->ImportedBy[0]); // The top-level PCH is stale. StringRef TopLevelPCHName(ImportStack.back()->FileName); unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind); if (DiagnosticKind == 0) Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName); else if (DiagnosticKind == 1) Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName); else Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName); // Print the import stack. if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) { Diag(diag::note_pch_required_by) << Filename << ImportStack[0]->FileName; for (unsigned I = 1; I < ImportStack.size(); ++I) Diag(diag::note_pch_required_by) << ImportStack[I-1]->FileName << ImportStack[I]->FileName; } if (!Diags.isDiagnosticInFlight()) Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; } IsOutOfDate = true; } // FIXME: If the file is overridden and we've already opened it, // issue an error (or split it into a separate FileEntry). InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate); // Note that we've loaded this input file. F.InputFilesLoaded[ID-1] = IF; return IF; } /// \brief If we are loading a relocatable PCH or module file, and the filename /// is not an absolute path, add the system or module root to the beginning of /// the file name. void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) { // Resolve relative to the base directory, if we have one. if (!M.BaseDirectory.empty()) return ResolveImportedPath(Filename, M.BaseDirectory); } void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) { if (Filename.empty() || llvm::sys::path::is_absolute(Filename)) return; SmallString<128> Buffer; llvm::sys::path::append(Buffer, Prefix, Filename); Filename.assign(Buffer.begin(), Buffer.end()); } static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { switch (ARR) { case ASTReader::Failure: return true; case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); case ASTReader::ConfigurationMismatch: return !(Caps & ASTReader::ARR_ConfigurationMismatch); case ASTReader::HadErrors: return true; case ASTReader::Success: return false; } llvm_unreachable("unknown ASTReadResult"); } ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( BitstreamCursor &Stream, unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, std::string &SuggestedPredefines) { if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) return Failure; // Read all of the records in the options block. RecordData Record; ASTReadResult Result = Success; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: case llvm::BitstreamEntry::SubBlock: return Failure; case llvm::BitstreamEntry::EndBlock: return Result; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read and process a record. Record.clear(); switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) { case LANGUAGE_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (ParseLanguageOptions(Record, Complain, Listener, AllowCompatibleConfigurationMismatch)) Result = ConfigurationMismatch; break; } case TARGET_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (ParseTargetOptions(Record, Complain, Listener, AllowCompatibleConfigurationMismatch)) Result = ConfigurationMismatch; break; } case FILE_SYSTEM_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (!AllowCompatibleConfigurationMismatch && ParseFileSystemOptions(Record, Complain, Listener)) Result = ConfigurationMismatch; break; } case HEADER_SEARCH_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (!AllowCompatibleConfigurationMismatch && ParseHeaderSearchOptions(Record, Complain, Listener)) Result = ConfigurationMismatch; break; } case PREPROCESSOR_OPTIONS: bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (!AllowCompatibleConfigurationMismatch && ParsePreprocessorOptions(Record, Complain, Listener, SuggestedPredefines)) Result = ConfigurationMismatch; break; } } } ASTReader::ASTReadResult ASTReader::ReadControlBlock(ModuleFile &F, SmallVectorImpl<ImportedModule> &Loaded, const ModuleFile *ImportedBy, unsigned ClientLoadCapabilities) { BitstreamCursor &Stream = F.Stream; ASTReadResult Result = Success; if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } // Lambda to read the unhashed control block the first time it's called. // // For PCM files, the unhashed control block cannot be read until after the // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still // need to look ahead before reading the IMPORTS record. For consistency, // this block is always read somehow (see BitstreamEntry::EndBlock). bool HasReadUnhashedControlBlock = false; auto readUnhashedControlBlockOnce = [&]() { if (!HasReadUnhashedControlBlock) { HasReadUnhashedControlBlock = true; if (ASTReadResult Result = readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities)) return Result; } return Success; }; // Read all of the records and blocks in the control block. RecordData Record; unsigned NumInputs = 0; unsigned NumUserInputs = 0; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return Failure; case llvm::BitstreamEntry::EndBlock: { // Validate the module before returning. This call catches an AST with // no module name and no imports. if (ASTReadResult Result = readUnhashedControlBlockOnce()) return Result; // Validate input files. const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); // All user input files reside at the index range [0, NumUserInputs), and // system input files reside at [NumUserInputs, NumInputs). For explicitly // loaded module files, ignore missing inputs. bool Validate = !DisableValidation && F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule; bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; Complain &= Validate; // If we are reading a module, we will create a verification timestamp, // so we verify all input files. Otherwise, verify only user input // files. unsigned N = NumUserInputs; if (ValidateSystemInputs || (HSOpts.ModulesValidateOncePerBuildSession && F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp && F.Kind == MK_ImplicitModule)) N = NumInputs; for (unsigned I = 0; I < NumInputs; ++I) { if (I == N) Complain = false; InputFile IF = getInputFile(F, I+1, Complain); if (Validate && (!IF.getFile() || IF.isOutOfDate())) return OutOfDate; } if (Listener) Listener->visitModuleFile(F.FileName, F.Kind); if (Listener && Listener->needsInputFileVisitation()) { unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs : NumUserInputs; for (unsigned I = 0; I < N; ++I) { bool IsSystem = I >= NumUserInputs; InputFileInfo FI = readInputFileInfo(F, I+1); Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden, F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule); } } return Result; } case llvm::BitstreamEntry::SubBlock: switch (Entry.ID) { case INPUT_FILES_BLOCK_ID: F.InputFilesCursor = Stream; if (Stream.SkipBlock() || // Skip with the main cursor // Read the abbreviations ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } continue; case OPTIONS_BLOCK_ID: // If we're reading the first module for this group, check its options // are compatible with ours. For modules it imports, no further checking // is required, because we checked them when we built it. if (Listener && !ImportedBy) { // Should we allow the configuration of the module file to differ from // the configuration of the current translation unit in a compatible // way? // // FIXME: Allow this for files explicitly specified with -include-pch. bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; Result = ReadOptionsBlock(Stream, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, *Listener, SuggestedPredefines); if (Result == Failure) { Error("malformed block record in AST file"); return Result; } if (DisableValidation || (AllowConfigurationMismatch && Result == ConfigurationMismatch)) Result = Success; // If we can't load the module, exit early since we likely // will rebuild the module anyway. The stream may be in the // middle of a block. if (Result != Success) return Result; } else if (Stream.SkipBlock()) { Error("malformed block record in AST file"); return Failure; } continue; default: if (Stream.SkipBlock()) { Error("malformed block record in AST file"); return Failure; } continue; } case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read and process a record. Record.clear(); StringRef Blob; switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) { case METADATA: { if (Record[0] != VERSION_MAJOR && !DisableValidation) { if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old : diag::err_pch_version_too_new); return VersionMismatch; } bool hasErrors = Record[6]; if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) { Diag(diag::err_pch_with_compiler_errors); return HadErrors; } if (hasErrors) { Diags.ErrorOccurred = true; Diags.UncompilableErrorOccurred = true; Diags.UnrecoverableErrorOccurred = true; } F.RelocatablePCH = Record[4]; // Relative paths in a relocatable PCH are relative to our sysroot. if (F.RelocatablePCH) F.BaseDirectory = isysroot.empty() ? "/" : isysroot; F.HasTimestamps = Record[5]; const std::string &CurBranch = getClangFullRepositoryVersion(); StringRef ASTBranch = Blob; if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch; return VersionMismatch; } break; } case IMPORTS: { // Validate the AST before processing any imports (otherwise, untangling // them can be error-prone and expensive). A module will have a name and // will already have been validated, but this catches the PCH case. if (ASTReadResult Result = readUnhashedControlBlockOnce()) return Result; // Load each of the imported PCH files. unsigned Idx = 0, N = Record.size(); while (Idx < N) { // Read information about the AST file. ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; // The import location will be the local one for now; we will adjust // all import locations of module imports after the global source // location info are setup, in ReadAST. SourceLocation ImportLoc = ReadUntranslatedSourceLocation(Record[Idx++]); off_t StoredSize = (off_t)Record[Idx++]; time_t StoredModTime = (time_t)Record[Idx++]; ASTFileSignature StoredSignature = { {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++], (uint32_t)Record[Idx++], (uint32_t)Record[Idx++], (uint32_t)Record[Idx++]}}}; auto ImportedFile = ReadPath(F, Record, Idx); // Check if ImportedFile exists on disk if (!llvm::sys::fs::is_directory(ImportedFile)) { StringRef ModuleName = llvm::sys::path::filename(ImportedFile.c_str()); ModuleName.consume_back(".pcm"); // Get clang::Module pointer by looking up the module name clang::Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName, true, true); if (M) { std::string Path = PP.getHeaderSearchInfo().getModuleFileName(M->Name, PP.getHeaderSearchInfo().getModuleMap().getModuleMapFileForUniquing(M)->getName(), true); // FIXME: Add a hash comparison to check if ImportedFile's hash and the // new Modules Path's hash matches or not. if (!Path.empty()) ImportedFile = Path; } } // If our client can't cope with us being out of date, we can't cope with // our dependency being missing. unsigned Capabilities = ClientLoadCapabilities; if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Capabilities &= ~ARR_Missing; // Load the AST file. auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded, StoredSize, StoredModTime, StoredSignature, Capabilities); // If we diagnosed a problem, produce a backtrace. if (isDiagnosedResult(Result, Capabilities)) Diag(diag::note_module_file_imported_by) << F.FileName << !F.ModuleName.empty() << F.ModuleName; switch (Result) { case Failure: return Failure; // If we have to ignore the dependency, we'll have to ignore this too. case Missing: case OutOfDate: return OutOfDate; case VersionMismatch: return VersionMismatch; case ConfigurationMismatch: return ConfigurationMismatch; case HadErrors: return HadErrors; case Success: break; } } break; } case ORIGINAL_FILE: F.OriginalSourceFileID = FileID::get(Record[0]); F.ActualOriginalSourceFileName = Blob; F.OriginalSourceFileName = F.ActualOriginalSourceFileName; ResolveImportedPath(F, F.OriginalSourceFileName); break; case ORIGINAL_FILE_ID: F.OriginalSourceFileID = FileID::get(Record[0]); break; case ORIGINAL_PCH_DIR: F.OriginalDir = Blob; break; case MODULE_NAME: F.ModuleName = Blob; if (Listener) Listener->ReadModuleName(F.ModuleName); // Validate the AST as soon as we have a name so we can exit early on // failure. if (ASTReadResult Result = readUnhashedControlBlockOnce()) return Result; break; case MODULE_DIRECTORY: { assert(!F.ModuleName.empty() && "MODULE_DIRECTORY found before MODULE_NAME"); // If we've already loaded a module map file covering this module, we may // have a better path for it (relative to the current build). Module *M = PP.getHeaderSearchInfo().lookupModule( F.ModuleName, /*AllowSearch*/ true, /*AllowExtraModuleMapSearch*/ true); if (M && M->Directory) { // If we're implicitly loading a module, the base directory can't // change between the build and use. // Don't emit module relocation error if we have -fno-validate-pch if (!PP.getPreprocessorOpts().DisablePCHValidation && F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { const DirectoryEntry *BuildDir = PP.getFileManager().getDirectory(Blob); if (!BuildDir || BuildDir != M->Directory) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_imported_module_relocated) << F.ModuleName << Blob << M->Directory->getName(); return OutOfDate; } } F.BaseDirectory = M->Directory->getName(); } else { F.BaseDirectory = Blob; } break; } case MODULE_MAP_FILE: if (ASTReadResult Result = ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) return Result; break; case INPUT_FILE_OFFSETS: NumInputs = Record[0]; NumUserInputs = Record[1]; F.InputFileOffsets = (const llvm::support::unaligned_uint64_t *)Blob.data(); F.InputFilesLoaded.resize(NumInputs); F.NumUserInputFiles = NumUserInputs; break; } } } ASTReader::ASTReadResult ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { BitstreamCursor &Stream = F.Stream; if (Stream.EnterSubBlock(AST_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } // Read all of the records and blocks for the AST file. RecordData Record; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: Error("error at end of module block in AST file"); return Failure; case llvm::BitstreamEntry::EndBlock: { // Outside of C++, we do not store a lookup map for the translation unit. // Instead, mark it as needing a lookup map to be built if this module // contains any declarations lexically within it (which it always does!). // This usually has no cost, since we very rarely need the lookup map for // the translation unit outside C++. if (ASTContext *Ctx = ContextObj) { DeclContext *DC = Ctx->getTranslationUnitDecl(); if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus) DC->setMustBuildLookupTable(); } return Success; } case llvm::BitstreamEntry::SubBlock: switch (Entry.ID) { case DECLTYPES_BLOCK_ID: // We lazily load the decls block, but we want to set up the // DeclsCursor cursor to point into it. Clone our current bitcode // cursor to it, enter the block and read the abbrevs in that block. // With the main cursor, we just skip over it. F.DeclsCursor = Stream; if (Stream.SkipBlock() || // Skip with the main cursor. // Read the abbrevs. ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } break; case PREPROCESSOR_BLOCK_ID: F.MacroCursor = Stream; if (!PP.getExternalSource()) PP.setExternalSource(this); if (Stream.SkipBlock() || ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); break; case PREPROCESSOR_DETAIL_BLOCK_ID: F.PreprocessorDetailCursor = Stream; if (Stream.SkipBlock() || ReadBlockAbbrevs(F.PreprocessorDetailCursor, PREPROCESSOR_DETAIL_BLOCK_ID)) { Error("malformed preprocessor detail record in AST file"); return Failure; } F.PreprocessorDetailStartOffset = F.PreprocessorDetailCursor.GetCurrentBitNo(); if (!PP.getPreprocessingRecord()) PP.createPreprocessingRecord(); if (!PP.getPreprocessingRecord()->getExternalSource()) PP.getPreprocessingRecord()->SetExternalSource(*this); break; case SOURCE_MANAGER_BLOCK_ID: if (ReadSourceManagerBlock(F)) return Failure; break; case SUBMODULE_BLOCK_ID: if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities)) return Result; break; case COMMENTS_BLOCK_ID: { BitstreamCursor C = Stream; if (Stream.SkipBlock() || ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) { Error("malformed comments block in AST file"); return Failure; } CommentsCursors.push_back(std::make_pair(C, &F)); break; } default: if (Stream.SkipBlock()) { Error("malformed block record in AST file"); return Failure; } break; } continue; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read and process a record. Record.clear(); StringRef Blob; auto RecordType = (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob); // If we're not loading an AST context, we don't care about most records. if (!ContextObj) { switch (RecordType) { case IDENTIFIER_TABLE: case IDENTIFIER_OFFSET: case INTERESTING_IDENTIFIERS: case STATISTICS: case PP_CONDITIONAL_STACK: case PP_COUNTER_VALUE: case SOURCE_LOCATION_OFFSETS: case MODULE_OFFSET_MAP: case SOURCE_MANAGER_LINE_TABLE: case SOURCE_LOCATION_PRELOADS: case PPD_ENTITIES_OFFSETS: case HEADER_SEARCH_TABLE: case IMPORTED_MODULES: case MACRO_OFFSET: break; default: continue; } } switch (RecordType) { default: // Default behavior: ignore. break; case TYPE_OFFSET: { if (F.LocalNumTypes != 0) { Error("duplicate TYPE_OFFSET record in AST file"); return Failure; } F.TypeOffsets = (const uint32_t *)Blob.data(); F.LocalNumTypes = Record[0]; unsigned LocalBaseTypeIndex = Record[1]; F.BaseTypeIndex = getTotalNumTypes(); if (F.LocalNumTypes > 0) { // Introduce the global -> local mapping for types within this module. GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F)); // Introduce the local -> global mapping for types within this module. F.TypeRemap.insertOrReplace( std::make_pair(LocalBaseTypeIndex, F.BaseTypeIndex - LocalBaseTypeIndex)); NumTypesLoaded += F.LocalNumTypes; } break; } case DECL_OFFSET: { if (F.LocalNumDecls != 0) { Error("duplicate DECL_OFFSET record in AST file"); return Failure; } F.DeclOffsets = (const DeclOffset *)Blob.data(); F.LocalNumDecls = Record[0]; unsigned LocalBaseDeclID = Record[1]; F.BaseDeclID = getTotalNumDecls(); if (F.LocalNumDecls > 0) { // Introduce the global -> local mapping for declarations within this // module. GlobalDeclMap.insert( std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F)); // Introduce the local -> global mapping for declarations within this // module. F.DeclRemap.insertOrReplace( std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID)); // Introduce the global -> local mapping for declarations within this // module. F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID; NumDeclsLoaded += F.LocalNumDecls; } break; } case TU_UPDATE_LEXICAL: { DeclContext *TU = ContextObj->getTranslationUnitDecl(); LexicalContents Contents( reinterpret_cast<const llvm::support::unaligned_uint32_t *>( Blob.data()), static_cast<unsigned int>(Blob.size() / 4)); TULexicalDecls.push_back(std::make_pair(&F, Contents)); TU->setHasExternalLexicalStorage(true); break; } case UPDATE_VISIBLE: { unsigned Idx = 0; serialization::DeclID ID = ReadDeclID(F, Record, Idx); auto *Data = (const unsigned char*)Blob.data(); PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data}); // If we've already loaded the decl, perform the updates when we finish // loading this block. if (Decl *D = GetExistingDecl(ID)) PendingUpdateRecords.push_back( PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); break; } case IDENTIFIER_TABLE: F.IdentifierTableData = Blob.data(); if (Record[0]) { F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( (const unsigned char *)F.IdentifierTableData + Record[0], (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t), (const unsigned char *)F.IdentifierTableData, ASTIdentifierLookupTrait(*this, F)); PP.getIdentifierTable().setExternalIdentifierLookup(this); } break; case IDENTIFIER_OFFSET: { if (F.LocalNumIdentifiers != 0) { Error("duplicate IDENTIFIER_OFFSET record in AST file"); return Failure; } F.IdentifierOffsets = (const uint32_t *)Blob.data(); F.LocalNumIdentifiers = Record[0]; unsigned LocalBaseIdentifierID = Record[1]; F.BaseIdentifierID = getTotalNumIdentifiers(); if (F.LocalNumIdentifiers > 0) { // Introduce the global -> local mapping for identifiers within this // module. GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1, &F)); // Introduce the local -> global mapping for identifiers within this // module. F.IdentifierRemap.insertOrReplace( std::make_pair(LocalBaseIdentifierID, F.BaseIdentifierID - LocalBaseIdentifierID)); IdentifiersLoaded.resize(IdentifiersLoaded.size() + F.LocalNumIdentifiers); } break; } case INTERESTING_IDENTIFIERS: F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end()); break; case EAGERLY_DESERIALIZED_DECLS: // FIXME: Skip reading this record if our ASTConsumer doesn't care // about "interesting" decls (for instance, if we're building a module). for (unsigned I = 0, N = Record.size(); I != N; ++I) EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); break; case MODULAR_CODEGEN_DECLS: // FIXME: Skip reading this record if our ASTConsumer doesn't care about // them (ie: if we're not codegenerating this module). if (F.Kind == MK_MainFile) for (unsigned I = 0, N = Record.size(); I != N; ++I) EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); break; case SPECIAL_TYPES: if (SpecialTypes.empty()) { for (unsigned I = 0, N = Record.size(); I != N; ++I) SpecialTypes.push_back(getGlobalTypeID(F, Record[I])); break; } if (SpecialTypes.size() != Record.size()) { Error("invalid special-types record"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; ++I) { serialization::TypeID ID = getGlobalTypeID(F, Record[I]); if (!SpecialTypes[I]) SpecialTypes[I] = ID; // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate // merge step? } break; case STATISTICS: TotalNumStatements += Record[0]; TotalNumMacros += Record[1]; TotalLexicalDeclContexts += Record[2]; TotalVisibleDeclContexts += Record[3]; break; case UNUSED_FILESCOPED_DECLS: for (unsigned I = 0, N = Record.size(); I != N; ++I) UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I])); break; case DELEGATING_CTORS: for (unsigned I = 0, N = Record.size(); I != N; ++I) DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I])); break; case WEAK_UNDECLARED_IDENTIFIERS: if (Record.size() % 4 != 0) { Error("invalid weak identifiers record"); return Failure; } // FIXME: Ignore weak undeclared identifiers from non-original PCH // files. This isn't the way to do it :) WeakUndeclaredIdentifiers.clear(); // Translate the weak, undeclared identifiers into global IDs. for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { WeakUndeclaredIdentifiers.push_back( getGlobalIdentifierID(F, Record[I++])); WeakUndeclaredIdentifiers.push_back( getGlobalIdentifierID(F, Record[I++])); WeakUndeclaredIdentifiers.push_back( ReadSourceLocation(F, Record, I).getRawEncoding()); WeakUndeclaredIdentifiers.push_back(Record[I++]); } break; case SELECTOR_OFFSETS: { F.SelectorOffsets = (const uint32_t *)Blob.data(); F.LocalNumSelectors = Record[0]; unsigned LocalBaseSelectorID = Record[1]; F.BaseSelectorID = getTotalNumSelectors(); if (F.LocalNumSelectors > 0) { // Introduce the global -> local mapping for selectors within this // module. GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F)); // Introduce the local -> global mapping for selectors within this // module. F.SelectorRemap.insertOrReplace( std::make_pair(LocalBaseSelectorID, F.BaseSelectorID - LocalBaseSelectorID)); SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); } break; } case METHOD_POOL: F.SelectorLookupTableData = (const unsigned char *)Blob.data(); if (Record[0]) F.SelectorLookupTable = ASTSelectorLookupTable::Create( F.SelectorLookupTableData + Record[0], F.SelectorLookupTableData, ASTSelectorLookupTrait(*this, F)); TotalNumMethodPoolEntries += Record[1]; break; case REFERENCED_SELECTOR_POOL: if (!Record.empty()) { for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { ReferencedSelectorsData.push_back(getGlobalSelectorID(F, Record[Idx++])); ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx). getRawEncoding()); } } break; case PP_CONDITIONAL_STACK: if (!Record.empty()) { SmallVector<PPConditionalInfo, 4> ConditionalStack; for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { auto Loc = ReadSourceLocation(F, Record, Idx); bool WasSkipping = Record[Idx++]; bool FoundNonSkip = Record[Idx++]; bool FoundElse = Record[Idx++]; ConditionalStack.push_back( {Loc, WasSkipping, FoundNonSkip, FoundElse}); } PP.setReplayablePreambleConditionalStack(ConditionalStack); } break; case PP_COUNTER_VALUE: if (!Record.empty() && Listener) Listener->ReadCounter(F, Record[0]); break; case FILE_SORTED_DECLS: F.FileSortedDecls = (const DeclID *)Blob.data(); F.NumFileSortedDecls = Record[0]; break; case SOURCE_LOCATION_OFFSETS: { F.SLocEntryOffsets = (const uint32_t *)Blob.data(); F.LocalNumSLocEntries = Record[0]; unsigned SLocSpaceSize = Record[1]; std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, SLocSpaceSize); if (!F.SLocEntryBaseID) { Error("ran out of source locations"); break; } // Make our entry in the range map. BaseID is negative and growing, so // we invert it. Because we invert it, though, we need the other end of // the range. unsigned RangeStart = unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0); GlobalSLocOffsetMap.insert( std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset - SLocSpaceSize,&F)); // Initialize the remapping table. // Invalid stays invalid. F.SLocRemap.insertOrReplace(std::make_pair(0U, 0)); // This module. Base was 2 when being compiled. F.SLocRemap.insertOrReplace(std::make_pair(2U, static_cast<int>(F.SLocEntryBaseOffset - 2))); TotalNumSLocEntries += F.LocalNumSLocEntries; break; } case MODULE_OFFSET_MAP: F.ModuleOffsetMap = Blob; break; case SOURCE_MANAGER_LINE_TABLE: if (ParseLineTable(F, Record)) return Failure; break; case SOURCE_LOCATION_PRELOADS: { // Need to transform from the local view (1-based IDs) to the global view, // which is based off F.SLocEntryBaseID. if (!F.PreloadSLocEntries.empty()) { Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file"); return Failure; } F.PreloadSLocEntries.swap(Record); break; } case EXT_VECTOR_DECLS: for (unsigned I = 0, N = Record.size(); I != N; ++I) ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I])); break; case VTABLE_USES: if (Record.size() % 3 != 0) { Error("Invalid VTABLE_USES record"); return Failure; } // Later tables overwrite earlier ones. // FIXME: Modules will have some trouble with this. This is clearly not // the right way to do this. VTableUses.clear(); for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { VTableUses.push_back(getGlobalDeclID(F, Record[Idx++])); VTableUses.push_back( ReadSourceLocation(F, Record, Idx).getRawEncoding()); VTableUses.push_back(Record[Idx++]); } break; case PENDING_IMPLICIT_INSTANTIATIONS: if (PendingInstantiations.size() % 2 != 0) { Error("Invalid existing PendingInstantiations"); return Failure; } if (Record.size() % 2 != 0) { Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++])); PendingInstantiations.push_back( ReadSourceLocation(F, Record, I).getRawEncoding()); } break; case SEMA_DECL_REFS: if (Record.size() != 3) { Error("Invalid SEMA_DECL_REFS block"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; ++I) SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I])); break; case PPD_ENTITIES_OFFSETS: { F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); assert(Blob.size() % sizeof(PPEntityOffset) == 0); F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); unsigned LocalBasePreprocessedEntityID = Record[0]; unsigned StartingID; if (!PP.getPreprocessingRecord()) PP.createPreprocessingRecord(); if (!PP.getPreprocessingRecord()->getExternalSource()) PP.getPreprocessingRecord()->SetExternalSource(*this); StartingID = PP.getPreprocessingRecord() ->allocateLoadedEntities(F.NumPreprocessedEntities); F.BasePreprocessedEntityID = StartingID; if (F.NumPreprocessedEntities > 0) { // Introduce the global -> local mapping for preprocessed entities in // this module. GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F)); // Introduce the local -> global mapping for preprocessed entities in // this module. F.PreprocessedEntityRemap.insertOrReplace( std::make_pair(LocalBasePreprocessedEntityID, F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); } break; } case DECL_UPDATE_OFFSETS: { if (Record.size() % 2 != 0) { Error("invalid DECL_UPDATE_OFFSETS block in AST file"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; I += 2) { GlobalDeclID ID = getGlobalDeclID(F, Record[I]); DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1])); // If we've already loaded the decl, perform the updates when we finish // loading this block. if (Decl *D = GetExistingDecl(ID)) PendingUpdateRecords.push_back( PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); } break; } case OBJC_CATEGORIES_MAP: { if (F.LocalNumObjCCategoriesInMap != 0) { Error("duplicate OBJC_CATEGORIES_MAP record in AST file"); return Failure; } F.LocalNumObjCCategoriesInMap = Record[0]; F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); break; } case OBJC_CATEGORIES: F.ObjCCategories.swap(Record); break; case CUDA_SPECIAL_DECL_REFS: // Later tables overwrite earlier ones. // FIXME: Modules will have trouble with this. CUDASpecialDeclRefs.clear(); for (unsigned I = 0, N = Record.size(); I != N; ++I) CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I])); break; case HEADER_SEARCH_TABLE: { F.HeaderFileInfoTableData = Blob.data(); F.LocalNumHeaderFileInfos = Record[1]; if (Record[0]) { F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create( (const unsigned char *)F.HeaderFileInfoTableData + Record[0], (const unsigned char *)F.HeaderFileInfoTableData, HeaderFileInfoTrait(*this, F, &PP.getHeaderSearchInfo(), Blob.data() + Record[2])); PP.getHeaderSearchInfo().SetExternalSource(this); if (!PP.getHeaderSearchInfo().getExternalLookup()) PP.getHeaderSearchInfo().SetExternalLookup(this); } break; } case FP_PRAGMA_OPTIONS: // Later tables overwrite earlier ones. FPPragmaOptions.swap(Record); break; case OPENCL_EXTENSIONS: for (unsigned I = 0, E = Record.size(); I != E; ) { auto Name = ReadString(Record, I); auto &Opt = OpenCLExtensions.OptMap[Name]; Opt.Supported = Record[I++] != 0; Opt.Enabled = Record[I++] != 0; Opt.Avail = Record[I++]; Opt.Core = Record[I++]; } break; case OPENCL_EXTENSION_TYPES: for (unsigned I = 0, E = Record.size(); I != E;) { auto TypeID = static_cast<::TypeID>(Record[I++]); auto *Type = GetType(TypeID).getTypePtr(); auto NumExt = static_cast<unsigned>(Record[I++]); for (unsigned II = 0; II != NumExt; ++II) { auto Ext = ReadString(Record, I); OpenCLTypeExtMap[Type].insert(Ext); } } break; case OPENCL_EXTENSION_DECLS: for (unsigned I = 0, E = Record.size(); I != E;) { auto DeclID = static_cast<::DeclID>(Record[I++]); auto *Decl = GetDecl(DeclID); auto NumExt = static_cast<unsigned>(Record[I++]); for (unsigned II = 0; II != NumExt; ++II) { auto Ext = ReadString(Record, I); OpenCLDeclExtMap[Decl].insert(Ext); } } break; case TENTATIVE_DEFINITIONS: for (unsigned I = 0, N = Record.size(); I != N; ++I) TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I])); break; case KNOWN_NAMESPACES: for (unsigned I = 0, N = Record.size(); I != N; ++I) KnownNamespaces.push_back(getGlobalDeclID(F, Record[I])); break; case UNDEFINED_BUT_USED: if (UndefinedButUsed.size() % 2 != 0) { Error("Invalid existing UndefinedButUsed"); return Failure; } if (Record.size() % 2 != 0) { Error("invalid undefined-but-used record"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++])); UndefinedButUsed.push_back( ReadSourceLocation(F, Record, I).getRawEncoding()); } break; case DELETE_EXPRS_TO_ANALYZE: for (unsigned I = 0, N = Record.size(); I != N;) { DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++])); const uint64_t Count = Record[I++]; DelayedDeleteExprs.push_back(Count); for (uint64_t C = 0; C < Count; ++C) { DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding()); bool IsArrayForm = Record[I++] == 1; DelayedDeleteExprs.push_back(IsArrayForm); } } break; case IMPORTED_MODULES: { if (!F.isModule()) { // If we aren't loading a module (which has its own exports), make // all of the imported modules visible. // FIXME: Deal with macros-only imports. for (unsigned I = 0, N = Record.size(); I != N; /**/) { unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]); SourceLocation Loc = ReadSourceLocation(F, Record, I); if (GlobalID) { ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc)); if (DeserializationListener) DeserializationListener->ModuleImportRead(GlobalID, Loc); } } } break; } case MACRO_OFFSET: { if (F.LocalNumMacros != 0) { Error("duplicate MACRO_OFFSET record in AST file"); return Failure; } F.MacroOffsets = (const uint32_t *)Blob.data(); F.LocalNumMacros = Record[0]; unsigned LocalBaseMacroID = Record[1]; F.BaseMacroID = getTotalNumMacros(); if (F.LocalNumMacros > 0) { // Introduce the global -> local mapping for macros within this module. GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F)); // Introduce the local -> global mapping for macros within this module. F.MacroRemap.insertOrReplace( std::make_pair(LocalBaseMacroID, F.BaseMacroID - LocalBaseMacroID)); NumMacrosLoaded += F.LocalNumMacros; } break; } case LATE_PARSED_TEMPLATE: { LateParsedTemplates.append(Record.begin(), Record.end()); break; } case OPTIMIZE_PRAGMA_OPTIONS: if (Record.size() != 1) { Error("invalid pragma optimize record"); return Failure; } OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]); break; case MSSTRUCT_PRAGMA_OPTIONS: if (Record.size() != 1) { Error("invalid pragma ms_struct record"); return Failure; } PragmaMSStructState = Record[0]; break; case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: if (Record.size() != 2) { Error("invalid pragma ms_struct record"); return Failure; } PragmaMSPointersToMembersState = Record[0]; PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]); break; case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: for (unsigned I = 0, N = Record.size(); I != N; ++I) UnusedLocalTypedefNameCandidates.push_back( getGlobalDeclID(F, Record[I])); break; case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: if (Record.size() != 1) { Error("invalid cuda pragma options record"); return Failure; } ForceCUDAHostDeviceDepth = Record[0]; break; case PACK_PRAGMA_OPTIONS: { if (Record.size() < 3) { Error("invalid pragma pack record"); return Failure; } PragmaPackCurrentValue = Record[0]; PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]); unsigned NumStackEntries = Record[2]; unsigned Idx = 3; // Reset the stack when importing a new module. PragmaPackStack.clear(); for (unsigned I = 0; I < NumStackEntries; ++I) { PragmaPackStackEntry Entry; Entry.Value = Record[Idx++]; Entry.Location = ReadSourceLocation(F, Record[Idx++]); PragmaPackStrings.push_back(ReadString(Record, Idx)); Entry.SlotLabel = PragmaPackStrings.back(); PragmaPackStack.push_back(Entry); } break; } } } } void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { assert(!F.ModuleOffsetMap.empty() && "no module offset map to read"); // Additional remapping information. const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); F.ModuleOffsetMap = StringRef(); // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders. if (F.SLocRemap.find(0) == F.SLocRemap.end()) { F.SLocRemap.insert(std::make_pair(0U, 0)); F.SLocRemap.insert(std::make_pair(2U, 1)); } // Continuous range maps we may be updating in our module. typedef ContinuousRangeMap<uint32_t, int, 2>::Builder RemapBuilder; RemapBuilder SLocRemap(F.SLocRemap); RemapBuilder IdentifierRemap(F.IdentifierRemap); RemapBuilder MacroRemap(F.MacroRemap); RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); RemapBuilder SubmoduleRemap(F.SubmoduleRemap); RemapBuilder SelectorRemap(F.SelectorRemap); RemapBuilder DeclRemap(F.DeclRemap); RemapBuilder TypeRemap(F.TypeRemap); while (Data < DataEnd) { // FIXME: Looking up dependency modules by filename is horrible. using namespace llvm::support; uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data); StringRef Name = StringRef((const char*)Data, Len); Data += Len; ModuleFile *OM = ModuleMgr.lookup(Name); // Check if ModuleFile exists if (!OM) { StringRef ModuleName = llvm::sys::path::filename(Name); ModuleName.consume_back(".pcm"); clang::Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName, true, true); std::string Path; // If module definition exists in modulemap, search the modulepath in HeaderSearchInfo if (M) Path = PP.getHeaderSearchInfo().getModuleFileName(M->Name, PP.getHeaderSearchInfo().getModuleMap().getModuleMapFileForUniquing(M)->getName(), true); StringRef NewName = StringRef(Path); OM = ModuleMgr.lookup(NewName); if (!OM) { std::string Msg = "SourceLocation remap refers to unknown module, cannot find "; Msg.append(std::string(NewName)); Error(Msg); return; } } uint32_t SLocOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t IdentifierIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t MacroIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t PreprocessedEntityIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t SubmoduleIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t SelectorIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t DeclIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t TypeIndexOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t None = std::numeric_limits<uint32_t>::max(); auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, RemapBuilder &Remap) { if (Offset != None) Remap.insert(std::make_pair(Offset, static_cast<int>(BaseOffset - Offset))); }; mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap); mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap); mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, PreprocessedEntityRemap); mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap); mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap); // Global -> local mappings. F.GlobalToLocalDeclIDs[OM] = DeclIDOffset; } } ASTReader::ASTReadResult ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, const ModuleFile *ImportedBy, unsigned ClientLoadCapabilities) { unsigned Idx = 0; F.ModuleMapPath = ReadPath(F, Record, Idx); // Try to resolve ModuleName in the current header search context and // verify that it is found in the same module map file as we saved. If the // top-level AST file is a main file, skip this check because there is no // usable header search context. assert(!F.ModuleName.empty() && "MODULE_NAME should come before MODULE_MAP_FILE"); if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { // An implicitly-loaded module file should have its module listed in some // module map file that we've already loaded. Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); auto &Map = PP.getHeaderSearchInfo().getModuleMap(); const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr; // Don't emit module relocation error if we have -fno-validate-pch if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) { assert(ImportedBy && "top-level import should be verified"); if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) { if (auto *ASTFE = M ? M->getASTFile() : nullptr) // This module was defined by an imported (explicit) module. Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName << ASTFE->getName(); else // This module was built with a different module map. Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName << ImportedBy->FileName << F.ModuleMapPath; } return OutOfDate; } assert(M->Name == F.ModuleName && "found module with different name"); // Check the primary module map file. const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath); if (!PP.getPreprocessorOpts().DisablePCHValidation && (StoredModMap == nullptr || StoredModMap != ModMap)) { assert(ModMap && "found module is missing module map file"); assert(ImportedBy && "top-level import should be verified"); if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_imported_module_modmap_changed) << F.ModuleName << ImportedBy->FileName << ModMap->getName() << F.ModuleMapPath; return OutOfDate; } llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps; for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { // FIXME: we should use input files rather than storing names. std::string Filename = ReadPath(F, Record, Idx); const FileEntry *F = FileMgr.getFile(Filename, false, false); if (F == nullptr) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Error("could not find file '" + Filename +"' referenced by AST file"); return OutOfDate; } AdditionalStoredMaps.insert(F); } // Check any additional module map files (e.g. module.private.modulemap) // that are not in the pcm. if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { for (const FileEntry *ModMap : *AdditionalModuleMaps) { // Remove files that match // Note: SmallPtrSet::erase is really remove if (!AdditionalStoredMaps.erase(ModMap)) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_module_different_modmap) << F.ModuleName << /*new*/0 << ModMap->getName(); return OutOfDate; } } } // Check any additional module map files that are in the pcm, but not // found in header search. Cases that match are already removed. for (const FileEntry *ModMap : AdditionalStoredMaps) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_module_different_modmap) << F.ModuleName << /*not new*/1 << ModMap->getName(); return OutOfDate; } } if (Listener) Listener->ReadModuleMapFile(F.ModuleMapPath); return Success; } /// \brief Move the given method to the back of the global list of methods. static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { // Find the entry for this selector in the method pool. Sema::GlobalMethodPool::iterator Known = S.MethodPool.find(Method->getSelector()); if (Known == S.MethodPool.end()) return; // Retrieve the appropriate method list. ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first : Known->second.second; bool Found = false; for (ObjCMethodList *List = &Start; List; List = List->getNext()) { if (!Found) { if (List->getMethod() == Method) { Found = true; } else { // Keep searching. continue; } } if (List->getNext()) List->setMethod(List->getNext()->getMethod()); else List->setMethod(Method); } } void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?"); for (Decl *D : Names) { bool wasHidden = D->isHidden(); D->setVisibleDespiteOwningModule(); if (wasHidden && SemaObj) { if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) { moveMethodToBackOfGlobalList(*SemaObj, Method); } } } } void ASTReader::makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc) { llvm::SmallPtrSet<Module *, 4> Visited; SmallVector<Module *, 4> Stack; Stack.push_back(Mod); while (!Stack.empty()) { Mod = Stack.pop_back_val(); if (NameVisibility <= Mod->NameVisibility) { // This module already has this level of visibility (or greater), so // there is nothing more to do. continue; } if (!Mod->isAvailable()) { // Modules that aren't available cannot be made visible. continue; } // Update the module's name visibility. Mod->NameVisibility = NameVisibility; // If we've already deserialized any names from this module, // mark them as visible. HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod); if (Hidden != HiddenNamesMap.end()) { auto HiddenNames = std::move(*Hidden); HiddenNamesMap.erase(Hidden); makeNamesVisible(HiddenNames.second, HiddenNames.first); assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() && "making names visible added hidden names"); } // Push any exported modules onto the stack to be marked as visible. SmallVector<Module *, 16> Exports; Mod->getExportedModules(Exports); for (SmallVectorImpl<Module *>::iterator I = Exports.begin(), E = Exports.end(); I != E; ++I) { Module *Exported = *I; if (Visited.insert(Exported).second) Stack.push_back(Exported); } } } /// We've merged the definition \p MergedDef into the existing definition /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made /// visible. void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef) { // FIXME: This doesn't correctly handle the case where MergedDef is visible // in modules other than its owning module. We should instead give the // ASTContext a list of merged definitions for Def. if (Def->isHidden()) { // If MergedDef is visible or becomes visible, make the definition visible. if (!MergedDef->isHidden()) Def->setVisibleDespiteOwningModule(); else if (getContext().getLangOpts().ModulesLocalVisibility) { getContext().mergeDefinitionIntoModule( Def, MergedDef->getImportedOwningModule(), /*NotifyListeners*/ false); PendingMergedDefinitionsToDeduplicate.insert(Def); } else { auto SubmoduleID = MergedDef->getOwningModuleID(); assert(SubmoduleID && "hidden definition in no module"); HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def); } } } bool ASTReader::loadGlobalIndex() { if (GlobalIndex) return false; if (TriedLoadingGlobalIndex || !UseGlobalIndex || !PP.getLangOpts().Modules) return true; // Try to load the global index. TriedLoadingGlobalIndex = true; StringRef ModuleCachePath = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result = GlobalModuleIndex::readIndex(ModuleCachePath); if (!Result.first) return true; GlobalIndex.reset(Result.first); ModuleMgr.setGlobalIndex(GlobalIndex.get()); return false; } bool ASTReader::isGlobalIndexUnavailable() const { return PP.getLangOpts().Modules && UseGlobalIndex && !hasGlobalIndex() && TriedLoadingGlobalIndex; } static void updateModuleTimestamp(ModuleFile &MF) { // Overwrite the timestamp file contents so that file's mtime changes. std::string TimestampFilename = MF.getTimestampFilename(); std::error_code EC; llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text); if (EC) return; OS << "Timestamp file\n"; OS.close(); OS.clear_error(); // Avoid triggering a fatal error. } /// \brief Given a cursor at the start of an AST file, scan ahead and drop the /// cursor into the start of the given block ID, returning false on success and /// true on failure. static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { while (true) { llvm::BitstreamEntry Entry = Cursor.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: case llvm::BitstreamEntry::EndBlock: return true; case llvm::BitstreamEntry::Record: // Ignore top-level records. Cursor.skipRecord(Entry.ID); break; case llvm::BitstreamEntry::SubBlock: if (Entry.ID == BlockID) { if (Cursor.EnterSubBlock(BlockID)) return true; // Found it! return false; } if (Cursor.SkipBlock()) return true; } } } ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, SmallVectorImpl<ImportedSubmodule> *Imported) { llvm::SaveAndRestore<SourceLocation> SetCurImportLocRAII(CurrentImportLoc, ImportLoc); // Defer any pending actions until we get to the end of reading the AST file. Deserializing AnASTFile(this); // Bump the generation number. unsigned PreviousGeneration = 0; if (ContextObj) PreviousGeneration = incrementGeneration(*ContextObj); unsigned NumModules = ModuleMgr.size(); SmallVector<ImportedModule, 4> Loaded; switch (ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc, /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(), ClientLoadCapabilities)) { case Failure: case Missing: case OutOfDate: case VersionMismatch: case ConfigurationMismatch: case HadErrors: { llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet; for (const ImportedModule &IM : Loaded) LoadedSet.insert(IM.Mod); ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet, PP.getLangOpts().Modules ? &PP.getHeaderSearchInfo().getModuleMap() : nullptr); // If we find that any modules are unusable, the global index is going // to be out-of-date. Just remove it. GlobalIndex.reset(); ModuleMgr.setGlobalIndex(nullptr); return ReadResult; } case Success: break; } // Here comes stuff that we only do once the entire chain is loaded. // Load the AST blocks of all of the modules that we loaded. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(), MEnd = Loaded.end(); M != MEnd; ++M) { ModuleFile &F = *M->Mod; // Read the AST block. if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities)) return Result; // Read the extension blocks. while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) { if (ASTReadResult Result = ReadExtensionBlock(F)) return Result; } // Once read, set the ModuleFile bit base offset and update the size in // bits of all files we've seen. F.GlobalBitOffset = TotalModulesSizeInBits; TotalModulesSizeInBits += F.SizeInBits; GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F)); // Preload SLocEntries. for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) { int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID; // Load it through the SourceManager and don't call ReadSLocEntry() // directly because the entry may have already been loaded in which case // calling ReadSLocEntry() directly would trigger an assertion in // SourceManager. SourceMgr.getLoadedSLocEntryByID(Index); } // Map the original source file ID into the ID space of the current // compilation. if (F.OriginalSourceFileID.isValid()) { F.OriginalSourceFileID = FileID::get( F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1); } // Preload all the pending interesting identifiers by marking them out of // date. for (auto Offset : F.PreloadIdentifierOffsets) { const unsigned char *Data = reinterpret_cast<const unsigned char *>( F.IdentifierTableData + Offset); ASTIdentifierLookupTrait Trait(*this, F); auto KeyDataLen = Trait.ReadKeyDataLength(Data); auto Key = Trait.ReadKey(Data, KeyDataLen.first); auto &II = PP.getIdentifierTable().getOwn(Key); II.setOutOfDate(true); // Mark this identifier as being from an AST file so that we can track // whether we need to serialize it. markIdentifierFromAST(*this, II); // Associate the ID with the identifier so that the writer can reuse it. auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first); SetIdentifierInfo(ID, &II); } } // Setup the import locations and notify the module manager that we've // committed to these module files. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(), MEnd = Loaded.end(); M != MEnd; ++M) { ModuleFile &F = *M->Mod; ModuleMgr.moduleFileAccepted(&F); // Set the import location. F.DirectImportLoc = ImportLoc; // FIXME: We assume that locations from PCH / preamble do not need // any translation. if (!M->ImportedBy) F.ImportLoc = M->ImportLoc; else F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc); } if (!PP.getLangOpts().CPlusPlus || (Type != MK_ImplicitModule && Type != MK_ExplicitModule && Type != MK_PrebuiltModule)) { // Mark all of the identifiers in the identifier table as being out of date, // so that various accessors know to check the loaded modules when the // identifier is used. // // For C++ modules, we don't need information on many identifiers (just // those that provide macros or are poisoned), so we mark all of // the interesting ones via PreloadIdentifierOffsets. for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(), IdEnd = PP.getIdentifierTable().end(); Id != IdEnd; ++Id) Id->second->setOutOfDate(true); } // Mark selectors as out of date. for (auto Sel : SelectorGeneration) SelectorOutOfDate[Sel.first] = true; // Resolve any unresolved module exports. for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID); Module *ResolvedMod = getSubmodule(GlobalID); switch (Unresolved.Kind) { case UnresolvedModuleRef::Conflict: if (ResolvedMod) { Module::Conflict Conflict; Conflict.Other = ResolvedMod; Conflict.Message = Unresolved.String.str(); Unresolved.Mod->Conflicts.push_back(Conflict); } continue; case UnresolvedModuleRef::Import: if (ResolvedMod) Unresolved.Mod->Imports.insert(ResolvedMod); continue; case UnresolvedModuleRef::Export: if (ResolvedMod || Unresolved.IsWildcard) Unresolved.Mod->Exports.push_back( Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); continue; } } UnresolvedModuleRefs.clear(); if (Imported) Imported->append(ImportedModules.begin(), ImportedModules.end()); // FIXME: How do we load the 'use'd modules? They may not be submodules. // Might be unnecessary as use declarations are only used to build the // module itself. if (ContextObj) InitializeContext(); if (SemaObj) UpdateSema(); if (DeserializationListener) DeserializationListener->ReaderInitialized(this); ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); if (PrimaryModule.OriginalSourceFileID.isValid()) { // If this AST file is a precompiled preamble, then set the // preamble file ID of the source manager to the file source file // from which the preamble was built. if (Type == MK_Preamble) { SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); } else if (Type == MK_MainFile) { SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); } } // For any Objective-C class definitions we have already loaded, make sure // that we load any additional categories. if (ContextObj) { for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), ObjCClassesLoaded[I], PreviousGeneration); } } if (PP.getHeaderSearchInfo() .getHeaderSearchOpts() .ModulesValidateOncePerBuildSession) { // Now we are certain that the module and all modules it depends on are // up to date. Create or update timestamp files for modules that are // located in the module cache (not for PCH files that could be anywhere // in the filesystem). for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { ImportedModule &M = Loaded[I]; if (M.Mod->Kind == MK_ImplicitModule) { updateModuleTimestamp(*M.Mod); } } } return Success; } static ASTFileSignature readASTFileSignature(StringRef PCH); /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'. static bool startsWithASTFileMagic(BitstreamCursor &Stream) { return Stream.canSkipToPos(4) && Stream.Read(8) == 'C' && Stream.Read(8) == 'P' && Stream.Read(8) == 'C' && Stream.Read(8) == 'H'; } static unsigned moduleKindForDiagnostic(ModuleKind Kind) { switch (Kind) { case MK_PCH: return 0; // PCH case MK_ImplicitModule: case MK_ExplicitModule: case MK_PrebuiltModule: return 1; // module case MK_MainFile: case MK_Preamble: return 2; // main source file } llvm_unreachable("unknown module kind"); } ASTReader::ASTReadResult ASTReader::ReadASTCore(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities) { ModuleFile *M; std::string ErrorStr; ModuleManager::AddModuleResult AddResult = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, getGenerationOrNull(), ExpectedSize, ExpectedModTime, ExpectedSignature, readASTFileSignature, M, ErrorStr); switch (AddResult) { case ModuleManager::AlreadyLoaded: return Success; case ModuleManager::NewlyLoaded: // Load module file below. break; case ModuleManager::Missing: // The module file was missing; if the client can handle that, return // it. if (ClientLoadCapabilities & ARR_Missing) return Missing; // Otherwise, return an error. Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() << ErrorStr; return Failure; case ModuleManager::OutOfDate: // We couldn't load the module file because it is out-of-date. If the // client can handle out-of-date, return it. if (ClientLoadCapabilities & ARR_OutOfDate) return OutOfDate; // Otherwise, return an error. Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() << ErrorStr; return Failure; } assert(M && "Missing module file"); // FIXME: This seems rather a hack. Should CurrentDir be part of the // module? if (FileName != "-") { CurrentDir = llvm::sys::path::parent_path(FileName); if (CurrentDir.empty()) CurrentDir = "."; } ModuleFile &F = *M; BitstreamCursor &Stream = F.Stream; Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer)); F.SizeInBits = F.Buffer->getBufferSize() * 8; // Sniff for the signature. if (!startsWithASTFileMagic(Stream)) { Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type) << FileName; return Failure; } // This is used for compatibility with older PCH formats. bool HaveReadControlBlock = false; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: case llvm::BitstreamEntry::Record: case llvm::BitstreamEntry::EndBlock: Error("invalid record at top-level of AST file"); return Failure; case llvm::BitstreamEntry::SubBlock: break; } switch (Entry.ID) { case CONTROL_BLOCK_ID: HaveReadControlBlock = true; switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { case Success: // Check that we didn't try to load a non-module AST file as a module. // // FIXME: Should we also perform the converse check? Loading a module as // a PCH file sort of works, but it's a bit wonky. if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || Type == MK_PrebuiltModule) && F.ModuleName.empty()) { auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; if (Result != OutOfDate || (ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_module_file_not_module) << FileName; return Result; } break; case Failure: return Failure; case Missing: return Missing; case OutOfDate: return OutOfDate; case VersionMismatch: return VersionMismatch; case ConfigurationMismatch: return ConfigurationMismatch; case HadErrors: return HadErrors; } break; case AST_BLOCK_ID: if (!HaveReadControlBlock) { if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) Diag(diag::err_pch_version_too_old); return VersionMismatch; } // Record that we've loaded this module. Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc)); return Success; case UNHASHED_CONTROL_BLOCK_ID: // This block is handled using look-ahead during ReadControlBlock. We // shouldn't get here! Error("malformed block record in AST file"); return Failure; default: if (Stream.SkipBlock()) { Error("malformed block record in AST file"); return Failure; } break; } } return Success; } ASTReader::ASTReadResult ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, unsigned ClientLoadCapabilities) { const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; ASTReadResult Result = readUnhashedControlBlockImpl( &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, Listener.get(), WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); // If F was directly imported by another module, it's implicitly validated by // the importing module. if (DisableValidation || WasImportedBy || (AllowConfigurationMismatch && Result == ConfigurationMismatch)) return Success; if (Result == Failure) { Error("malformed block record in AST file"); return Failure; } if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { // If this module has already been finalized in the PCMCache, we're stuck // with it; we can only load a single version of each module. // // This can happen when a module is imported in two contexts: in one, as a // user module; in another, as a system module (due to an import from // another module marked with the [system] flag). It usually indicates a // bug in the module map: this module should also be marked with [system]. // // If -Wno-system-headers (the default), and the first import is as a // system module, then validation will fail during the as-user import, // since -Werror flags won't have been validated. However, it's reasonable // to treat this consistently as a system module. // // If -Wsystem-headers, the PCM on disk was built with // -Wno-system-headers, and the first import is as a user module, then // validation will fail during the as-system import since the PCM on disk // doesn't guarantee that -Werror was respected. However, the -Werror // flags were checked during the initial as-user import. if (PCMCache.isBufferFinal(F.FileName)) { Diag(diag::warn_module_system_bit_conflict) << F.FileName; return Success; } } return Result; } ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener, bool ValidateDiagnosticOptions) { // Initialize a stream. BitstreamCursor Stream(StreamData); // Sniff for the signature. if (!startsWithASTFileMagic(Stream)) return Failure; // Scan for the UNHASHED_CONTROL_BLOCK_ID block. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) return Failure; // Read all of the records in the options block. RecordData Record; ASTReadResult Result = Success; while (1) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: case llvm::BitstreamEntry::SubBlock: return Failure; case llvm::BitstreamEntry::EndBlock: return Result; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read and process a record. Record.clear(); switch ( (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) { case SIGNATURE: { if (F) std::copy(Record.begin(), Record.end(), F->Signature.data()); break; } case DIAGNOSTIC_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; if (Listener && ValidateDiagnosticOptions && !AllowCompatibleConfigurationMismatch && ParseDiagnosticOptions(Record, Complain, *Listener)) Result = OutOfDate; // Don't return early. Read the signature. break; } case DIAG_PRAGMA_MAPPINGS: if (!F) break; if (F->PragmaDiagMappings.empty()) F->PragmaDiagMappings.swap(Record); else F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(), Record.begin(), Record.end()); break; } } } /// Parse a record and blob containing module file extension metadata. static bool parseModuleFileExtensionMetadata( const SmallVectorImpl<uint64_t> &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata) { if (Record.size() < 4) return true; Metadata.MajorVersion = Record[0]; Metadata.MinorVersion = Record[1]; unsigned BlockNameLen = Record[2]; unsigned UserInfoLen = Record[3]; if (BlockNameLen + UserInfoLen > Blob.size()) return true; Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, Blob.data() + BlockNameLen + UserInfoLen); return false; } ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) { BitstreamCursor &Stream = F.Stream; RecordData Record; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: if (Stream.SkipBlock()) return Failure; continue; case llvm::BitstreamEntry::EndBlock: return Success; case llvm::BitstreamEntry::Error: return HadErrors; case llvm::BitstreamEntry::Record: break; } Record.clear(); StringRef Blob; unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); switch (RecCode) { case EXTENSION_METADATA: { ModuleFileExtensionMetadata Metadata; if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) return Failure; // Find a module file extension with this block name. auto Known = ModuleFileExtensions.find(Metadata.BlockName); if (Known == ModuleFileExtensions.end()) break; // Form a reader. if (auto Reader = Known->second->createExtensionReader(Metadata, *this, F, Stream)) { F.ExtensionReaders.push_back(std::move(Reader)); } break; } } } return Success; } void ASTReader::InitializeContext() { assert(ContextObj && "no context to initialize"); ASTContext &Context = *ContextObj; // If there's a listener, notify them that we "read" the translation unit. if (DeserializationListener) DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, Context.getTranslationUnitDecl()); // FIXME: Find a better way to deal with collisions between these // built-in types. Right now, we just ignore the problem. // Load the special types. if (SpecialTypes.size() >= NumSpecialTypeIDs) { if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { if (!Context.CFConstantStringTypeDecl) Context.setCFConstantStringType(GetType(String)); } if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) { QualType FileType = GetType(File); if (FileType.isNull()) { Error("FILE type is NULL"); return; } if (!Context.FILEDecl) { if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) Context.setFILEDecl(Typedef->getDecl()); else { const TagType *Tag = FileType->getAs<TagType>(); if (!Tag) { Error("Invalid FILE type in AST file"); return; } Context.setFILEDecl(Tag->getDecl()); } } } if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { QualType Jmp_bufType = GetType(Jmp_buf); if (Jmp_bufType.isNull()) { Error("jmp_buf type is NULL"); return; } if (!Context.jmp_bufDecl) { if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) Context.setjmp_bufDecl(Typedef->getDecl()); else { const TagType *Tag = Jmp_bufType->getAs<TagType>(); if (!Tag) { Error("Invalid jmp_buf type in AST file"); return; } Context.setjmp_bufDecl(Tag->getDecl()); } } } if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { QualType Sigjmp_bufType = GetType(Sigjmp_buf); if (Sigjmp_bufType.isNull()) { Error("sigjmp_buf type is NULL"); return; } if (!Context.sigjmp_bufDecl) { if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) Context.setsigjmp_bufDecl(Typedef->getDecl()); else { const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); assert(Tag && "Invalid sigjmp_buf type in AST file"); Context.setsigjmp_bufDecl(Tag->getDecl()); } } } if (unsigned ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { if (Context.ObjCIdRedefinitionType.isNull()) Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef); } if (unsigned ObjCClassRedef = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { if (Context.ObjCClassRedefinitionType.isNull()) Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef); } if (unsigned ObjCSelRedef = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { if (Context.ObjCSelRedefinitionType.isNull()) Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef); } if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { QualType Ucontext_tType = GetType(Ucontext_t); if (Ucontext_tType.isNull()) { Error("ucontext_t type is NULL"); return; } if (!Context.ucontext_tDecl) { if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) Context.setucontext_tDecl(Typedef->getDecl()); else { const TagType *Tag = Ucontext_tType->getAs<TagType>(); assert(Tag && "Invalid ucontext_t type in AST file"); Context.setucontext_tDecl(Tag->getDecl()); } } } } ReadPragmaDiagnosticMappings(Context.getDiagnostics()); // If there were any CUDA special declarations, deserialize them. if (!CUDASpecialDeclRefs.empty()) { assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); Context.setcudaConfigureCallDecl( cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); } // Re-export any modules that were imported by a non-module AST file. // FIXME: This does not make macro-only imports visible again. for (auto &Import : ImportedModules) { if (Module *Imported = getSubmodule(Import.ID)) { makeModuleVisible(Imported, Module::AllVisible, /*ImportLoc=*/Import.ImportLoc); if (Import.ImportLoc.isValid()) PP.makeModuleVisible(Imported, Import.ImportLoc); // FIXME: should we tell Sema to make the module visible too? } } ImportedModules.clear(); } void ASTReader::finalizeForWriting() { // Nothing to do for now. } /// \brief Reads and return the signature record from \p PCH's control block, or /// else returns 0. static ASTFileSignature readASTFileSignature(StringRef PCH) { BitstreamCursor Stream(PCH); if (!startsWithASTFileMagic(Stream)) return ASTFileSignature(); // Scan for the UNHASHED_CONTROL_BLOCK_ID block. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) return ASTFileSignature(); // Scan for SIGNATURE inside the diagnostic options block. ASTReader::RecordData Record; while (true) { llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); if (Entry.Kind != llvm::BitstreamEntry::Record) return ASTFileSignature(); Record.clear(); StringRef Blob; if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob)) return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2], (uint32_t)Record[3], (uint32_t)Record[4]}}}; } } /// \brief Retrieve the name of the original source file name /// directly from the AST file, without actually loading the AST /// file. std::string ASTReader::getOriginalSourceFile( const std::string &ASTFileName, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { // Open the AST file. auto Buffer = FileMgr.getBufferForFile(ASTFileName); if (!Buffer) { Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << Buffer.getError().message(); return std::string(); } // Initialize the stream BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer)); // Sniff for the signature. if (!startsWithASTFileMagic(Stream)) { Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName; return std::string(); } // Scan for the CONTROL_BLOCK_ID block. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) { Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; return std::string(); } // Scan for ORIGINAL_FILE inside the control block. RecordData Record; while (true) { llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); if (Entry.Kind == llvm::BitstreamEntry::EndBlock) return std::string(); if (Entry.Kind != llvm::BitstreamEntry::Record) { Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; return std::string(); } Record.clear(); StringRef Blob; if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE) return Blob.str(); } } namespace { class SimplePCHValidator : public ASTReaderListener { const LangOptions &ExistingLangOpts; const TargetOptions &ExistingTargetOpts; const PreprocessorOptions &ExistingPPOpts; std::string ExistingModuleCachePath; FileManager &FileMgr; public: SimplePCHValidator(const LangOptions &ExistingLangOpts, const TargetOptions &ExistingTargetOpts, const PreprocessorOptions &ExistingPPOpts, StringRef ExistingModuleCachePath, FileManager &FileMgr) : ExistingLangOpts(ExistingLangOpts), ExistingTargetOpts(ExistingTargetOpts), ExistingPPOpts(ExistingPPOpts), ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) { } bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override { return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr, AllowCompatibleDifferences); } bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override { return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr, AllowCompatibleDifferences); } bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override { return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, ExistingModuleCachePath, nullptr, ExistingLangOpts); } bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override { return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr, SuggestedPredefines, ExistingLangOpts); } }; } // end anonymous namespace bool ASTReader::readASTFileControlBlock( StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions) { // Open the AST file. // FIXME: This allows use of the VFS; we do not allow use of the // VFS when actually loading a module. auto Buffer = FileMgr.getBufferForFile(Filename); if (!Buffer) { return true; } // Initialize the stream StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer); BitstreamCursor Stream(Bytes); // Sniff for the signature. if (!startsWithASTFileMagic(Stream)) return true; // Scan for the CONTROL_BLOCK_ID block. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) return true; bool NeedsInputFiles = Listener.needsInputFileVisitation(); bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); bool NeedsImports = Listener.needsImportVisitation(); BitstreamCursor InputFilesCursor; RecordData Record; std::string ModuleDir; bool DoneWithControlBlock = false; while (!DoneWithControlBlock) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: { switch (Entry.ID) { case OPTIONS_BLOCK_ID: { std::string IgnoredSuggestedPredefines; if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate, /*AllowCompatibleConfigurationMismatch*/ false, Listener, IgnoredSuggestedPredefines) != Success) return true; break; } case INPUT_FILES_BLOCK_ID: InputFilesCursor = Stream; if (Stream.SkipBlock() || (NeedsInputFiles && ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))) return true; break; default: if (Stream.SkipBlock()) return true; break; } continue; } case llvm::BitstreamEntry::EndBlock: DoneWithControlBlock = true; break; case llvm::BitstreamEntry::Error: return true; case llvm::BitstreamEntry::Record: break; } if (DoneWithControlBlock) break; Record.clear(); StringRef Blob; unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); switch ((ControlRecordTypes)RecCode) { case METADATA: { if (Record[0] != VERSION_MAJOR) return true; if (Listener.ReadFullVersionInformation(Blob)) return true; break; } case MODULE_NAME: Listener.ReadModuleName(Blob); break; case MODULE_DIRECTORY: ModuleDir = Blob; break; case MODULE_MAP_FILE: { unsigned Idx = 0; auto Path = ReadString(Record, Idx); ResolveImportedPath(Path, ModuleDir); Listener.ReadModuleMapFile(Path); break; } case INPUT_FILE_OFFSETS: { if (!NeedsInputFiles) break; unsigned NumInputFiles = Record[0]; unsigned NumUserFiles = Record[1]; const uint64_t *InputFileOffs = (const uint64_t *)Blob.data(); for (unsigned I = 0; I != NumInputFiles; ++I) { // Go find this input file. bool isSystemFile = I >= NumUserFiles; if (isSystemFile && !NeedsSystemInputFiles) break; // the rest are system input files BitstreamCursor &Cursor = InputFilesCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(InputFileOffs[I]); unsigned Code = Cursor.ReadCode(); RecordData Record; StringRef Blob; bool shouldContinue = false; switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) { case INPUT_FILE: bool Overridden = static_cast<bool>(Record[3]); std::string Filename = Blob; ResolveImportedPath(Filename, ModuleDir); shouldContinue = Listener.visitInputFile( Filename, isSystemFile, Overridden, /*IsExplicitModule*/false); break; } if (!shouldContinue) break; } break; } case IMPORTS: { if (!NeedsImports) break; unsigned Idx = 0, N = Record.size(); while (Idx < N) { // Read information about the AST file. Idx += 5; // ImportLoc, Size, ModTime, Signature std::string Filename = ReadString(Record, Idx); ResolveImportedPath(Filename, ModuleDir); Listener.visitImport(Filename); } break; } default: // No other validation to perform. break; } } // Look for module file extension blocks, if requested. if (FindModuleFileExtensions) { BitstreamCursor SavedStream = Stream; while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) { bool DoneWithExtensionBlock = false; while (!DoneWithExtensionBlock) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: if (Stream.SkipBlock()) return true; continue; case llvm::BitstreamEntry::EndBlock: DoneWithExtensionBlock = true; continue; case llvm::BitstreamEntry::Error: return true; case llvm::BitstreamEntry::Record: break; } Record.clear(); StringRef Blob; unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); switch (RecCode) { case EXTENSION_METADATA: { ModuleFileExtensionMetadata Metadata; if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) return true; Listener.readModuleFileExtension(Metadata); break; } } } } Stream = SavedStream; } // Scan for the UNHASHED_CONTROL_BLOCK_ID block. if (readUnhashedControlBlockImpl( nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate, /*AllowCompatibleConfigurationMismatch*/ false, &Listener, ValidateDiagnosticOptions) != Success) return true; return false; } bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath) { SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, ExistingModuleCachePath, FileMgr); return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr, /*FindModuleFileExtensions=*/false, validator, /*ValidateDiagnosticOptions=*/true); } ASTReader::ASTReadResult ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { // Enter the submodule block. if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) { Error("malformed submodule block record in AST file"); return Failure; } ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); bool First = true; Module *CurrentModule = nullptr; Module::ModuleKind ModuleKind = Module::ModuleMapModule; RecordData Record; while (true) { llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return Failure; case llvm::BitstreamEntry::EndBlock: return Success; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read a record. StringRef Blob; Record.clear(); auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob); if ((Kind == SUBMODULE_METADATA) != First) { Error("submodule metadata record should be at beginning of block"); return Failure; } First = false; // Submodule information is only valid if we have a current module. // FIXME: Should we error on these cases? if (!CurrentModule && Kind != SUBMODULE_METADATA && Kind != SUBMODULE_DEFINITION) continue; switch (Kind) { default: // Default behavior: ignore. break; case SUBMODULE_DEFINITION: { if (Record.size() < 8) { Error("malformed module definition"); return Failure; } StringRef Name = Blob; unsigned Idx = 0; SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]); SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]); bool IsFramework = Record[Idx++]; bool IsExplicit = Record[Idx++]; bool IsSystem = Record[Idx++]; bool IsExternC = Record[Idx++]; bool InferSubmodules = Record[Idx++]; bool InferExplicitSubmodules = Record[Idx++]; bool InferExportWildcard = Record[Idx++]; bool ConfigMacrosExhaustive = Record[Idx++]; Module *ParentModule = nullptr; if (Parent) ParentModule = getSubmodule(Parent); // Retrieve this (sub)module from the module map, creating it if // necessary. CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit) .first; // FIXME: set the definition loc for CurrentModule, or call // ModMap.setInferredModuleAllowedBy() SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; if (GlobalIndex >= SubmodulesLoaded.size() || SubmodulesLoaded[GlobalIndex]) { Error("too many submodules"); return Failure; } if (!ParentModule) { if (const FileEntry *CurFile = CurrentModule->getASTFile()) { // Don't emit module relocation error if we have -fno-validate-pch if (!PP.getPreprocessorOpts().DisablePCHValidation && CurFile != F.File) { if (!Diags.isDiagnosticInFlight()) { Diag(diag::err_module_file_conflict) << CurrentModule->getTopLevelModuleName() << CurFile->getName() << F.File->getName(); } return Failure; } } CurrentModule->setASTFile(F.File); CurrentModule->PresumedModuleMapFile = F.ModuleMapPath; } CurrentModule->Kind = ModuleKind; CurrentModule->Signature = F.Signature; CurrentModule->IsFromModuleFile = true; CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; CurrentModule->IsExternC = IsExternC; CurrentModule->InferSubmodules = InferSubmodules; CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; CurrentModule->InferExportWildcard = InferExportWildcard; CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; if (DeserializationListener) DeserializationListener->ModuleRead(GlobalID, CurrentModule); SubmodulesLoaded[GlobalIndex] = CurrentModule; // Clear out data that will be replaced by what is in the module file. CurrentModule->LinkLibraries.clear(); CurrentModule->ConfigMacros.clear(); CurrentModule->UnresolvedConflicts.clear(); CurrentModule->Conflicts.clear(); // The module is available unless it's missing a requirement; relevant // requirements will be (re-)added by SUBMODULE_REQUIRES records. // Missing headers that were present when the module was built do not // make it unavailable -- if we got this far, this must be an explicitly // imported module file. CurrentModule->Requirements.clear(); CurrentModule->MissingHeaders.clear(); CurrentModule->IsMissingRequirement = ParentModule && ParentModule->IsMissingRequirement; CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement; break; } case SUBMODULE_UMBRELLA_HEADER: { std::string Filename = Blob; ResolveImportedPath(F, Filename); if (auto *Umbrella = PP.getFileManager().getFile(Filename)) { if (!CurrentModule->getUmbrellaHeader()) ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob); else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Error("mismatched umbrella headers in submodule"); return OutOfDate; } } break; } case SUBMODULE_HEADER: case SUBMODULE_EXCLUDED_HEADER: case SUBMODULE_PRIVATE_HEADER: // We lazily associate headers with their modules via the HeaderInfo table. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead // of complete filenames or remove it entirely. break; case SUBMODULE_TEXTUAL_HEADER: case SUBMODULE_PRIVATE_TEXTUAL_HEADER: // FIXME: Textual headers are not marked in the HeaderInfo table. Load // them here. break; case SUBMODULE_TOPHEADER: { CurrentModule->addTopHeaderFilename(Blob); break; } case SUBMODULE_UMBRELLA_DIR: { std::string Dirname = Blob; ResolveImportedPath(F, Dirname); if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) { if (!CurrentModule->getUmbrellaDir()) ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob); else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Error("mismatched umbrella directories in submodule"); return OutOfDate; } } break; } case SUBMODULE_METADATA: { F.BaseSubmoduleID = getTotalNumSubmodules(); F.LocalNumSubmodules = Record[0]; unsigned LocalBaseSubmoduleID = Record[1]; if (F.LocalNumSubmodules > 0) { // Introduce the global -> local mapping for submodules within this // module. GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F)); // Introduce the local -> global mapping for submodules within this // module. F.SubmoduleRemap.insertOrReplace( std::make_pair(LocalBaseSubmoduleID, F.BaseSubmoduleID - LocalBaseSubmoduleID)); SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules); } ModuleKind = (Module::ModuleKind)Record[2]; break; } case SUBMODULE_IMPORTS: { for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { UnresolvedModuleRef Unresolved; Unresolved.File = &F; Unresolved.Mod = CurrentModule; Unresolved.ID = Record[Idx]; Unresolved.Kind = UnresolvedModuleRef::Import; Unresolved.IsWildcard = false; UnresolvedModuleRefs.push_back(Unresolved); } break; } case SUBMODULE_EXPORTS: { for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) { UnresolvedModuleRef Unresolved; Unresolved.File = &F; Unresolved.Mod = CurrentModule; Unresolved.ID = Record[Idx]; Unresolved.Kind = UnresolvedModuleRef::Export; Unresolved.IsWildcard = Record[Idx + 1]; UnresolvedModuleRefs.push_back(Unresolved); } // Once we've loaded the set of exports, there's no reason to keep // the parsed, unresolved exports around. CurrentModule->UnresolvedExports.clear(); break; } case SUBMODULE_REQUIRES: { CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(), PP.getTargetInfo()); break; } case SUBMODULE_LINK_LIBRARY: CurrentModule->LinkLibraries.push_back( Module::LinkLibrary(Blob, Record[0])); break; case SUBMODULE_CONFIG_MACRO: CurrentModule->ConfigMacros.push_back(Blob.str()); break; case SUBMODULE_CONFLICT: { UnresolvedModuleRef Unresolved; Unresolved.File = &F; Unresolved.Mod = CurrentModule; Unresolved.ID = Record[0]; Unresolved.Kind = UnresolvedModuleRef::Conflict; Unresolved.IsWildcard = false; Unresolved.String = Blob; UnresolvedModuleRefs.push_back(Unresolved); break; } case SUBMODULE_INITIALIZERS: if (!ContextObj) break; SmallVector<uint32_t, 16> Inits; for (auto &ID : Record) Inits.push_back(getGlobalDeclID(F, ID)); ContextObj->addLazyModuleInitializers(CurrentModule, Inits); break; } } } /// \brief Parse the record that corresponds to a LangOptions data /// structure. /// /// This routine parses the language options from the AST file and then gives /// them to the AST listener if one is set. /// /// \returns true if the listener deems the file unacceptable, false otherwise. bool ASTReader::ParseLanguageOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, bool AllowCompatibleDifferences) { LangOptions LangOpts; unsigned Idx = 0; #define LANGOPT(Name, Bits, Default, Description) \ LangOpts.Name = Record[Idx++]; #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++])); #include "clang/Basic/LangOptions.def" #define SANITIZER(NAME, ID) \ LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]); #include "clang/Basic/Sanitizers.def" for (unsigned N = Record[Idx++]; N; --N) LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx)); ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++]; VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx); LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion); LangOpts.CurrentModule = ReadString(Record, Idx); // Comment options. for (unsigned N = Record[Idx++]; N; --N) { LangOpts.CommentOpts.BlockCommandNames.push_back( ReadString(Record, Idx)); } LangOpts.CommentOpts.ParseAllComments = Record[Idx++]; // OpenMP offloading options. for (unsigned N = Record[Idx++]; N; --N) { LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx))); } LangOpts.OMPHostIRFile = ReadString(Record, Idx); return Listener.ReadLanguageOptions(LangOpts, Complain, AllowCompatibleDifferences); } bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, bool AllowCompatibleDifferences) { unsigned Idx = 0; TargetOptions TargetOpts; TargetOpts.Triple = ReadString(Record, Idx); TargetOpts.CPU = ReadString(Record, Idx); TargetOpts.ABI = ReadString(Record, Idx); for (unsigned N = Record[Idx++]; N; --N) { TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx)); } for (unsigned N = Record[Idx++]; N; --N) { TargetOpts.Features.push_back(ReadString(Record, Idx)); } return Listener.ReadTargetOptions(TargetOpts, Complain, AllowCompatibleDifferences); } bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener) { IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions); unsigned Idx = 0; #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++]; #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ DiagOpts->set##Name(static_cast<Type>(Record[Idx++])); #include "clang/Basic/DiagnosticOptions.def" for (unsigned N = Record[Idx++]; N; --N) DiagOpts->Warnings.push_back(ReadString(Record, Idx)); for (unsigned N = Record[Idx++]; N; --N) DiagOpts->Remarks.push_back(ReadString(Record, Idx)); return Listener.ReadDiagnosticOptions(DiagOpts, Complain); } bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener) { FileSystemOptions FSOpts; unsigned Idx = 0; FSOpts.WorkingDir = ReadString(Record, Idx); return Listener.ReadFileSystemOptions(FSOpts, Complain); } bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener) { HeaderSearchOptions HSOpts; unsigned Idx = 0; HSOpts.Sysroot = ReadString(Record, Idx); // Include entries. for (unsigned N = Record[Idx++]; N; --N) { std::string Path = ReadString(Record, Idx); frontend::IncludeDirGroup Group = static_cast<frontend::IncludeDirGroup>(Record[Idx++]); bool IsFramework = Record[Idx++]; bool IgnoreSysRoot = Record[Idx++]; HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework, IgnoreSysRoot); } // System header prefixes. for (unsigned N = Record[Idx++]; N; --N) { std::string Prefix = ReadString(Record, Idx); bool IsSystemHeader = Record[Idx++]; HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader); } HSOpts.ResourceDir = ReadString(Record, Idx); HSOpts.ModuleCachePath = ReadString(Record, Idx); HSOpts.ModuleUserBuildPath = ReadString(Record, Idx); HSOpts.DisableModuleHash = Record[Idx++]; HSOpts.ImplicitModuleMaps = Record[Idx++]; HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++]; HSOpts.UseBuiltinIncludes = Record[Idx++]; HSOpts.UseStandardSystemIncludes = Record[Idx++]; HSOpts.UseStandardCXXIncludes = Record[Idx++]; HSOpts.UseLibcxx = Record[Idx++]; std::string SpecificModuleCachePath = ReadString(Record, Idx); return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, Complain); } bool ASTReader::ParsePreprocessorOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, std::string &SuggestedPredefines) { PreprocessorOptions PPOpts; unsigned Idx = 0; // Macro definitions/undefs for (unsigned N = Record[Idx++]; N; --N) { std::string Macro = ReadString(Record, Idx); bool IsUndef = Record[Idx++]; PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef)); } // Includes for (unsigned N = Record[Idx++]; N; --N) { PPOpts.Includes.push_back(ReadString(Record, Idx)); } // Macro Includes for (unsigned N = Record[Idx++]; N; --N) { PPOpts.MacroIncludes.push_back(ReadString(Record, Idx)); } PPOpts.UsePredefines = Record[Idx++]; PPOpts.DetailedRecord = Record[Idx++]; PPOpts.ImplicitPCHInclude = ReadString(Record, Idx); PPOpts.ImplicitPTHInclude = ReadString(Record, Idx); PPOpts.ObjCXXARCStandardLibrary = static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]); SuggestedPredefines.clear(); return Listener.ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines); } std::pair<ModuleFile *, unsigned> ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) { GlobalPreprocessedEntityMapType::iterator I = GlobalPreprocessedEntityMap.find(GlobalIndex); assert(I != GlobalPreprocessedEntityMap.end() && "Corrupted global preprocessed entity map"); ModuleFile *M = I->second; unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID; return std::make_pair(M, LocalIndex); } llvm::iterator_range<PreprocessingRecord::iterator> ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const { if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord()) return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID, Mod.NumPreprocessedEntities); return llvm::make_range(PreprocessingRecord::iterator(), PreprocessingRecord::iterator()); } llvm::iterator_range<ASTReader::ModuleDeclIterator> ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) { return llvm::make_range( ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls), ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls + Mod.NumFileSortedDecls)); } PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) { PreprocessedEntityID PPID = Index+1; std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); ModuleFile &M = *PPInfo.first; unsigned LocalIndex = PPInfo.second; const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; if (!PP.getPreprocessingRecord()) { Error("no preprocessing record"); return nullptr; } SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset); llvm::BitstreamEntry Entry = M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); if (Entry.Kind != llvm::BitstreamEntry::Record) return nullptr; // Read the record. SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()), TranslateSourceLocation(M, PPOffs.getEnd())); PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); StringRef Blob; RecordData Record; PreprocessorDetailRecordTypes RecType = (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord( Entry.ID, Record, &Blob); switch (RecType) { case PPD_MACRO_EXPANSION: { bool isBuiltin = Record[0]; IdentifierInfo *Name = nullptr; MacroDefinitionRecord *Def = nullptr; if (isBuiltin) Name = getLocalIdentifier(M, Record[1]); else { PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(M, Record[1]); Def = cast<MacroDefinitionRecord>( PPRec.getLoadedPreprocessedEntity(GlobalID - 1)); } MacroExpansion *ME; if (isBuiltin) ME = new (PPRec) MacroExpansion(Name, Range); else ME = new (PPRec) MacroExpansion(Def, Range); return ME; } case PPD_MACRO_DEFINITION: { // Decode the identifier info and then check again; if the macro is // still defined and associated with the identifier, IdentifierInfo *II = getLocalIdentifier(M, Record[0]); MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range); if (DeserializationListener) DeserializationListener->MacroDefinitionRead(PPID, MD); return MD; } case PPD_INCLUSION_DIRECTIVE: { const char *FullFileNameStart = Blob.data() + Record[0]; StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]); const FileEntry *File = nullptr; if (!FullFileName.empty()) File = PP.getFileManager().getFile(FullFileName); // FIXME: Stable encoding InclusionDirective::InclusionKind Kind = static_cast<InclusionDirective::InclusionKind>(Record[2]); InclusionDirective *ID = new (PPRec) InclusionDirective(PPRec, Kind, StringRef(Blob.data(), Record[0]), Record[1], Record[3], File, Range); return ID; } } llvm_unreachable("Invalid PreprocessorDetailRecordTypes"); } /// \brief \arg SLocMapI points at a chunk of a module that contains no /// preprocessed entities or the entities it contains are not the ones we are /// looking for. Find the next module that contains entities and return the ID /// of the first entry. PreprocessedEntityID ASTReader::findNextPreprocessedEntity( GlobalSLocOffsetMapType::const_iterator SLocMapI) const { ++SLocMapI; for (GlobalSLocOffsetMapType::const_iterator EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) { ModuleFile &M = *SLocMapI->second; if (M.NumPreprocessedEntities) return M.BasePreprocessedEntityID; } return getTotalNumPreprocessedEntities(); } namespace { struct PPEntityComp { const ASTReader &Reader; ModuleFile &M; PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { } bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const { SourceLocation LHS = getLoc(L); SourceLocation RHS = getLoc(R); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } bool operator()(const PPEntityOffset &L, SourceLocation RHS) const { SourceLocation LHS = getLoc(L); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } bool operator()(SourceLocation LHS, const PPEntityOffset &R) const { SourceLocation RHS = getLoc(R); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } SourceLocation getLoc(const PPEntityOffset &PPE) const { return Reader.TranslateSourceLocation(M, PPE.getBegin()); } }; } // end anonymous namespace PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const { if (SourceMgr.isLocalSourceLocation(Loc)) return getTotalNumPreprocessedEntities(); GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find( SourceManager::MaxLoadedOffset - Loc.getOffset() - 1); assert(SLocMapI != GlobalSLocOffsetMap.end() && "Corrupted global sloc offset map"); if (SLocMapI->second->NumPreprocessedEntities == 0) return findNextPreprocessedEntity(SLocMapI); ModuleFile &M = *SLocMapI->second; typedef const PPEntityOffset *pp_iterator; pp_iterator pp_begin = M.PreprocessedEntityOffsets; pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities; size_t Count = M.NumPreprocessedEntities; size_t Half; pp_iterator First = pp_begin; pp_iterator PPI; if (EndsAfter) { PPI = std::upper_bound(pp_begin, pp_end, Loc, PPEntityComp(*this, M)); } else { // Do a binary search manually instead of using std::lower_bound because // The end locations of entities may be unordered (when a macro expansion // is inside another macro argument), but for this case it is not important // whether we get the first macro expansion or its containing macro. while (Count > 0) { Half = Count / 2; PPI = First; std::advance(PPI, Half); if (SourceMgr.isBeforeInTranslationUnit( TranslateSourceLocation(M, PPI->getEnd()), Loc)) { First = PPI; ++First; Count = Count - Half - 1; } else Count = Half; } } if (PPI == pp_end) return findNextPreprocessedEntity(SLocMapI); return M.BasePreprocessedEntityID + (PPI - pp_begin); } /// \brief Returns a pair of [Begin, End) indices of preallocated /// preprocessed entities that \arg Range encompasses. std::pair<unsigned, unsigned> ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) { if (Range.isInvalid()) return std::make_pair(0,0); assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); PreprocessedEntityID BeginID = findPreprocessedEntity(Range.getBegin(), false); PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true); return std::make_pair(BeginID, EndID); } /// \brief Optionally returns true or false if the preallocated preprocessed /// entity with index \arg Index came from file \arg FID. Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, FileID FID) { if (FID.isInvalid()) return false; std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); ModuleFile &M = *PPInfo.first; unsigned LocalIndex = PPInfo.second; const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin()); if (Loc.isInvalid()) return false; if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID)) return true; else return false; } namespace { /// \brief Visitor used to search for information about a header file. class HeaderFileInfoVisitor { const FileEntry *FE; Optional<HeaderFileInfo> HFI; public: explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) { } bool operator()(ModuleFile &M) { HeaderFileInfoLookupTable *Table = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable); if (!Table) return false; // Look in the on-disk hash table for an entry for this file name. HeaderFileInfoLookupTable::iterator Pos = Table->find(FE); if (Pos == Table->end()) return false; HFI = *Pos; return true; } Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } }; } // end anonymous namespace HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) { HeaderFileInfoVisitor Visitor(FE); ModuleMgr.visit(Visitor); if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) return *HFI; return HeaderFileInfo(); } void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) { using DiagState = DiagnosticsEngine::DiagState; SmallVector<DiagState *, 32> DiagStates; for (ModuleFile &F : ModuleMgr) { unsigned Idx = 0; auto &Record = F.PragmaDiagMappings; if (Record.empty()) continue; DiagStates.clear(); auto ReadDiagState = [&](const DiagState &BasedOn, SourceLocation Loc, bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * { unsigned BackrefID = Record[Idx++]; if (BackrefID != 0) return DiagStates[BackrefID - 1]; // A new DiagState was created here. Diag.DiagStates.push_back(BasedOn); DiagState *NewState = &Diag.DiagStates.back(); DiagStates.push_back(NewState); unsigned Size = Record[Idx++]; assert(Idx + Size * 2 <= Record.size() && "Invalid data, not enough diag/map pairs"); while (Size--) { unsigned DiagID = Record[Idx++]; DiagnosticMapping NewMapping = DiagnosticMapping::deserialize(Record[Idx++]); if (!NewMapping.isPragma() && !IncludeNonPragmaStates) continue; DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID); // If this mapping was specified as a warning but the severity was // upgraded due to diagnostic settings, simulate the current diagnostic // settings (and use a warning). if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) { NewMapping.setSeverity(diag::Severity::Warning); NewMapping.setUpgradedFromWarning(false); } Mapping = NewMapping; } return NewState; }; // Read the first state. DiagState *FirstState; if (F.Kind == MK_ImplicitModule) { // Implicitly-built modules are reused with different diagnostic // settings. Use the initial diagnostic state from Diag to simulate this // compilation's diagnostic settings. FirstState = Diag.DiagStatesByLoc.FirstDiagState; DiagStates.push_back(FirstState); // Skip the initial diagnostic state from the serialized module. assert(Record[1] == 0 && "Invalid data, unexpected backref in initial state"); Idx = 3 + Record[2] * 2; assert(Idx < Record.size() && "Invalid data, not enough state change pairs in initial state"); } else if (F.isModule()) { // For an explicit module, preserve the flags from the module build // command line (-w, -Weverything, -Werror, ...) along with any explicit // -Wblah flags. unsigned Flags = Record[Idx++]; DiagState Initial; Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1; Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1; Initial.WarningsAsErrors = Flags & 1; Flags >>= 1; Initial.EnableAllWarnings = Flags & 1; Flags >>= 1; Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1; Initial.ExtBehavior = (diag::Severity)Flags; FirstState = ReadDiagState(Initial, SourceLocation(), true); // Set up the root buffer of the module to start with the initial // diagnostic state of the module itself, to cover files that contain no // explicit transitions (for which we did not serialize anything). Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID] .StateTransitions.push_back({FirstState, 0}); } else { // For prefix ASTs, start with whatever the user configured on the // command line. Idx++; // Skip flags. FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, SourceLocation(), false); } // Read the state transitions. unsigned NumLocations = Record[Idx++]; while (NumLocations--) { assert(Idx < Record.size() && "Invalid data, missing pragma diagnostic states"); SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]); auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc); assert(IDAndOffset.second == 0 && "not a start location for a FileID"); unsigned Transitions = Record[Idx++]; // Note that we don't need to set up Parent/ParentOffset here, because // we won't be changing the diagnostic state within imported FileIDs // (other than perhaps appending to the main source file, which has no // parent). auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first]; F.StateTransitions.reserve(F.StateTransitions.size() + Transitions); for (unsigned I = 0; I != Transitions; ++I) { unsigned Offset = Record[Idx++]; auto *State = ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false); F.StateTransitions.push_back({State, Offset}); } } // Read the final state. assert(Idx < Record.size() && "Invalid data, missing final pragma diagnostic state"); SourceLocation CurStateLoc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]); auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false); if (!F.isModule()) { Diag.DiagStatesByLoc.CurDiagState = CurState; Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc; // Preserve the property that the imaginary root file describes the // current state. auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions; if (T.empty()) T.push_back({CurState, 0}); else T[0].State = CurState; } // Don't try to read these mappings again. Record.clear(); } } /// \brief Get the correct cursor and offset for loading a type. ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index); assert(I != GlobalTypeMap.end() && "Corrupted global type map"); ModuleFile *M = I->second; return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]); } /// \brief Read and return the type with the given index.. /// /// The index is the type ID, shifted and minus the number of predefs. This /// routine actually reads the record corresponding to the type at the given /// location. It is a helper routine for GetType, which deals with reading type /// IDs. QualType ASTReader::readTypeRecord(unsigned Index) { assert(ContextObj && "reading type with no AST context"); ASTContext &Context = *ContextObj; RecordLocation Loc = TypeCursorForIndex(Index); BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; // Keep track of where we are in the stream, then jump back there // after reading this type. SavedStreamPosition SavedPosition(DeclsCursor); ReadingKindTracker ReadingKind(Read_Type, *this); // Note that we are loading a type record. Deserializing AType(this); unsigned Idx = 0; DeclsCursor.JumpToBit(Loc.Offset); RecordData Record; unsigned Code = DeclsCursor.ReadCode(); switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) { case TYPE_EXT_QUAL: { if (Record.size() != 2) { Error("Incorrect encoding of extended qualifier type"); return QualType(); } QualType Base = readType(*Loc.F, Record, Idx); Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]); return Context.getQualifiedType(Base, Quals); } case TYPE_COMPLEX: { if (Record.size() != 1) { Error("Incorrect encoding of complex type"); return QualType(); } QualType ElemType = readType(*Loc.F, Record, Idx); return Context.getComplexType(ElemType); } case TYPE_POINTER: { if (Record.size() != 1) { Error("Incorrect encoding of pointer type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); return Context.getPointerType(PointeeType); } case TYPE_DECAYED: { if (Record.size() != 1) { Error("Incorrect encoding of decayed type"); return QualType(); } QualType OriginalType = readType(*Loc.F, Record, Idx); QualType DT = Context.getAdjustedParameterType(OriginalType); if (!isa<DecayedType>(DT)) Error("Decayed type does not decay"); return DT; } case TYPE_ADJUSTED: { if (Record.size() != 2) { Error("Incorrect encoding of adjusted type"); return QualType(); } QualType OriginalTy = readType(*Loc.F, Record, Idx); QualType AdjustedTy = readType(*Loc.F, Record, Idx); return Context.getAdjustedType(OriginalTy, AdjustedTy); } case TYPE_BLOCK_POINTER: { if (Record.size() != 1) { Error("Incorrect encoding of block pointer type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); return Context.getBlockPointerType(PointeeType); } case TYPE_LVALUE_REFERENCE: { if (Record.size() != 2) { Error("Incorrect encoding of lvalue reference type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); return Context.getLValueReferenceType(PointeeType, Record[1]); } case TYPE_RVALUE_REFERENCE: { if (Record.size() != 1) { Error("Incorrect encoding of rvalue reference type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); return Context.getRValueReferenceType(PointeeType); } case TYPE_MEMBER_POINTER: { if (Record.size() != 2) { Error("Incorrect encoding of member pointer type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); QualType ClassType = readType(*Loc.F, Record, Idx); if (PointeeType.isNull() || ClassType.isNull()) return QualType(); return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr()); } case TYPE_CONSTANT_ARRAY: { QualType ElementType = readType(*Loc.F, Record, Idx); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; unsigned Idx = 3; llvm::APInt Size = ReadAPInt(Record, Idx); return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals); } case TYPE_INCOMPLETE_ARRAY: { QualType ElementType = readType(*Loc.F, Record, Idx); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals); } case TYPE_VARIABLE_ARRAY: { QualType ElementType = readType(*Loc.F, Record, Idx); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]); SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]); return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F), ASM, IndexTypeQuals, SourceRange(LBLoc, RBLoc)); } case TYPE_VECTOR: { if (Record.size() != 3) { Error("incorrect encoding of vector type in AST file"); return QualType(); } QualType ElementType = readType(*Loc.F, Record, Idx); unsigned NumElements = Record[1]; unsigned VecKind = Record[2]; return Context.getVectorType(ElementType, NumElements, (VectorType::VectorKind)VecKind); } case TYPE_EXT_VECTOR: { if (Record.size() != 3) { Error("incorrect encoding of extended vector type in AST file"); return QualType(); } QualType ElementType = readType(*Loc.F, Record, Idx); unsigned NumElements = Record[1]; return Context.getExtVectorType(ElementType, NumElements); } case TYPE_FUNCTION_NO_PROTO: { if (Record.size() != 7) { Error("incorrect encoding of no-proto function type"); return QualType(); } QualType ResultType = readType(*Loc.F, Record, Idx); FunctionType::ExtInfo Info(Record[1], Record[2], Record[3], (CallingConv)Record[4], Record[5], Record[6]); return Context.getFunctionNoProtoType(ResultType, Info); } case TYPE_FUNCTION_PROTO: { QualType ResultType = readType(*Loc.F, Record, Idx); FunctionProtoType::ExtProtoInfo EPI; EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1], /*hasregparm*/ Record[2], /*regparm*/ Record[3], static_cast<CallingConv>(Record[4]), /*produces*/ Record[5], /*nocallersavedregs*/ Record[6]); unsigned Idx = 7; EPI.Variadic = Record[Idx++]; EPI.HasTrailingReturn = Record[Idx++]; EPI.TypeQuals = Record[Idx++]; EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]); SmallVector<QualType, 8> ExceptionStorage; readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx); unsigned NumParams = Record[Idx++]; SmallVector<QualType, 16> ParamTypes; for (unsigned I = 0; I != NumParams; ++I) ParamTypes.push_back(readType(*Loc.F, Record, Idx)); SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos; if (Idx != Record.size()) { for (unsigned I = 0; I != NumParams; ++I) ExtParameterInfos.push_back( FunctionProtoType::ExtParameterInfo ::getFromOpaqueValue(Record[Idx++])); EPI.ExtParameterInfos = ExtParameterInfos.data(); } assert(Idx == Record.size()); return Context.getFunctionType(ResultType, ParamTypes, EPI); } case TYPE_UNRESOLVED_USING: { unsigned Idx = 0; return Context.getTypeDeclType( ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx)); } case TYPE_TYPEDEF: { if (Record.size() != 2) { Error("incorrect encoding of typedef type"); return QualType(); } unsigned Idx = 0; TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx); QualType Canonical = readType(*Loc.F, Record, Idx); if (!Canonical.isNull()) Canonical = Context.getCanonicalType(Canonical); return Context.getTypedefType(Decl, Canonical); } case TYPE_TYPEOF_EXPR: return Context.getTypeOfExprType(ReadExpr(*Loc.F)); case TYPE_TYPEOF: { if (Record.size() != 1) { Error("incorrect encoding of typeof(type) in AST file"); return QualType(); } QualType UnderlyingType = readType(*Loc.F, Record, Idx); return Context.getTypeOfType(UnderlyingType); } case TYPE_DECLTYPE: { QualType UnderlyingType = readType(*Loc.F, Record, Idx); return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType); } case TYPE_UNARY_TRANSFORM: { QualType BaseType = readType(*Loc.F, Record, Idx); QualType UnderlyingType = readType(*Loc.F, Record, Idx); UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2]; return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind); } case TYPE_AUTO: { QualType Deduced = readType(*Loc.F, Record, Idx); AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++]; bool IsDependent = Deduced.isNull() ? Record[Idx++] : false; return Context.getAutoType(Deduced, Keyword, IsDependent); } case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: { TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); QualType Deduced = readType(*Loc.F, Record, Idx); bool IsDependent = Deduced.isNull() ? Record[Idx++] : false; return Context.getDeducedTemplateSpecializationType(Name, Deduced, IsDependent); } case TYPE_RECORD: { if (Record.size() != 2) { Error("incorrect encoding of record type"); return QualType(); } unsigned Idx = 0; bool IsDependent = Record[Idx++]; RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx); RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl()); QualType T = Context.getRecordType(RD); const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); return T; } case TYPE_ENUM: { if (Record.size() != 2) { Error("incorrect encoding of enum type"); return QualType(); } unsigned Idx = 0; bool IsDependent = Record[Idx++]; QualType T = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx)); const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); return T; } case TYPE_ATTRIBUTED: { if (Record.size() != 3) { Error("incorrect encoding of attributed type"); return QualType(); } QualType modifiedType = readType(*Loc.F, Record, Idx); QualType equivalentType = readType(*Loc.F, Record, Idx); AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]); return Context.getAttributedType(kind, modifiedType, equivalentType); } case TYPE_PAREN: { if (Record.size() != 1) { Error("incorrect encoding of paren type"); return QualType(); } QualType InnerType = readType(*Loc.F, Record, Idx); return Context.getParenType(InnerType); } case TYPE_PACK_EXPANSION: { if (Record.size() != 2) { Error("incorrect encoding of pack expansion type"); return QualType(); } QualType Pattern = readType(*Loc.F, Record, Idx); if (Pattern.isNull()) return QualType(); Optional<unsigned> NumExpansions; if (Record[1]) NumExpansions = Record[1] - 1; return Context.getPackExpansionType(Pattern, NumExpansions); } case TYPE_ELABORATED: { unsigned Idx = 0; ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); QualType NamedType = readType(*Loc.F, Record, Idx); return Context.getElaboratedType(Keyword, NNS, NamedType); } case TYPE_OBJC_INTERFACE: { unsigned Idx = 0; ObjCInterfaceDecl *ItfD = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx); return Context.getObjCInterfaceType(ItfD->getCanonicalDecl()); } case TYPE_OBJC_TYPE_PARAM: { unsigned Idx = 0; ObjCTypeParamDecl *Decl = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx); unsigned NumProtos = Record[Idx++]; SmallVector<ObjCProtocolDecl*, 4> Protos; for (unsigned I = 0; I != NumProtos; ++I) Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx)); return Context.getObjCTypeParamType(Decl, Protos); } case TYPE_OBJC_OBJECT: { unsigned Idx = 0; QualType Base = readType(*Loc.F, Record, Idx); unsigned NumTypeArgs = Record[Idx++]; SmallVector<QualType, 4> TypeArgs; for (unsigned I = 0; I != NumTypeArgs; ++I) TypeArgs.push_back(readType(*Loc.F, Record, Idx)); unsigned NumProtos = Record[Idx++]; SmallVector<ObjCProtocolDecl*, 4> Protos; for (unsigned I = 0; I != NumProtos; ++I) Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx)); bool IsKindOf = Record[Idx++]; return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf); } case TYPE_OBJC_OBJECT_POINTER: { unsigned Idx = 0; QualType Pointee = readType(*Loc.F, Record, Idx); return Context.getObjCObjectPointerType(Pointee); } case TYPE_SUBST_TEMPLATE_TYPE_PARM: { unsigned Idx = 0; QualType Parm = readType(*Loc.F, Record, Idx); QualType Replacement = readType(*Loc.F, Record, Idx); return Context.getSubstTemplateTypeParmType( cast<TemplateTypeParmType>(Parm), Context.getCanonicalType(Replacement)); } case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: { unsigned Idx = 0; QualType Parm = readType(*Loc.F, Record, Idx); TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx); return Context.getSubstTemplateTypeParmPackType( cast<TemplateTypeParmType>(Parm), ArgPack); } case TYPE_INJECTED_CLASS_NAME: { CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx); QualType TST = readType(*Loc.F, Record, Idx); // probably derivable // FIXME: ASTContext::getInjectedClassNameType is not currently suitable // for AST reading, too much interdependencies. const Type *T = nullptr; for (auto *DI = D; DI; DI = DI->getPreviousDecl()) { if (const Type *Existing = DI->getTypeForDecl()) { T = Existing; break; } } if (!T) { T = new (Context, TypeAlignment) InjectedClassNameType(D, TST); for (auto *DI = D; DI; DI = DI->getPreviousDecl()) DI->setTypeForDecl(T); } return QualType(T, 0); } case TYPE_TEMPLATE_TYPE_PARM: { unsigned Idx = 0; unsigned Depth = Record[Idx++]; unsigned Index = Record[Idx++]; bool Pack = Record[Idx++]; TemplateTypeParmDecl *D = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx); return Context.getTemplateTypeParmType(Depth, Index, Pack, D); } case TYPE_DEPENDENT_NAME: { unsigned Idx = 0; ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx); QualType Canon = readType(*Loc.F, Record, Idx); if (!Canon.isNull()) Canon = Context.getCanonicalType(Canon); return Context.getDependentNameType(Keyword, NNS, Name, Canon); } case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: { unsigned Idx = 0; ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx); unsigned NumArgs = Record[Idx++]; SmallVector<TemplateArgument, 8> Args; Args.reserve(NumArgs); while (NumArgs--) Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx)); return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name, Args); } case TYPE_DEPENDENT_SIZED_ARRAY: { unsigned Idx = 0; // ArrayType QualType ElementType = readType(*Loc.F, Record, Idx); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[Idx++]; unsigned IndexTypeQuals = Record[Idx++]; // DependentSizedArrayType Expr *NumElts = ReadExpr(*Loc.F); SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx); return Context.getDependentSizedArrayType(ElementType, NumElts, ASM, IndexTypeQuals, Brackets); } case TYPE_TEMPLATE_SPECIALIZATION: { unsigned Idx = 0; bool IsDependent = Record[Idx++]; TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); SmallVector<TemplateArgument, 8> Args; ReadTemplateArgumentList(Args, *Loc.F, Record, Idx); QualType Underlying = readType(*Loc.F, Record, Idx); QualType T; if (Underlying.isNull()) T = Context.getCanonicalTemplateSpecializationType(Name, Args); else T = Context.getTemplateSpecializationType(Name, Args, Underlying); const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); return T; } case TYPE_ATOMIC: { if (Record.size() != 1) { Error("Incorrect encoding of atomic type"); return QualType(); } QualType ValueType = readType(*Loc.F, Record, Idx); return Context.getAtomicType(ValueType); } case TYPE_PIPE: { if (Record.size() != 2) { Error("Incorrect encoding of pipe type"); return QualType(); } // Reading the pipe element type. QualType ElementType = readType(*Loc.F, Record, Idx); unsigned ReadOnly = Record[1]; return Context.getPipeType(ElementType, ReadOnly); } case TYPE_DEPENDENT_SIZED_EXT_VECTOR: { unsigned Idx = 0; // DependentSizedExtVectorType QualType ElementType = readType(*Loc.F, Record, Idx); Expr *SizeExpr = ReadExpr(*Loc.F); SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx); return Context.getDependentSizedExtVectorType(ElementType, SizeExpr, AttrLoc); } } llvm_unreachable("Invalid TypeCode!"); } void ASTReader::readExceptionSpec(ModuleFile &ModuleFile, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI, const RecordData &Record, unsigned &Idx) { ExceptionSpecificationType EST = static_cast<ExceptionSpecificationType>(Record[Idx++]); ESI.Type = EST; if (EST == EST_Dynamic) { for (unsigned I = 0, N = Record[Idx++]; I != N; ++I) Exceptions.push_back(readType(ModuleFile, Record, Idx)); ESI.Exceptions = Exceptions; } else if (EST == EST_ComputedNoexcept) { ESI.NoexceptExpr = ReadExpr(ModuleFile); } else if (EST == EST_Uninstantiated) { ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); } else if (EST == EST_Unevaluated) { ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); } } class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> { ModuleFile *F; ASTReader *Reader; const ASTReader::RecordData &Record; unsigned &Idx; SourceLocation ReadSourceLocation() { return Reader->ReadSourceLocation(*F, Record, Idx); } TypeSourceInfo *GetTypeSourceInfo() { return Reader->GetTypeSourceInfo(*F, Record, Idx); } NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() { return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx); } public: TypeLocReader(ModuleFile &F, ASTReader &Reader, const ASTReader::RecordData &Record, unsigned &Idx) : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {} // We want compile-time assurance that we've enumerated all of // these, so unfortunately we have to declare them first, then // define them out-of-line. #define ABSTRACT_TYPELOC(CLASS, PARENT) #define TYPELOC(CLASS, PARENT) \ void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); #include "clang/AST/TypeLocNodes.def" void VisitFunctionTypeLoc(FunctionTypeLoc); void VisitArrayTypeLoc(ArrayTypeLoc); }; void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { // nothing to do } void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { TL.setBuiltinLoc(ReadSourceLocation()); if (TL.needsExtraLocalData()) { TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++])); TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++])); TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++])); TL.setModeAttr(Record[Idx++]); } } void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { TL.setStarLoc(ReadSourceLocation()); } void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) { // nothing to do } void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { // nothing to do } void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { TL.setCaretLoc(ReadSourceLocation()); } void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { TL.setAmpLoc(ReadSourceLocation()); } void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { TL.setAmpAmpLoc(ReadSourceLocation()); } void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { TL.setStarLoc(ReadSourceLocation()); TL.setClassTInfo(GetTypeSourceInfo()); } void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { TL.setLBracketLoc(ReadSourceLocation()); TL.setRBracketLoc(ReadSourceLocation()); if (Record[Idx++]) TL.setSizeExpr(Reader->ReadExpr(*F)); else TL.setSizeExpr(nullptr); } void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { VisitArrayTypeLoc(TL); } void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { VisitArrayTypeLoc(TL); } void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { VisitArrayTypeLoc(TL); } void TypeLocReader::VisitDependentSizedArrayTypeLoc( DependentSizedArrayTypeLoc TL) { VisitArrayTypeLoc(TL); } void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( DependentSizedExtVectorTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { TL.setLocalRangeBegin(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx), Reader->ReadSourceLocation(*F, Record, Idx))); TL.setLocalRangeEnd(ReadSourceLocation()); for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) { TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx)); } } void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { VisitFunctionTypeLoc(TL); } void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { VisitFunctionTypeLoc(TL); } void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { TL.setTypeofLoc(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); } void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { TL.setTypeofLoc(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); TL.setUnderlyingTInfo(GetTypeSourceInfo()); } void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { TL.setKWLoc(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); TL.setUnderlyingTInfo(GetTypeSourceInfo()); } void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc( DeducedTemplateSpecializationTypeLoc TL) { TL.setTemplateNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { TL.setAttrNameLoc(ReadSourceLocation()); if (TL.hasAttrOperand()) { SourceRange range; range.setBegin(ReadSourceLocation()); range.setEnd(ReadSourceLocation()); TL.setAttrOperandParensRange(range); } if (TL.hasAttrExprOperand()) { if (Record[Idx++]) TL.setAttrExprOperand(Reader->ReadExpr(*F)); else TL.setAttrExprOperand(nullptr); } else if (TL.hasAttrEnumOperand()) TL.setAttrEnumOperandLoc(ReadSourceLocation()); } void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( SubstTemplateTypeParmTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( SubstTemplateTypeParmPackTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitTemplateSpecializationTypeLoc( TemplateSpecializationTypeLoc TL) { TL.setTemplateKeywordLoc(ReadSourceLocation()); TL.setTemplateNameLoc(ReadSourceLocation()); TL.setLAngleLoc(ReadSourceLocation()); TL.setRAngleLoc(ReadSourceLocation()); for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) TL.setArgLocInfo( i, Reader->GetTemplateArgumentLocInfo( *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx)); } void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); } void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { TL.setElaboratedKeywordLoc(ReadSourceLocation()); TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); } void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { TL.setElaboratedKeywordLoc(ReadSourceLocation()); TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( DependentTemplateSpecializationTypeLoc TL) { TL.setElaboratedKeywordLoc(ReadSourceLocation()); TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); TL.setTemplateKeywordLoc(ReadSourceLocation()); TL.setTemplateNameLoc(ReadSourceLocation()); TL.setLAngleLoc(ReadSourceLocation()); TL.setRAngleLoc(ReadSourceLocation()); for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) TL.setArgLocInfo( I, Reader->GetTemplateArgumentLocInfo( *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx)); } void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { TL.setEllipsisLoc(ReadSourceLocation()); } void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { if (TL.getNumProtocols()) { TL.setProtocolLAngleLoc(ReadSourceLocation()); TL.setProtocolRAngleLoc(ReadSourceLocation()); } for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) TL.setProtocolLoc(i, ReadSourceLocation()); } void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { TL.setHasBaseTypeAsWritten(Record[Idx++]); TL.setTypeArgsLAngleLoc(ReadSourceLocation()); TL.setTypeArgsRAngleLoc(ReadSourceLocation()); for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) TL.setTypeArgTInfo(i, GetTypeSourceInfo()); TL.setProtocolLAngleLoc(ReadSourceLocation()); TL.setProtocolRAngleLoc(ReadSourceLocation()); for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) TL.setProtocolLoc(i, ReadSourceLocation()); } void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { TL.setStarLoc(ReadSourceLocation()); } void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) { TL.setKWLoc(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); } void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) { TL.setKWLoc(ReadSourceLocation()); } TypeSourceInfo * ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record, unsigned &Idx) { QualType InfoTy = readType(F, Record, Idx); if (InfoTy.isNull()) return nullptr; TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy); TypeLocReader TLR(F, *this, Record, Idx); for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc()) TLR.Visit(TL); return TInfo; } QualType ASTReader::GetType(TypeID ID) { assert(ContextObj && "reading type with no AST context"); ASTContext &Context = *ContextObj; unsigned FastQuals = ID & Qualifiers::FastMask; unsigned Index = ID >> Qualifiers::FastWidth; if (Index < NUM_PREDEF_TYPE_IDS) { QualType T; switch ((PredefinedTypeIDs)Index) { case PREDEF_TYPE_NULL_ID: return QualType(); case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break; case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break; case PREDEF_TYPE_CHAR_U_ID: case PREDEF_TYPE_CHAR_S_ID: // FIXME: Check that the signedness of CharTy is correct! T = Context.CharTy; break; case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break; case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break; case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break; case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break; case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break; case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break; case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break; case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break; case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break; case PREDEF_TYPE_INT_ID: T = Context.IntTy; break; case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break; case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break; case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break; case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break; case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break; case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break; case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break; case PREDEF_TYPE_FLOAT128_ID: T = Context.Float128Ty; break; case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break; case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break; case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break; case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break; case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break; case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break; case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break; case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break; case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break; case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break; case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break; #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case PREDEF_TYPE_##Id##_ID: \ T = Context.SingletonId; \ break; #include "clang/Basic/OpenCLImageTypes.def" case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break; case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break; case PREDEF_TYPE_CLK_EVENT_ID: T = Context.OCLClkEventTy; break; case PREDEF_TYPE_QUEUE_ID: T = Context.OCLQueueTy; break; case PREDEF_TYPE_RESERVE_ID_ID: T = Context.OCLReserveIDTy; break; case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break; case PREDEF_TYPE_AUTO_RREF_DEDUCT: T = Context.getAutoRRefDeductType(); break; case PREDEF_TYPE_ARC_UNBRIDGED_CAST: T = Context.ARCUnbridgedCastTy; break; case PREDEF_TYPE_BUILTIN_FN: T = Context.BuiltinFnTy; break; case PREDEF_TYPE_OMP_ARRAY_SECTION: T = Context.OMPArraySectionTy; break; } assert(!T.isNull() && "Unknown predefined type"); return T.withFastQualifiers(FastQuals); } Index -= NUM_PREDEF_TYPE_IDS; assert(Index < NumTypesLoaded && "Type index out-of-range"); if (TypesLoaded.find(Index) == TypesLoaded.end()) { QualType QualTy = readTypeRecord(Index); TypesLoaded.insert({Index, QualTy}); if (TypesLoaded.find(Index) == TypesLoaded.end()) return QualType(); QualTy->setFromAST(); if (DeserializationListener) DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID), QualTy); } return TypesLoaded.find(Index)->second.withFastQualifiers(FastQuals); } QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) { return GetType(getGlobalTypeID(F, LocalID)); } serialization::TypeID ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const { unsigned FastQuals = LocalID & Qualifiers::FastMask; unsigned LocalIndex = LocalID >> Qualifiers::FastWidth; if (LocalIndex < NUM_PREDEF_TYPE_IDS) return LocalID; if (!F.ModuleOffsetMap.empty()) ReadModuleOffsetMap(F); ContinuousRangeMap<uint32_t, int, 2>::iterator I = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS); assert(I != F.TypeRemap.end() && "Invalid index into type index remap"); unsigned GlobalIndex = LocalIndex + I->second; return (GlobalIndex << Qualifiers::FastWidth) | FastQuals; } TemplateArgumentLocInfo ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind, const RecordData &Record, unsigned &Index) { switch (Kind) { case TemplateArgument::Expression: return ReadExpr(F); case TemplateArgument::Type: return GetTypeSourceInfo(F, Record, Index); case TemplateArgument::Template: { NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Index); SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, SourceLocation()); } case TemplateArgument::TemplateExpansion: { NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Index); SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index); return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, EllipsisLoc); } case TemplateArgument::Null: case TemplateArgument::Integral: case TemplateArgument::Declaration: case TemplateArgument::NullPtr: case TemplateArgument::Pack: // FIXME: Is this right? return TemplateArgumentLocInfo(); } llvm_unreachable("unexpected template argument loc"); } TemplateArgumentLoc ASTReader::ReadTemplateArgumentLoc(ModuleFile &F, const RecordData &Record, unsigned &Index) { TemplateArgument Arg = ReadTemplateArgument(F, Record, Index); if (Arg.getKind() == TemplateArgument::Expression) { if (Record[Index++]) // bool InfoHasSameExpr. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); } return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(), Record, Index)); } const ASTTemplateArgumentListInfo* ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F, const RecordData &Record, unsigned &Index) { SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index); SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index); unsigned NumArgsAsWritten = Record[Index++]; TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc); for (unsigned i = 0; i != NumArgsAsWritten; ++i) TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index)); return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo); } Decl *ASTReader::GetExternalDecl(uint32_t ID) { return GetDecl(ID); } void ASTReader::CompleteRedeclChain(const Decl *D) { if (NumCurrentElementsDeserializing) { // We arrange to not care about the complete redeclaration chain while we're // deserializing. Just remember that the AST has marked this one as complete // but that it's not actually complete yet, so we know we still need to // complete it later. PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D)); return; } const DeclContext *DC = D->getDeclContext()->getRedeclContext(); // If this is a named declaration, complete it by looking it up // within its context. // // FIXME: Merging a function definition should merge // all mergeable entities within it. if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) || isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) { if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) { if (!getContext().getLangOpts().CPlusPlus && isa<TranslationUnitDecl>(DC)) { // Outside of C++, we don't have a lookup table for the TU, so update // the identifier instead. (For C++ modules, we don't store decls // in the serialized identifier table, so we do the lookup in the TU.) auto *II = Name.getAsIdentifierInfo(); assert(II && "non-identifier name in C?"); if (II->isOutOfDate()) updateOutOfDateIdentifier(*II); } else DC->lookup(Name); } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) { // Find all declarations of this kind from the relevant context. for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) { auto *DC = cast<DeclContext>(DCDecl); SmallVector<Decl*, 8> Decls; FindExternalLexicalDecls( DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls); } } } RedeclarableTemplateDecl *Template = nullptr; ArrayRef<TemplateArgument> Args; if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { Template = CTSD->getSpecializedTemplate(); Args = CTSD->getTemplateArgs().asArray(); } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) { Template = VTSD->getSpecializedTemplate(); Args = VTSD->getTemplateArgs().asArray(); } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { if (auto *Tmplt = FD->getPrimaryTemplate()) { Template = Tmplt; Args = FD->getTemplateSpecializationArgs()->asArray(); } } if (Template) Template->loadLazySpecializationsImpl(Args); } CXXCtorInitializer ** ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { RecordLocation Loc = getLocalBitOffset(Offset); BitstreamCursor &Cursor = Loc.F->DeclsCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(Loc.Offset); ReadingKindTracker ReadingKind(Read_Decl, *this); RecordData Record; unsigned Code = Cursor.ReadCode(); unsigned RecCode = Cursor.readRecord(Code, Record); if (RecCode != DECL_CXX_CTOR_INITIALIZERS) { Error("malformed AST file: missing C++ ctor initializers"); return nullptr; } unsigned Idx = 0; return ReadCXXCtorInitializers(*Loc.F, Record, Idx); } CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { assert(ContextObj && "reading base specifiers with no AST context"); ASTContext &Context = *ContextObj; RecordLocation Loc = getLocalBitOffset(Offset); BitstreamCursor &Cursor = Loc.F->DeclsCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(Loc.Offset); ReadingKindTracker ReadingKind(Read_Decl, *this); RecordData Record; unsigned Code = Cursor.ReadCode(); unsigned RecCode = Cursor.readRecord(Code, Record); if (RecCode != DECL_CXX_BASE_SPECIFIERS) { Error("malformed AST file: missing C++ base specifiers"); return nullptr; } unsigned Idx = 0; unsigned NumBases = Record[Idx++]; void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases); CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; for (unsigned I = 0; I != NumBases; ++I) Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx); return Bases; } serialization::DeclID ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const { if (LocalID < NUM_PREDEF_DECL_IDS) return LocalID; if (!F.ModuleOffsetMap.empty()) ReadModuleOffsetMap(F); ContinuousRangeMap<uint32_t, int, 2>::iterator I = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS); assert(I != F.DeclRemap.end() && "Invalid index into decl index remap"); return LocalID + I->second; } bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const { // Predefined decls aren't from any module. if (ID < NUM_PREDEF_DECL_IDS) return false; return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID && ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls; } ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) { if (!D->isFromASTFile()) return nullptr; GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID()); assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); return I->second; } SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) { if (ID < NUM_PREDEF_DECL_IDS) return SourceLocation(); unsigned Index = ID - NUM_PREDEF_DECL_IDS; if (Index > NumDeclsLoaded) { Error("declaration ID out-of-range for AST file"); return SourceLocation(); } auto FindRes = DeclsLoaded.find(Index); if (FindRes != DeclsLoaded.end()) return FindRes->second->getLocation(); SourceLocation Loc; DeclCursorForID(ID, Loc); return Loc; } static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) { switch (ID) { case PREDEF_DECL_NULL_ID: return nullptr; case PREDEF_DECL_TRANSLATION_UNIT_ID: return Context.getTranslationUnitDecl(); case PREDEF_DECL_OBJC_ID_ID: return Context.getObjCIdDecl(); case PREDEF_DECL_OBJC_SEL_ID: return Context.getObjCSelDecl(); case PREDEF_DECL_OBJC_CLASS_ID: return Context.getObjCClassDecl(); case PREDEF_DECL_OBJC_PROTOCOL_ID: return Context.getObjCProtocolDecl(); case PREDEF_DECL_INT_128_ID: return Context.getInt128Decl(); case PREDEF_DECL_UNSIGNED_INT_128_ID: return Context.getUInt128Decl(); case PREDEF_DECL_OBJC_INSTANCETYPE_ID: return Context.getObjCInstanceTypeDecl(); case PREDEF_DECL_BUILTIN_VA_LIST_ID: return Context.getBuiltinVaListDecl(); case PREDEF_DECL_VA_LIST_TAG: return Context.getVaListTagDecl(); case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID: return Context.getBuiltinMSVaListDecl(); case PREDEF_DECL_EXTERN_C_CONTEXT_ID: return Context.getExternCContextDecl(); case PREDEF_DECL_MAKE_INTEGER_SEQ_ID: return Context.getMakeIntegerSeqDecl(); case PREDEF_DECL_CF_CONSTANT_STRING_ID: return Context.getCFConstantStringDecl(); case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID: return Context.getCFConstantStringTagDecl(); case PREDEF_DECL_TYPE_PACK_ELEMENT_ID: return Context.getTypePackElementDecl(); } llvm_unreachable("PredefinedDeclIDs unknown enum value"); } Decl *ASTReader::GetExistingDecl(DeclID ID) { assert(ContextObj && "reading decl with no AST context"); if (ID < NUM_PREDEF_DECL_IDS) { Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID); if (D) { // Track that we have merged the declaration with ID \p ID into the // pre-existing predefined declaration \p D. auto &Merged = KeyDecls[D->getCanonicalDecl()]; if (Merged.empty()) Merged.push_back(ID); } return D; } unsigned Index = ID - NUM_PREDEF_DECL_IDS; if (Index >= NumDeclsLoaded) { assert(0 && "declaration ID out-of-range for AST file"); Error("declaration ID out-of-range for AST file"); return nullptr; } auto FindRes = DeclsLoaded.find(Index); if (FindRes == DeclsLoaded.end()) return nullptr; return FindRes->second; } Decl *ASTReader::GetDecl(DeclID ID) { if (ID < NUM_PREDEF_DECL_IDS) return GetExistingDecl(ID); unsigned Index = ID - NUM_PREDEF_DECL_IDS; if (Index >= NumDeclsLoaded) { assert(0 && "declaration ID out-of-range for AST file"); Error("declaration ID out-of-range for AST file"); return nullptr; } if (DeclsLoaded.find(Index) == DeclsLoaded.end()) { ReadDeclRecord(ID); if (DeserializationListener) DeserializationListener->DeclRead(ID, DeclsLoaded.find(Index)->second); } return DeclsLoaded.find(Index)->second; } DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, DeclID GlobalID) { if (GlobalID < NUM_PREDEF_DECL_IDS) return GlobalID; GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID); assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); ModuleFile *Owner = I->second; llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos = M.GlobalToLocalDeclIDs.find(Owner); if (Pos == M.GlobalToLocalDeclIDs.end()) return 0; return GlobalID - Owner->BaseDeclID + Pos->second; } serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F, const RecordData &Record, unsigned &Idx) { if (Idx >= Record.size()) { Error("Corrupted AST file"); return 0; } return getGlobalDeclID(F, Record[Idx++]); } /// \brief Resolve the offset of a statement into a statement. /// /// This operation will read a new statement from the external /// source each time it is called, and is meant to be used via a /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { // Switch case IDs are per Decl. ClearSwitchCaseIDs(); // Offset here is a global offset across the entire chain. RecordLocation Loc = getLocalBitOffset(Offset); Loc.F->DeclsCursor.JumpToBit(Loc.Offset); assert(NumCurrentElementsDeserializing == 0 && "should not be called while already deserializing"); Deserializing D(this); return ReadStmtFromStream(*Loc.F); } void ASTReader::FindExternalLexicalDecls( const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl<Decl *> &Decls) { bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {}; auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) { assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries"); for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) { auto K = (Decl::Kind)+LexicalDecls[I]; if (!IsKindWeWant(K)) continue; auto ID = (serialization::DeclID)+LexicalDecls[I + 1]; // Don't add predefined declarations to the lexical context more // than once. if (ID < NUM_PREDEF_DECL_IDS) { if (PredefsVisited[ID]) continue; PredefsVisited[ID] = true; } if (Decl *D = GetLocalDecl(*M, ID)) { assert(D->getKind() == K && "wrong kind for lexical decl"); if (!DC->isDeclInLexicalTraversal(D)) Decls.push_back(D); } } }; if (isa<TranslationUnitDecl>(DC)) { for (auto Lexical : TULexicalDecls) Visit(Lexical.first, Lexical.second); } else { auto I = LexicalDecls.find(DC); if (I != LexicalDecls.end()) Visit(I->second.first, I->second.second); } ++NumLexicalDeclContextsRead; } namespace { class DeclIDComp { ASTReader &Reader; ModuleFile &Mod; public: DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {} bool operator()(LocalDeclID L, LocalDeclID R) const { SourceLocation LHS = getLocation(L); SourceLocation RHS = getLocation(R); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } bool operator()(SourceLocation LHS, LocalDeclID R) const { SourceLocation RHS = getLocation(R); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } bool operator()(LocalDeclID L, SourceLocation RHS) const { SourceLocation LHS = getLocation(L); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } SourceLocation getLocation(LocalDeclID ID) const { return Reader.getSourceManager().getFileLoc( Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID))); } }; } // end anonymous namespace void ASTReader::FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl<Decl *> &Decls) { SourceManager &SM = getSourceManager(); llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File); if (I == FileDeclIDs.end()) return; FileDeclsInfo &DInfo = I->second; if (DInfo.Decls.empty()) return; SourceLocation BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset); SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length); DeclIDComp DIDComp(*this, *DInfo.Mod); ArrayRef<serialization::LocalDeclID>::iterator BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(), BeginLoc, DIDComp); if (BeginIt != DInfo.Decls.begin()) --BeginIt; // If we are pointing at a top-level decl inside an objc container, we need // to backtrack until we find it otherwise we will fail to report that the // region overlaps with an objc container. while (BeginIt != DInfo.Decls.begin() && GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt)) ->isTopLevelDeclInObjCContainer()) --BeginIt; ArrayRef<serialization::LocalDeclID>::iterator EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(), EndLoc, DIDComp); if (EndIt != DInfo.Decls.end()) ++EndIt; for (ArrayRef<serialization::LocalDeclID>::iterator DIt = BeginIt; DIt != EndIt; ++DIt) Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt))); } bool ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) { assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() && "DeclContext has no visible decls in storage"); if (!Name) return false; auto It = Lookups.find(DC); if (It == Lookups.end()) return false; Deserializing LookupResults(this); // Load the list of declarations. SmallVector<NamedDecl *, 64> Decls; for (DeclID ID : It->second.Table.find(Name)) { NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); if (ND->getDeclName() == Name) Decls.push_back(ND); } ++NumVisibleDeclContextsRead; SetExternalVisibleDeclsForName(DC, Name, Decls); return !Decls.empty(); } void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) { if (!DC->hasExternalVisibleStorage()) return; auto It = Lookups.find(DC); assert(It != Lookups.end() && "have external visible storage but no lookup tables"); DeclsMap Decls; for (DeclID ID : It->second.Table.findAll()) { NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); Decls[ND->getDeclName()].push_back(ND); } ++NumVisibleDeclContextsRead; for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) { SetExternalVisibleDeclsForName(DC, I->first, I->second); } const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false); } const serialization::reader::DeclContextLookupTable * ASTReader::getLoadedLookupTables(DeclContext *Primary) const { auto I = Lookups.find(Primary); return I == Lookups.end() ? nullptr : &I->second; } /// \brief Under non-PCH compilation the consumer receives the objc methods /// before receiving the implementation, and codegen depends on this. /// We simulate this by deserializing and passing to consumer the methods of the /// implementation before passing the deserialized implementation decl. static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer) { assert(ImplD && Consumer); for (auto *I : ImplD->methods()) Consumer->HandleInterestingDecl(DeclGroupRef(I)); Consumer->HandleInterestingDecl(DeclGroupRef(ImplD)); } void ASTReader::PassInterestingDeclToConsumer(Decl *D) { if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) PassObjCImplDeclToConsumer(ImplD, Consumer); else Consumer->HandleInterestingDecl(DeclGroupRef(D)); } void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { this->Consumer = Consumer; if (Consumer) PassInterestingDeclsToConsumer(); if (DeserializationListener) DeserializationListener->ReaderInitialized(this); } void ASTReader::PrintStats() { std::fprintf(stderr, "*** AST File Statistics:\n"); unsigned NumTypesLoaded = TypesLoaded.size(); unsigned NumDeclsLoaded = DeclsLoaded.size(); unsigned NumIdentifiersLoaded = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(), IdentifiersLoaded.end(), (IdentifierInfo *)nullptr); unsigned NumMacrosLoaded = MacrosLoaded.size(); unsigned NumSelectorsLoaded = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(), SelectorsLoaded.end(), Selector()); if (unsigned TotalNumSLocEntries = getTotalNumSLocs()) std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n", NumSLocEntriesRead, TotalNumSLocEntries, ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); if (!TypesLoaded.empty()) std::fprintf(stderr, " %u/%u types read (%f%%)\n", NumTypesLoaded, (unsigned)TypesLoaded.size(), ((float)NumTypesLoaded/TypesLoaded.size() * 100)); if (!DeclsLoaded.empty()) std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", NumDeclsLoaded, (unsigned)DeclsLoaded.size(), ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); if (!IdentifiersLoaded.empty()) std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); if (!MacrosLoaded.empty()) std::fprintf(stderr, " %u/%u macros read (%f%%)\n", NumMacrosLoaded, (unsigned)MacrosLoaded.size(), ((float)NumMacrosLoaded/MacrosLoaded.size() * 100)); if (!SelectorsLoaded.empty()) std::fprintf(stderr, " %u/%u selectors read (%f%%)\n", NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); if (TotalNumStatements) std::fprintf(stderr, " %u/%u statements read (%f%%)\n", NumStatementsRead, TotalNumStatements, ((float)NumStatementsRead/TotalNumStatements * 100)); if (TotalNumMacros) std::fprintf(stderr, " %u/%u macros read (%f%%)\n", NumMacrosRead, TotalNumMacros, ((float)NumMacrosRead/TotalNumMacros * 100)); if (TotalLexicalDeclContexts) std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n", NumLexicalDeclContextsRead, TotalLexicalDeclContexts, ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts * 100)); if (TotalVisibleDeclContexts) std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n", NumVisibleDeclContextsRead, TotalVisibleDeclContexts, ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts * 100)); if (TotalNumMethodPoolEntries) { std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n", NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries * 100)); } if (NumMethodPoolLookups) { std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n", NumMethodPoolHits, NumMethodPoolLookups, ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0)); } if (NumMethodPoolTableLookups) { std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n", NumMethodPoolTableHits, NumMethodPoolTableLookups, ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups * 100.0)); } if (NumIdentifierLookupHits) { std::fprintf(stderr, " %u / %u identifier table lookups succeeded (%f%%)\n", NumIdentifierLookupHits, NumIdentifierLookups, (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups); } if (GlobalIndex) { std::fprintf(stderr, "\n"); GlobalIndex->printStats(); } std::fprintf(stderr, "\n"); dump(); std::fprintf(stderr, "\n"); } template<typename Key, typename ModuleFile, unsigned InitialCapacity> LLVM_DUMP_METHOD static void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> &Map) { if (Map.begin() == Map.end()) return; typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType; llvm::errs() << Name << ":\n"; for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); I != IEnd; ++I) { llvm::errs() << " " << I->first << " -> " << I->second->FileName << "\n"; } } LLVM_DUMP_METHOD void ASTReader::dump() { llvm::errs() << "*** PCH/ModuleFile Remappings:\n"; dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap); dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap); dumpModuleIDMap("Global type map", GlobalTypeMap); dumpModuleIDMap("Global declaration map", GlobalDeclMap); dumpModuleIDMap("Global identifier map", GlobalIdentifierMap); dumpModuleIDMap("Global macro map", GlobalMacroMap); dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap); dumpModuleIDMap("Global selector map", GlobalSelectorMap); dumpModuleIDMap("Global preprocessed entity map", GlobalPreprocessedEntityMap); llvm::errs() << "\n*** PCH/Modules Loaded:"; for (ModuleFile &M : ModuleMgr) M.dump(); } /// Return the amount of memory used by memory buffers, breaking down /// by heap-backed versus mmap'ed memory. void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { for (ModuleFile &I : ModuleMgr) { if (llvm::MemoryBuffer *buf = I.Buffer) { size_t bytes = buf->getBufferSize(); switch (buf->getBufferKind()) { case llvm::MemoryBuffer::MemoryBuffer_Malloc: sizes.malloc_bytes += bytes; break; case llvm::MemoryBuffer::MemoryBuffer_MMap: sizes.mmap_bytes += bytes; break; } } } } void ASTReader::InitializeSema(Sema &S) { SemaObj = &S; S.addExternalSource(this); // Makes sure any declarations that were deserialized "too early" // still get added to the identifier's declaration chains. for (uint64_t ID : PreloadedDeclIDs) { NamedDecl *D = cast<NamedDecl>(GetDecl(ID)); pushExternalDeclIntoScope(D, D->getDeclName()); } PreloadedDeclIDs.clear(); // FIXME: What happens if these are changed by a module import? if (!FPPragmaOptions.empty()) { assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS"); SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]); } SemaObj->OpenCLFeatures.copy(OpenCLExtensions); SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap; SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap; UpdateSema(); } void ASTReader::UpdateSema() { assert(SemaObj && "no Sema to update"); // Load the offsets of the declarations that Sema references. // They will be lazily deserialized when needed. if (!SemaDeclRefs.empty()) { assert(SemaDeclRefs.size() % 3 == 0); for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) { if (!SemaObj->StdNamespace) SemaObj->StdNamespace = SemaDeclRefs[I]; if (!SemaObj->StdBadAlloc) SemaObj->StdBadAlloc = SemaDeclRefs[I+1]; if (!SemaObj->StdAlignValT) SemaObj->StdAlignValT = SemaDeclRefs[I+2]; } SemaDeclRefs.clear(); } // Update the state of pragmas. Use the same API as if we had encountered the // pragma in the source. if(OptimizeOffPragmaLocation.isValid()) SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation); if (PragmaMSStructState != -1) SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState); if (PointersToMembersPragmaLocation.isValid()) { SemaObj->ActOnPragmaMSPointersToMembers( (LangOptions::PragmaMSPointersToMembersKind) PragmaMSPointersToMembersState, PointersToMembersPragmaLocation); } SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth; if (PragmaPackCurrentValue) { // The bottom of the stack might have a default value. It must be adjusted // to the current value to ensure that the packing state is preserved after // popping entries that were included/imported from a PCH/module. bool DropFirst = false; if (!PragmaPackStack.empty() && PragmaPackStack.front().Location.isInvalid()) { assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue && "Expected a default alignment value"); SemaObj->PackStack.Stack.emplace_back( PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue, SemaObj->PackStack.CurrentPragmaLocation); DropFirst = true; } for (const auto &Entry : llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0)) SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value, Entry.Location); if (PragmaPackCurrentLocation.isInvalid()) { assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue && "Expected a default alignment value"); // Keep the current values. } else { SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue; SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation; } } } IdentifierInfo *ASTReader::get(StringRef Name) { // Note that we are loading an identifier. Deserializing AnIdentifier(this); IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, NumIdentifierLookups, NumIdentifierLookupHits); // We don't need to do identifier table lookups in C++ modules (we preload // all interesting declarations, and don't need to use the scope for name // lookups). Perform the lookup in PCH files, though, since we don't build // a complete initial identifier table if we're carrying on from a PCH. if (PP.getLangOpts().CPlusPlus) { for (auto F : ModuleMgr.pch_modules()) if (Visitor(*F)) break; } else { // If there is a global index, look there first to determine which modules // provably do not have any results for this identifier. GlobalModuleIndex::HitSet Hits; GlobalModuleIndex::HitSet *HitsPtr = nullptr; if (!loadGlobalIndex()) { if (GlobalIndex->lookupIdentifier(Name, Hits)) { HitsPtr = &Hits; } } ModuleMgr.visit(Visitor, HitsPtr); } IdentifierInfo *II = Visitor.getIdentifierInfo(); markIdentifierUpToDate(II); return II; } namespace clang { /// \brief An identifier-lookup iterator that enumerates all of the /// identifiers stored within a set of AST files. class ASTIdentifierIterator : public IdentifierIterator { /// \brief The AST reader whose identifiers are being enumerated. const ASTReader &Reader; /// \brief The current index into the chain of AST files stored in /// the AST reader. unsigned Index; /// \brief The current position within the identifier lookup table /// of the current AST file. ASTIdentifierLookupTable::key_iterator Current; /// \brief The end position within the identifier lookup table of /// the current AST file. ASTIdentifierLookupTable::key_iterator End; /// \brief Whether to skip any modules in the ASTReader. bool SkipModules; public: explicit ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules = false); StringRef Next() override; }; } // end namespace clang ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules) : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { } StringRef ASTIdentifierIterator::Next() { while (Current == End) { // If we have exhausted all of our AST files, we're done. if (Index == 0) return StringRef(); --Index; ModuleFile &F = Reader.ModuleMgr[Index]; if (SkipModules && F.isModule()) continue; ASTIdentifierLookupTable *IdTable = (ASTIdentifierLookupTable *)F.IdentifierLookupTable; Current = IdTable->key_begin(); End = IdTable->key_end(); } // We have any identifiers remaining in the current AST file; return // the next one. StringRef Result = *Current; ++Current; return Result; } namespace { /// A utility for appending two IdentifierIterators. class ChainedIdentifierIterator : public IdentifierIterator { std::unique_ptr<IdentifierIterator> Current; std::unique_ptr<IdentifierIterator> Queued; public: ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, std::unique_ptr<IdentifierIterator> Second) : Current(std::move(First)), Queued(std::move(Second)) {} StringRef Next() override { if (!Current) return StringRef(); StringRef result = Current->Next(); if (!result.empty()) return result; // Try the queued iterator, which may itself be empty. Current.reset(); std::swap(Current, Queued); return Next(); } }; } // end anonymous namespace. IdentifierIterator *ASTReader::getIdentifiers() { if (!loadGlobalIndex()) { std::unique_ptr<IdentifierIterator> ReaderIter( new ASTIdentifierIterator(*this, /*SkipModules=*/true)); std::unique_ptr<IdentifierIterator> ModulesIter( GlobalIndex->createIdentifierIterator()); return new ChainedIdentifierIterator(std::move(ReaderIter), std::move(ModulesIter)); } return new ASTIdentifierIterator(*this); } namespace clang { namespace serialization { class ReadMethodPoolVisitor { ASTReader &Reader; Selector Sel; unsigned PriorGeneration; unsigned InstanceBits; unsigned FactoryBits; bool InstanceHasMoreThanOneDecl; bool FactoryHasMoreThanOneDecl; SmallVector<ObjCMethodDecl *, 4> InstanceMethods; SmallVector<ObjCMethodDecl *, 4> FactoryMethods; public: ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration) : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration), InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false), FactoryHasMoreThanOneDecl(false) {} bool operator()(ModuleFile &M) { if (!M.SelectorLookupTable) return false; // If we've already searched this module file, skip it now. if (M.Generation <= PriorGeneration) return true; ++Reader.NumMethodPoolTableLookups; ASTSelectorLookupTable *PoolTable = (ASTSelectorLookupTable*)M.SelectorLookupTable; ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); if (Pos == PoolTable->end()) return false; ++Reader.NumMethodPoolTableHits; ++Reader.NumSelectorsRead; // FIXME: Not quite happy with the statistics here. We probably should // disable this tracking when called via LoadSelector. // Also, should entries without methods count as misses? ++Reader.NumMethodPoolEntriesRead; ASTSelectorLookupTrait::data_type Data = *Pos; if (Reader.DeserializationListener) Reader.DeserializationListener->SelectorRead(Data.ID, Sel); InstanceMethods.append(Data.Instance.begin(), Data.Instance.end()); FactoryMethods.append(Data.Factory.begin(), Data.Factory.end()); InstanceBits = Data.InstanceBits; FactoryBits = Data.FactoryBits; InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; return true; } /// \brief Retrieve the instance methods found by this visitor. ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { return InstanceMethods; } /// \brief Retrieve the instance methods found by this visitor. ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { return FactoryMethods; } unsigned getInstanceBits() const { return InstanceBits; } unsigned getFactoryBits() const { return FactoryBits; } bool instanceHasMoreThanOneDecl() const { return InstanceHasMoreThanOneDecl; } bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } }; } // end namespace serialization } // end namespace clang /// \brief Add the given set of methods to the method list. static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, ObjCMethodList &List) { for (unsigned I = 0, N = Methods.size(); I != N; ++I) { S.addMethodToGlobalList(&List, Methods[I]); } } void ASTReader::ReadMethodPool(Selector Sel) { // Get the selector generation and update it to the current generation. unsigned &Generation = SelectorGeneration[Sel]; unsigned PriorGeneration = Generation; Generation = getGenerationOrNull(); SelectorOutOfDate[Sel] = false; // Search for methods defined with this selector. ++NumMethodPoolLookups; ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); ModuleMgr.visit(Visitor); if (Visitor.getInstanceMethods().empty() && Visitor.getFactoryMethods().empty()) return; ++NumMethodPoolHits; if (!getSema()) return; Sema &S = *getSema(); Sema::GlobalMethodPool::iterator Pos = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first; Pos->second.first.setBits(Visitor.getInstanceBits()); Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); Pos->second.second.setBits(Visitor.getFactoryBits()); Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); // Add methods to the global pool *after* setting hasMoreThanOneDecl, since // when building a module we keep every method individually and may need to // update hasMoreThanOneDecl as we add the methods. addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first); addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second); } void ASTReader::updateOutOfDateSelector(Selector Sel) { if (SelectorOutOfDate[Sel]) ReadMethodPool(Sel); } void ASTReader::ReadKnownNamespaces( SmallVectorImpl<NamespaceDecl *> &Namespaces) { Namespaces.clear(); for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { if (NamespaceDecl *Namespace = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) Namespaces.push_back(Namespace); } } void ASTReader::ReadUndefinedButUsed( llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++])); SourceLocation Loc = SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]); Undefined.insert(std::make_pair(D, Loc)); } } void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & Exprs) { for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++])); uint64_t Count = DelayedDeleteExprs[Idx++]; for (uint64_t C = 0; C < Count; ++C) { SourceLocation DeleteLoc = SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]); const bool IsArrayForm = DelayedDeleteExprs[Idx++]; Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm)); } } } void ASTReader::ReadTentativeDefinitions( SmallVectorImpl<VarDecl *> &TentativeDefs) { for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I])); if (Var) TentativeDefs.push_back(Var); } TentativeDefinitions.clear(); } void ASTReader::ReadUnusedFileScopedDecls( SmallVectorImpl<const DeclaratorDecl *> &Decls) { for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { DeclaratorDecl *D = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); if (D) Decls.push_back(D); } UnusedFileScopedDecls.clear(); } void ASTReader::ReadDelegatingConstructors( SmallVectorImpl<CXXConstructorDecl *> &Decls) { for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { CXXConstructorDecl *D = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); if (D) Decls.push_back(D); } DelegatingCtorDecls.clear(); } void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])); if (D) Decls.push_back(D); } ExtVectorDecls.clear(); } void ASTReader::ReadUnusedLocalTypedefNameCandidates( llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; ++I) { TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( GetDecl(UnusedLocalTypedefNameCandidates[I])); if (D) Decls.insert(D); } UnusedLocalTypedefNameCandidates.clear(); } void ASTReader::ReadReferencedSelectors( SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) { if (ReferencedSelectorsData.empty()) return; // If there are @selector references added them to its pool. This is for // implementation of -Wselector. unsigned int DataSize = ReferencedSelectorsData.size()-1; unsigned I = 0; while (I < DataSize) { Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]); SourceLocation SelLoc = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]); Sels.push_back(std::make_pair(Sel, SelLoc)); } ReferencedSelectorsData.clear(); } void ASTReader::ReadWeakUndeclaredIdentifiers( SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) { if (WeakUndeclaredIdentifiers.empty()) return; for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { IdentifierInfo *WeakId = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); IdentifierInfo *AliasId = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); SourceLocation Loc = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]); bool Used = WeakUndeclaredIdentifiers[I++]; WeakInfo WI(AliasId, Loc); WI.setUsed(Used); WeakIDs.push_back(std::make_pair(WeakId, WI)); } WeakUndeclaredIdentifiers.clear(); } void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { ExternalVTableUse VT; VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++])); VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]); VT.DefinitionRequired = VTableUses[Idx++]; VTables.push_back(VT); } VTableUses.clear(); } void ASTReader::ReadPendingInstantiations( SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) { for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++])); SourceLocation Loc = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]); Pending.push_back(std::make_pair(D, Loc)); } PendingInstantiations.clear(); } void ASTReader::ReadLateParsedTemplates( llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> &LPTMap) { for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N; /* In loop */) { FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++])); auto LT = llvm::make_unique<LateParsedTemplate>(); LT->D = GetDecl(LateParsedTemplates[Idx++]); ModuleFile *F = getOwningModuleFile(LT->D); assert(F && "No module"); unsigned TokN = LateParsedTemplates[Idx++]; LT->Toks.reserve(TokN); for (unsigned T = 0; T < TokN; ++T) LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx)); LPTMap.insert(std::make_pair(FD, std::move(LT))); } LateParsedTemplates.clear(); } void ASTReader::LoadSelector(Selector Sel) { // It would be complicated to avoid reading the methods anyway. So don't. ReadMethodPool(Sel); } void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { assert(ID && "Non-zero identifier ID required"); assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range"); IdentifiersLoaded[ID - 1] = II; if (DeserializationListener) DeserializationListener->IdentifierRead(ID, II); } /// \brief Set the globally-visible declarations associated with the given /// identifier. /// /// If the AST reader is currently in a state where the given declaration IDs /// cannot safely be resolved, they are queued until it is safe to resolve /// them. /// /// \param II an IdentifierInfo that refers to one or more globally-visible /// declarations. /// /// \param DeclIDs the set of declaration IDs with the name @p II that are /// visible at global scope. /// /// \param Decls if non-null, this vector will be populated with the set of /// deserialized declarations. These declarations will not be pushed into /// scope. void ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl<uint32_t> &DeclIDs, SmallVectorImpl<Decl *> *Decls) { if (NumCurrentElementsDeserializing && !Decls) { PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end()); return; } for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { if (!SemaObj) { // Queue this declaration so that it will be added to the // translation unit scope and identifier's declaration chain // once a Sema object is known. PreloadedDeclIDs.push_back(DeclIDs[I]); continue; } NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); // If we're simply supposed to record the declarations, do so now. if (Decls) { Decls->push_back(D); continue; } // Introduce this declaration into the translation-unit scope // and add it to the declaration chain for this identifier, so // that (unqualified) name lookup will find it. pushExternalDeclIntoScope(D, II); } } IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { if (ID == 0) return nullptr; if (IdentifiersLoaded.empty()) { Error("no identifier table in AST file"); return nullptr; } ID -= 1; if (!IdentifiersLoaded[ID]) { GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1); assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map"); ModuleFile *M = I->second; unsigned Index = ID - M->BaseIdentifierID; const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index]; // All of the strings in the AST file are preceded by a 16-bit length. // Extract that 16-bit length to avoid having to execute strlen(). // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as // unsigned integers. This is important to avoid integer overflow when // we cast them to 'unsigned'. const unsigned char *StrLenPtr = (const unsigned char*) Str - 2; unsigned StrLen = (((unsigned) StrLenPtr[0]) | (((unsigned) StrLenPtr[1]) << 8)) - 1; auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen)); IdentifiersLoaded[ID] = &II; markIdentifierFromAST(*this, II); if (DeserializationListener) DeserializationListener->IdentifierRead(ID + 1, &II); } return IdentifiersLoaded[ID]; } IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) { return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID)); } IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) { if (LocalID < NUM_PREDEF_IDENT_IDS) return LocalID; if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::iterator I = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS); assert(I != M.IdentifierRemap.end() && "Invalid index into identifier index remap"); return LocalID + I->second; } MacroInfo *ASTReader::getMacro(MacroID ID) { if (ID == 0) return nullptr; if (!NumMacrosLoaded) { Error("no macro table in AST file"); return nullptr; } ID -= NUM_PREDEF_MACRO_IDS; auto FindRes = MacrosLoaded.find(ID); if (FindRes == MacrosLoaded.end()) { GlobalMacroMapType::iterator I = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS); assert(I != GlobalMacroMap.end() && "Corrupted global macro map"); ModuleFile *M = I->second; unsigned Index = ID - M->BaseMacroID; MacroInfo *MI = ReadMacroRecord(*M, M->MacroOffsets[Index]); MacrosLoaded.insert({ID, MI}); if (DeserializationListener) DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS, MI); } FindRes = MacrosLoaded.find(ID); if (FindRes == MacrosLoaded.end()) return nullptr; return FindRes->second; } MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { if (LocalID < NUM_PREDEF_MACRO_IDS) return LocalID; if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::iterator I = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS); assert(I != M.MacroRemap.end() && "Invalid index into macro index remap"); return LocalID + I->second; } serialization::SubmoduleID ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) { if (LocalID < NUM_PREDEF_SUBMODULE_IDS) return LocalID; if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::iterator I = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS); assert(I != M.SubmoduleRemap.end() && "Invalid index into submodule index remap"); return LocalID + I->second; } Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { assert(GlobalID == 0 && "Unhandled global submodule ID"); return nullptr; } if (GlobalID > SubmodulesLoaded.size()) { Error("submodule ID out of range in AST file"); return nullptr; } return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; } Module *ASTReader::getModule(unsigned ID) { return getSubmodule(ID); } ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) { if (ID & 1) { // It's a module, look it up by submodule ID. auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1)); return I == GlobalSubmoduleMap.end() ? nullptr : I->second; } else { // It's a prefix (preamble, PCH, ...). Look it up by index. unsigned IndexFromEnd = ID >> 1; assert(IndexFromEnd && "got reference to unknown module file"); return getModuleManager().pch_modules().end()[-IndexFromEnd]; } } unsigned ASTReader::getModuleFileID(ModuleFile *F) { if (!F) return 1; // For a file representing a module, use the submodule ID of the top-level // module as the file ID. For any other kind of file, the number of such // files loaded beforehand will be the same on reload. // FIXME: Is this true even if we have an explicit module file and a PCH? if (F->isModule()) return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; auto PCHModules = getModuleManager().pch_modules(); auto I = std::find(PCHModules.begin(), PCHModules.end(), F); assert(I != PCHModules.end() && "emitting reference to unknown file"); return (I - PCHModules.end()) << 1; } llvm::Optional<ExternalASTSource::ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) { if (const Module *M = getSubmodule(ID)) return ExternalASTSource::ASTSourceDescriptor(*M); // If there is only a single PCH, return it instead. // Chained PCH are not supported. const auto &PCHChain = ModuleMgr.pch_modules(); if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { ModuleFile &MF = ModuleMgr.getPrimaryModule(); StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName); StringRef FileName = llvm::sys::path::filename(MF.FileName); return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName, MF.Signature); } return None; } ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) { auto I = BodySource.find(FD); if (I == BodySource.end()) return EK_ReplyHazy; return I->second ? EK_Never : EK_Always; } Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { return DecodeSelector(getGlobalSelectorID(M, LocalID)); } Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { if (ID == 0) return Selector(); if (ID > SelectorsLoaded.size()) { Error("selector ID out of range in AST file"); return Selector(); } if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { // Load this selector from the selector table. GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); ModuleFile &M = *I->second; ASTSelectorLookupTrait Trait(*this, M); unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; SelectorsLoaded[ID - 1] = Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); if (DeserializationListener) DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); } return SelectorsLoaded[ID - 1]; } Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { return DecodeSelector(ID); } uint32_t ASTReader::GetNumExternalSelectors() { // ID 0 (the null selector) is considered an external selector. return getTotalNumSelectors() + 1; } serialization::SelectorID ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { if (LocalID < NUM_PREDEF_SELECTOR_IDS) return LocalID; if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::iterator I = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS); assert(I != M.SelectorRemap.end() && "Invalid index into selector index remap"); return LocalID + I->second; } DeclarationName ASTReader::ReadDeclarationName(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++]; switch (Kind) { case DeclarationName::Identifier: return DeclarationName(GetIdentifierInfo(F, Record, Idx)); case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: return DeclarationName(ReadSelector(F, Record, Idx)); case DeclarationName::CXXConstructorName: return Context.DeclarationNames.getCXXConstructorName( Context.getCanonicalType(readType(F, Record, Idx))); case DeclarationName::CXXDestructorName: return Context.DeclarationNames.getCXXDestructorName( Context.getCanonicalType(readType(F, Record, Idx))); case DeclarationName::CXXDeductionGuideName: return Context.DeclarationNames.getCXXDeductionGuideName( ReadDeclAs<TemplateDecl>(F, Record, Idx)); case DeclarationName::CXXConversionFunctionName: return Context.DeclarationNames.getCXXConversionFunctionName( Context.getCanonicalType(readType(F, Record, Idx))); case DeclarationName::CXXOperatorName: return Context.DeclarationNames.getCXXOperatorName( (OverloadedOperatorKind)Record[Idx++]); case DeclarationName::CXXLiteralOperatorName: return Context.DeclarationNames.getCXXLiteralOperatorName( GetIdentifierInfo(F, Record, Idx)); case DeclarationName::CXXUsingDirective: return DeclarationName::getUsingDirectiveName(); } llvm_unreachable("Invalid NameKind!"); } void ASTReader::ReadDeclarationNameLoc(ModuleFile &F, DeclarationNameLoc &DNLoc, DeclarationName Name, const RecordData &Record, unsigned &Idx) { switch (Name.getNameKind()) { case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx); break; case DeclarationName::CXXOperatorName: DNLoc.CXXOperatorName.BeginOpNameLoc = ReadSourceLocation(F, Record, Idx).getRawEncoding(); DNLoc.CXXOperatorName.EndOpNameLoc = ReadSourceLocation(F, Record, Idx).getRawEncoding(); break; case DeclarationName::CXXLiteralOperatorName: DNLoc.CXXLiteralOperatorName.OpNameLoc = ReadSourceLocation(F, Record, Idx).getRawEncoding(); break; case DeclarationName::Identifier: case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: case DeclarationName::CXXUsingDirective: case DeclarationName::CXXDeductionGuideName: break; } } void ASTReader::ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo, const RecordData &Record, unsigned &Idx) { NameInfo.setName(ReadDeclarationName(F, Record, Idx)); NameInfo.setLoc(ReadSourceLocation(F, Record, Idx)); DeclarationNameLoc DNLoc; ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx); NameInfo.setInfo(DNLoc); } void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, const RecordData &Record, unsigned &Idx) { Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx); unsigned NumTPLists = Record[Idx++]; Info.NumTemplParamLists = NumTPLists; if (NumTPLists) { Info.TemplParamLists = new (getContext()) TemplateParameterList *[NumTPLists]; for (unsigned i = 0; i != NumTPLists; ++i) Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx); } } TemplateName ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++]; switch (Kind) { case TemplateName::Template: return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx)); case TemplateName::OverloadedTemplate: { unsigned size = Record[Idx++]; UnresolvedSet<8> Decls; while (size--) Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx)); return Context.getOverloadedTemplateName(Decls.begin(), Decls.end()); } case TemplateName::QualifiedTemplate: { NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx); bool hasTemplKeyword = Record[Idx++]; TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx); return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template); } case TemplateName::DependentTemplate: { NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx); if (Record[Idx++]) // isIdentifier return Context.getDependentTemplateName(NNS, GetIdentifierInfo(F, Record, Idx)); return Context.getDependentTemplateName(NNS, (OverloadedOperatorKind)Record[Idx++]); } case TemplateName::SubstTemplateTemplateParm: { TemplateTemplateParmDecl *param = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx); if (!param) return TemplateName(); TemplateName replacement = ReadTemplateName(F, Record, Idx); return Context.getSubstTemplateTemplateParm(param, replacement); } case TemplateName::SubstTemplateTemplateParmPack: { TemplateTemplateParmDecl *Param = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx); if (!Param) return TemplateName(); TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx); if (ArgPack.getKind() != TemplateArgument::Pack) return TemplateName(); return Context.getSubstTemplateTemplateParmPack(Param, ArgPack); } } llvm_unreachable("Unhandled template name kind!"); } TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F, const RecordData &Record, unsigned &Idx, bool Canonicalize) { ASTContext &Context = getContext(); if (Canonicalize) { // The caller wants a canonical template argument. Sometimes the AST only // wants template arguments in canonical form (particularly as the template // argument lists of template specializations) so ensure we preserve that // canonical form across serialization. TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false); return Context.getCanonicalTemplateArgument(Arg); } TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++]; switch (Kind) { case TemplateArgument::Null: return TemplateArgument(); case TemplateArgument::Type: return TemplateArgument(readType(F, Record, Idx)); case TemplateArgument::Declaration: { ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx); return TemplateArgument(D, readType(F, Record, Idx)); } case TemplateArgument::NullPtr: return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true); case TemplateArgument::Integral: { llvm::APSInt Value = ReadAPSInt(Record, Idx); QualType T = readType(F, Record, Idx); return TemplateArgument(Context, Value, T); } case TemplateArgument::Template: return TemplateArgument(ReadTemplateName(F, Record, Idx)); case TemplateArgument::TemplateExpansion: { TemplateName Name = ReadTemplateName(F, Record, Idx); Optional<unsigned> NumTemplateExpansions; if (unsigned NumExpansions = Record[Idx++]) NumTemplateExpansions = NumExpansions - 1; return TemplateArgument(Name, NumTemplateExpansions); } case TemplateArgument::Expression: return TemplateArgument(ReadExpr(F)); case TemplateArgument::Pack: { unsigned NumArgs = Record[Idx++]; TemplateArgument *Args = new (Context) TemplateArgument[NumArgs]; for (unsigned I = 0; I != NumArgs; ++I) Args[I] = ReadTemplateArgument(F, Record, Idx); return TemplateArgument(llvm::makeArrayRef(Args, NumArgs)); } } llvm_unreachable("Unhandled template argument kind!"); } TemplateParameterList * ASTReader::ReadTemplateParameterList(ModuleFile &F, const RecordData &Record, unsigned &Idx) { SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx); SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx); SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx); unsigned NumParams = Record[Idx++]; SmallVector<NamedDecl *, 16> Params; Params.reserve(NumParams); while (NumParams--) Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx)); // TODO: Concepts TemplateParameterList *TemplateParams = TemplateParameterList::Create( getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr); return TemplateParams; } void ASTReader:: ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs, ModuleFile &F, const RecordData &Record, unsigned &Idx, bool Canonicalize) { unsigned NumTemplateArgs = Record[Idx++]; TemplArgs.reserve(NumTemplateArgs); while (NumTemplateArgs--) TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize)); } /// \brief Read a UnresolvedSet structure. void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set, const RecordData &Record, unsigned &Idx) { unsigned NumDecls = Record[Idx++]; Set.reserve(getContext(), NumDecls); while (NumDecls--) { DeclID ID = ReadDeclID(F, Record, Idx); AccessSpecifier AS = (AccessSpecifier)Record[Idx++]; Set.addLazyDecl(getContext(), ID, AS); } } CXXBaseSpecifier ASTReader::ReadCXXBaseSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx) { bool isVirtual = static_cast<bool>(Record[Idx++]); bool isBaseOfClass = static_cast<bool>(Record[Idx++]); AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]); bool inheritConstructors = static_cast<bool>(Record[Idx++]); TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx); CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, EllipsisLoc); Result.setInheritConstructors(inheritConstructors); return Result; } CXXCtorInitializer ** ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); unsigned NumInitializers = Record[Idx++]; assert(NumInitializers && "wrote ctor initializers but have no inits"); auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; for (unsigned i = 0; i != NumInitializers; ++i) { TypeSourceInfo *TInfo = nullptr; bool IsBaseVirtual = false; FieldDecl *Member = nullptr; IndirectFieldDecl *IndirectMember = nullptr; CtorInitializerType Type = (CtorInitializerType)Record[Idx++]; switch (Type) { case CTOR_INITIALIZER_BASE: TInfo = GetTypeSourceInfo(F, Record, Idx); IsBaseVirtual = Record[Idx++]; break; case CTOR_INITIALIZER_DELEGATING: TInfo = GetTypeSourceInfo(F, Record, Idx); break; case CTOR_INITIALIZER_MEMBER: Member = ReadDeclAs<FieldDecl>(F, Record, Idx); break; case CTOR_INITIALIZER_INDIRECT_MEMBER: IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx); break; } SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx); Expr *Init = ReadExpr(F); SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx); SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx); CXXCtorInitializer *BOMInit; if (Type == CTOR_INITIALIZER_BASE) BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, RParenLoc, MemberOrEllipsisLoc); else if (Type == CTOR_INITIALIZER_DELEGATING) BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); else if (Member) BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc); else BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc); if (/*IsWritten*/Record[Idx++]) { unsigned SourceOrder = Record[Idx++]; BOMInit->setSourceOrder(SourceOrder); } CtorInitializers[i] = BOMInit; } return CtorInitializers; } NestedNameSpecifier * ASTReader::ReadNestedNameSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); unsigned N = Record[Idx++]; NestedNameSpecifier *NNS = nullptr, *Prev = nullptr; for (unsigned I = 0; I != N; ++I) { NestedNameSpecifier::SpecifierKind Kind = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; switch (Kind) { case NestedNameSpecifier::Identifier: { IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx); NNS = NestedNameSpecifier::Create(Context, Prev, II); break; } case NestedNameSpecifier::Namespace: { NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx); NNS = NestedNameSpecifier::Create(Context, Prev, NS); break; } case NestedNameSpecifier::NamespaceAlias: { NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx); NNS = NestedNameSpecifier::Create(Context, Prev, Alias); break; } case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { const Type *T = readType(F, Record, Idx).getTypePtrOrNull(); if (!T) return nullptr; bool Template = Record[Idx++]; NNS = NestedNameSpecifier::Create(Context, Prev, Template, T); break; } case NestedNameSpecifier::Global: { NNS = NestedNameSpecifier::GlobalSpecifier(Context); // No associated value, and there can't be a prefix. break; } case NestedNameSpecifier::Super: { CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx); NNS = NestedNameSpecifier::SuperSpecifier(Context, RD); break; } } Prev = NNS; } return NNS; } NestedNameSpecifierLoc ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); unsigned N = Record[Idx++]; NestedNameSpecifierLocBuilder Builder; for (unsigned I = 0; I != N; ++I) { NestedNameSpecifier::SpecifierKind Kind = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; switch (Kind) { case NestedNameSpecifier::Identifier: { IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); Builder.Extend(Context, II, Range.getBegin(), Range.getEnd()); break; } case NestedNameSpecifier::Namespace: { NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd()); break; } case NestedNameSpecifier::NamespaceAlias: { NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd()); break; } case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { bool Template = Record[Idx++]; TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx); if (!T) return NestedNameSpecifierLoc(); SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); // FIXME: 'template' keyword location not saved anywhere, so we fake it. Builder.Extend(Context, Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), T->getTypeLoc(), ColonColonLoc); break; } case NestedNameSpecifier::Global: { SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); Builder.MakeGlobal(Context, ColonColonLoc); break; } case NestedNameSpecifier::Super: { CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd()); break; } } } return Builder.getWithLocInContext(Context); } SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx) { SourceLocation beg = ReadSourceLocation(F, Record, Idx); SourceLocation end = ReadSourceLocation(F, Record, Idx); return SourceRange(beg, end); } /// \brief Read an integral value llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) { unsigned BitWidth = Record[Idx++]; unsigned NumWords = llvm::APInt::getNumWords(BitWidth); llvm::APInt Result(BitWidth, NumWords, &Record[Idx]); Idx += NumWords; return Result; } /// \brief Read a signed integral value llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) { bool isUnsigned = Record[Idx++]; return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned); } /// \brief Read a floating-point value llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, const llvm::fltSemantics &Sem, unsigned &Idx) { return llvm::APFloat(Sem, ReadAPInt(Record, Idx)); } // \brief Read a string std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) { unsigned Len = Record[Idx++]; std::string Result(Record.data() + Idx, Record.data() + Idx + Len); Idx += Len; return Result; } std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx) { std::string Filename = ReadString(Record, Idx); ResolveImportedPath(F, Filename); return Filename; } VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, unsigned &Idx) { unsigned Major = Record[Idx++]; unsigned Minor = Record[Idx++]; unsigned Subminor = Record[Idx++]; if (Minor == 0) return VersionTuple(Major); if (Subminor == 0) return VersionTuple(Major, Minor - 1); return VersionTuple(Major, Minor - 1, Subminor - 1); } CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx) { CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); return CXXTemporary::Create(getContext(), Decl); } DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { return Diag(CurrentImportLoc, DiagID); } DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { return Diags.Report(Loc, DiagID); } /// \brief Retrieve the identifier table associated with the /// preprocessor. IdentifierTable &ASTReader::getIdentifierTable() { return PP.getIdentifierTable(); } /// \brief Record that the given ID maps to the given switch-case /// statement. void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { assert((*CurrSwitchCaseStmts)[ID] == nullptr && "Already have a SwitchCase with this ID"); (*CurrSwitchCaseStmts)[ID] = SC; } /// \brief Retrieve the switch-case statement with the given ID. SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID"); return (*CurrSwitchCaseStmts)[ID]; } void ASTReader::ClearSwitchCaseIDs() { CurrSwitchCaseStmts->clear(); } void ASTReader::ReadComments() { ASTContext &Context = getContext(); std::vector<RawComment *> Comments; for (SmallVectorImpl<std::pair<BitstreamCursor, serialization::ModuleFile *> >::iterator I = CommentsCursors.begin(), E = CommentsCursors.end(); I != E; ++I) { Comments.clear(); BitstreamCursor &Cursor = I->first; serialization::ModuleFile &F = *I->second; SavedStreamPosition SavedPosition(Cursor); RecordData Record; while (true) { llvm::BitstreamEntry Entry = Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return; case llvm::BitstreamEntry::EndBlock: goto NextCursor; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read a record. Record.clear(); switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) { case COMMENTS_RAW_COMMENT: { unsigned Idx = 0; SourceRange SR = ReadSourceRange(F, Record, Idx); RawComment::CommentKind Kind = (RawComment::CommentKind) Record[Idx++]; bool IsTrailingComment = Record[Idx++]; bool IsAlmostTrailingComment = Record[Idx++]; Comments.push_back(new (Context) RawComment( SR, Kind, IsTrailingComment, IsAlmostTrailingComment, Context.getLangOpts().CommentOpts.ParseAllComments)); break; } } } NextCursor: // De-serialized SourceLocations get negative FileIDs for other modules, // potentially invalidating the original order. Sort it again. std::sort(Comments.begin(), Comments.end(), BeforeThanCompare<RawComment>(SourceMgr)); Context.Comments.addDeserializedComments(Comments); } } void ASTReader::visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref<void(const serialization::InputFile &IF, bool isSystem)> Visitor) { unsigned NumUserInputs = MF.NumUserInputFiles; unsigned NumInputs = MF.InputFilesLoaded.size(); assert(NumUserInputs <= NumInputs); unsigned N = IncludeSystem ? NumInputs : NumUserInputs; for (unsigned I = 0; I < N; ++I) { bool IsSystem = I >= NumUserInputs; InputFile IF = getInputFile(MF, I+1, Complain); Visitor(IF, IsSystem); } } void ASTReader::visitTopLevelModuleMaps( serialization::ModuleFile &MF, llvm::function_ref<void(const FileEntry *FE)> Visitor) { unsigned NumInputs = MF.InputFilesLoaded.size(); for (unsigned I = 0; I < NumInputs; ++I) { InputFileInfo IFI = readInputFileInfo(MF, I + 1); if (IFI.TopLevelModuleMap) // FIXME: This unnecessarily re-reads the InputFileInfo. if (auto *FE = getInputFile(MF, I + 1).getFile()) Visitor(FE); } } std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) { // If we know the owning module, use it. if (Module *M = D->getImportedOwningModule()) return M->getFullModuleName(); // Otherwise, use the name of the top-level module the decl is within. if (ModuleFile *M = getOwningModuleFile(D)) return M->ModuleName; // Not from a module. return ""; } void ASTReader::finishPendingActions() { while (!PendingIdentifierInfos.empty() || !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() || !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty()) { // If any identifiers with corresponding top-level declarations have // been loaded, load those declarations now. typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDeclsMap; TopLevelDeclsMap TopLevelDecls; while (!PendingIdentifierInfos.empty()) { IdentifierInfo *II = PendingIdentifierInfos.back().first; SmallVector<uint32_t, 4> DeclIDs = std::move(PendingIdentifierInfos.back().second); PendingIdentifierInfos.pop_back(); SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]); } // For each decl chain that we wanted to complete while deserializing, mark // it as "still needs to be completed". for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { markIncompleteDeclChain(PendingIncompleteDeclChains[I]); } PendingIncompleteDeclChains.clear(); // Load pending declaration chains. for (unsigned I = 0; I != PendingDeclChains.size(); ++I) loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second); PendingDeclChains.clear(); // Make the most recent of the top-level declarations visible. for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { IdentifierInfo *II = TLD->first; for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II); } } // Load any pending macro definitions. for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { IdentifierInfo *II = PendingMacroIDs.begin()[I].first; SmallVector<PendingMacroInfo, 2> GlobalIDs; GlobalIDs.swap(PendingMacroIDs.begin()[I].second); // Initialize the macro history from chained-PCHs ahead of module imports. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; ++IDIdx) { const PendingMacroInfo &Info = GlobalIDs[IDIdx]; if (!Info.M->isModule()) resolvePendingMacro(II, Info); } // Handle module imports. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; ++IDIdx) { const PendingMacroInfo &Info = GlobalIDs[IDIdx]; if (Info.M->isModule()) resolvePendingMacro(II, Info); } } PendingMacroIDs.clear(); // Wire up the DeclContexts for Decls that we delayed setting until // recursive loading is completed. while (!PendingDeclContextInfos.empty()) { PendingDeclContextInfo Info = PendingDeclContextInfos.front(); PendingDeclContextInfos.pop_front(); DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC)); DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC)); Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext()); } // Perform any pending declaration updates. while (!PendingUpdateRecords.empty()) { auto Update = PendingUpdateRecords.pop_back_val(); ReadingKindTracker ReadingKind(Read_Decl, *this); loadDeclUpdateRecords(Update); } } // At this point, all update records for loaded decls are in place, so any // fake class definitions should have become real. assert(PendingFakeDefinitionData.empty() && "faked up a class definition but never saw the real one"); // If we deserialized any C++ or Objective-C class definitions, any // Objective-C protocol definitions, or any redeclarable templates, make sure // that all redeclarations point to the definitions. Note that this can only // happen now, after the redeclaration chains have been fully wired. for (Decl *D : PendingDefinitions) { if (TagDecl *TD = dyn_cast<TagDecl>(D)) { if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { // Make sure that the TagType points at the definition. const_cast<TagType*>(TagT)->decl = TD; } if (auto RD = dyn_cast<CXXRecordDecl>(D)) { for (auto *R = getMostRecentExistingDecl(RD); R; R = R->getPreviousDecl()) { assert((R == D) == cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && "declaration thinks it's the definition but it isn't"); cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; } } continue; } if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) { // Make sure that the ObjCInterfaceType points at the definition. const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl)) ->Decl = ID; for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) cast<ObjCInterfaceDecl>(R)->Data = ID->Data; continue; } if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) { for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) cast<ObjCProtocolDecl>(R)->Data = PD->Data; continue; } auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl(); for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; } PendingDefinitions.clear(); // Load the bodies of any functions or methods we've encountered. We do // this now (delayed) so that we can be sure that the declaration chains // have been fully wired up (hasBody relies on this). // FIXME: We shouldn't require complete redeclaration chains here. for (PendingBodiesMap::iterator PB = PendingBodies.begin(), PBEnd = PendingBodies.end(); PB != PBEnd; ++PB) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) { // FIXME: Check for =delete/=default? // FIXME: Complain about ODR violations here? const FunctionDecl *Defn = nullptr; if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) { FD->setLazyBody(PB->second); } else mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD); continue; } ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first); if (!getContext().getLangOpts().Modules || !MD->hasBody()) MD->setLazyBody(PB->second); } PendingBodies.clear(); // Do some cleanup. for (auto *ND : PendingMergedDefinitionsToDeduplicate) getContext().deduplicateMergedDefinitonsFor(ND); PendingMergedDefinitionsToDeduplicate.clear(); } void ASTReader::diagnoseOdrViolations() { if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty()) return; // Trigger the import of the full definition of each class that had any // odr-merging problems, so we can produce better diagnostics for them. // These updates may in turn find and diagnose some ODR failures, so take // ownership of the set first. auto OdrMergeFailures = std::move(PendingOdrMergeFailures); PendingOdrMergeFailures.clear(); for (auto &Merge : OdrMergeFailures) { Merge.first->buildLookup(); Merge.first->decls_begin(); Merge.first->bases_begin(); Merge.first->vbases_begin(); for (auto *RD : Merge.second) { RD->decls_begin(); RD->bases_begin(); RD->vbases_begin(); } } // For each declaration from a merged context, check that the canonical // definition of that context also contains a declaration of the same // entity. // // Caution: this loop does things that might invalidate iterators into // PendingOdrMergeChecks. Don't turn this into a range-based for loop! while (!PendingOdrMergeChecks.empty()) { NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); // FIXME: Skip over implicit declarations for now. This matters for things // like implicitly-declared special member functions. This isn't entirely // correct; we can end up with multiple unmerged declarations of the same // implicit entity. if (D->isImplicit()) continue; DeclContext *CanonDef = D->getDeclContext(); bool Found = false; const Decl *DCanon = D->getCanonicalDecl(); for (auto RI : D->redecls()) { if (RI->getLexicalDeclContext() == CanonDef) { Found = true; break; } } if (Found) continue; // Quick check failed, time to do the slow thing. Note, we can't just // look up the name of D in CanonDef here, because the member that is // in CanonDef might not be found by name lookup (it might have been // replaced by a more recent declaration in the lookup table), and we // can't necessarily find it in the redeclaration chain because it might // be merely mergeable, not redeclarable. llvm::SmallVector<const NamedDecl*, 4> Candidates; for (auto *CanonMember : CanonDef->decls()) { if (CanonMember->getCanonicalDecl() == DCanon) { // This can happen if the declaration is merely mergeable and not // actually redeclarable (we looked for redeclarations earlier). // // FIXME: We should be able to detect this more efficiently, without // pulling in all of the members of CanonDef. Found = true; break; } if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) if (ND->getDeclName() == D->getDeclName()) Candidates.push_back(ND); } if (!Found) { // The AST doesn't like TagDecls becoming invalid after they've been // completed. We only really need to mark FieldDecls as invalid here. if (!isa<TagDecl>(D)) D->setInvalidDecl(); // Ensure we don't accidentally recursively enter deserialization while // we're producing our diagnostic. Deserializing RecursionGuard(this); std::string CanonDefModule = getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef)); Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) << D << getOwningModuleNameForDiagnostic(D) << CanonDef << CanonDefModule.empty() << CanonDefModule; if (Candidates.empty()) Diag(cast<Decl>(CanonDef)->getLocation(), diag::note_module_odr_violation_no_possible_decls) << D; else { for (unsigned I = 0, N = Candidates.size(); I != N; ++I) Diag(Candidates[I]->getLocation(), diag::note_module_odr_violation_possible_decl) << Candidates[I]; } DiagnosedOdrMergeFailures.insert(CanonDef); } } if (OdrMergeFailures.empty()) return; // Ensure we don't accidentally recursively enter deserialization while // we're producing our diagnostics. Deserializing RecursionGuard(this); // Issue any pending ODR-failure diagnostics. for (auto &Merge : OdrMergeFailures) { // If we've already pointed out a specific problem with this class, don't // bother issuing a general "something's different" diagnostic. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) continue; bool Diagnosed = false; CXXRecordDecl *FirstRecord = Merge.first; std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord); for (CXXRecordDecl *SecondRecord : Merge.second) { // Multiple different declarations got merged together; tell the user // where they came from. if (FirstRecord == SecondRecord) continue; std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord); using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>; DeclHashes FirstHashes; DeclHashes SecondHashes; ODRHash Hash; auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes, CXXRecordDecl *Record) { for (auto *D : Record->decls()) { // Due to decl merging, the first CXXRecordDecl is the parent of // Decls in both records. if (!ODRHash::isWhitelistedDecl(D, FirstRecord)) continue; Hash.clear(); Hash.AddSubDecl(D); Hashes.emplace_back(D, Hash.CalculateHash()); } }; PopulateHashes(FirstHashes, FirstRecord); PopulateHashes(SecondHashes, SecondRecord); // Used with err_module_odr_violation_mismatch_decl and // note_module_odr_violation_mismatch_decl // This list should be the same Decl's as in ODRHash::isWhiteListedDecl enum { EndOfClass, PublicSpecifer, PrivateSpecifer, ProtectedSpecifer, StaticAssert, Field, CXXMethod, TypeAlias, TypeDef, Var, Friend, Other } FirstDiffType = Other, SecondDiffType = Other; auto DifferenceSelector = [](Decl *D) { assert(D && "valid Decl required"); switch (D->getKind()) { default: return Other; case Decl::AccessSpec: switch (D->getAccess()) { case AS_public: return PublicSpecifer; case AS_private: return PrivateSpecifer; case AS_protected: return ProtectedSpecifer; case AS_none: break; } llvm_unreachable("Invalid access specifier"); case Decl::StaticAssert: return StaticAssert; case Decl::Field: return Field; case Decl::CXXMethod: case Decl::CXXConstructor: case Decl::CXXDestructor: return CXXMethod; case Decl::TypeAlias: return TypeAlias; case Decl::Typedef: return TypeDef; case Decl::Var: return Var; case Decl::Friend: return Friend; } }; Decl *FirstDecl = nullptr; Decl *SecondDecl = nullptr; auto FirstIt = FirstHashes.begin(); auto SecondIt = SecondHashes.begin(); // If there is a diagnoseable difference, FirstDiffType and // SecondDiffType will not be Other and FirstDecl and SecondDecl will be // filled in if not EndOfClass. while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) { if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() && FirstIt->second == SecondIt->second) { ++FirstIt; ++SecondIt; continue; } FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first; SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first; FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass; SecondDiffType = SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass; break; } if (FirstDiffType == Other || SecondDiffType == Other) { // Reaching this point means an unexpected Decl was encountered // or no difference was detected. This causes a generic error // message to be emitted. Diag(FirstRecord->getLocation(), diag::err_module_odr_violation_different_definitions) << FirstRecord << FirstModule.empty() << FirstModule; if (FirstDecl) { Diag(FirstDecl->getLocation(), diag::note_first_module_difference) << FirstRecord << FirstDecl->getSourceRange(); } Diag(SecondRecord->getLocation(), diag::note_module_odr_violation_different_definitions) << SecondModule; if (SecondDecl) { Diag(SecondDecl->getLocation(), diag::note_second_module_difference) << SecondDecl->getSourceRange(); } Diagnosed = true; break; } if (FirstDiffType != SecondDiffType) { SourceLocation FirstLoc; SourceRange FirstRange; if (FirstDiffType == EndOfClass) { FirstLoc = FirstRecord->getBraceRange().getEnd(); } else { FirstLoc = FirstIt->first->getLocation(); FirstRange = FirstIt->first->getSourceRange(); } Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl) << FirstRecord << FirstModule.empty() << FirstModule << FirstRange << FirstDiffType; SourceLocation SecondLoc; SourceRange SecondRange; if (SecondDiffType == EndOfClass) { SecondLoc = SecondRecord->getBraceRange().getEnd(); } else { SecondLoc = SecondDecl->getLocation(); SecondRange = SecondDecl->getSourceRange(); } Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl) << SecondModule << SecondRange << SecondDiffType; Diagnosed = true; break; } assert(FirstDiffType == SecondDiffType); // Used with err_module_odr_violation_mismatch_decl_diff and // note_module_odr_violation_mismatch_decl_diff enum ODRDeclDifference{ StaticAssertCondition, StaticAssertMessage, StaticAssertOnlyMessage, FieldName, FieldTypeName, FieldSingleBitField, FieldDifferentWidthBitField, FieldSingleMutable, FieldSingleInitializer, FieldDifferentInitializers, MethodName, MethodDeleted, MethodVirtual, MethodStatic, MethodVolatile, MethodConst, MethodInline, MethodNumberParameters, MethodParameterType, MethodParameterName, MethodParameterSingleDefaultArgument, MethodParameterDifferentDefaultArgument, TypedefName, TypedefType, VarName, VarType, VarSingleInitializer, VarDifferentInitializer, VarConstexpr, FriendTypeFunction, FriendType, FriendFunction, }; // These lambdas have the common portions of the ODR diagnostics. This // has the same return as Diag(), so addition parameters can be passed // in with operator<< auto ODRDiagError = [FirstRecord, &FirstModule, this]( SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) { return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff) << FirstRecord << FirstModule.empty() << FirstModule << Range << DiffType; }; auto ODRDiagNote = [&SecondModule, this]( SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) { return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff) << SecondModule << Range << DiffType; }; auto ComputeODRHash = [&Hash](const Stmt* S) { assert(S); Hash.clear(); Hash.AddStmt(S); return Hash.CalculateHash(); }; auto ComputeQualTypeODRHash = [&Hash](QualType Ty) { Hash.clear(); Hash.AddQualType(Ty); return Hash.CalculateHash(); }; switch (FirstDiffType) { case Other: case EndOfClass: case PublicSpecifer: case PrivateSpecifer: case ProtectedSpecifer: llvm_unreachable("Invalid diff type"); case StaticAssert: { StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl); StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl); Expr *FirstExpr = FirstSA->getAssertExpr(); Expr *SecondExpr = SecondSA->getAssertExpr(); unsigned FirstODRHash = ComputeODRHash(FirstExpr); unsigned SecondODRHash = ComputeODRHash(SecondExpr); if (FirstODRHash != SecondODRHash) { ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(), StaticAssertCondition); ODRDiagNote(SecondExpr->getLocStart(), SecondExpr->getSourceRange(), StaticAssertCondition); Diagnosed = true; break; } StringLiteral *FirstStr = FirstSA->getMessage(); StringLiteral *SecondStr = SecondSA->getMessage(); assert((FirstStr || SecondStr) && "Both messages cannot be empty"); if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) { SourceLocation FirstLoc, SecondLoc; SourceRange FirstRange, SecondRange; if (FirstStr) { FirstLoc = FirstStr->getLocStart(); FirstRange = FirstStr->getSourceRange(); } else { FirstLoc = FirstSA->getLocStart(); FirstRange = FirstSA->getSourceRange(); } if (SecondStr) { SecondLoc = SecondStr->getLocStart(); SecondRange = SecondStr->getSourceRange(); } else { SecondLoc = SecondSA->getLocStart(); SecondRange = SecondSA->getSourceRange(); } ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage) << (FirstStr == nullptr); ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage) << (SecondStr == nullptr); Diagnosed = true; break; } if (FirstStr && SecondStr && FirstStr->getString() != SecondStr->getString()) { ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(), StaticAssertMessage); ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(), StaticAssertMessage); Diagnosed = true; break; } break; } case Field: { FieldDecl *FirstField = cast<FieldDecl>(FirstDecl); FieldDecl *SecondField = cast<FieldDecl>(SecondDecl); IdentifierInfo *FirstII = FirstField->getIdentifier(); IdentifierInfo *SecondII = SecondField->getIdentifier(); if (FirstII->getName() != SecondII->getName()) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldName) << FirstII; ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldName) << SecondII; Diagnosed = true; break; } assert(getContext().hasSameType(FirstField->getType(), SecondField->getType())); QualType FirstType = FirstField->getType(); QualType SecondType = SecondField->getType(); if (ComputeQualTypeODRHash(FirstType) != ComputeQualTypeODRHash(SecondType)) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldTypeName) << FirstII << FirstType; ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldTypeName) << SecondII << SecondType; Diagnosed = true; break; } const bool IsFirstBitField = FirstField->isBitField(); const bool IsSecondBitField = SecondField->isBitField(); if (IsFirstBitField != IsSecondBitField) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldSingleBitField) << FirstII << IsFirstBitField; ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldSingleBitField) << SecondII << IsSecondBitField; Diagnosed = true; break; } if (IsFirstBitField && IsSecondBitField) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldDifferentWidthBitField) << FirstII << FirstField->getBitWidth()->getSourceRange(); ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldDifferentWidthBitField) << SecondII << SecondField->getBitWidth()->getSourceRange(); Diagnosed = true; break; } const bool IsFirstMutable = FirstField->isMutable(); const bool IsSecondMutable = SecondField->isMutable(); if (IsFirstMutable != IsSecondMutable) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldSingleMutable) << FirstII << IsFirstMutable; ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldSingleMutable) << SecondII << IsSecondMutable; Diagnosed = true; break; } const Expr *FirstInitializer = FirstField->getInClassInitializer(); const Expr *SecondInitializer = SecondField->getInClassInitializer(); if ((!FirstInitializer && SecondInitializer) || (FirstInitializer && !SecondInitializer)) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldSingleInitializer) << FirstII << (FirstInitializer != nullptr); ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldSingleInitializer) << SecondII << (SecondInitializer != nullptr); Diagnosed = true; break; } if (FirstInitializer && SecondInitializer) { unsigned FirstInitHash = ComputeODRHash(FirstInitializer); unsigned SecondInitHash = ComputeODRHash(SecondInitializer); if (FirstInitHash != SecondInitHash) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldDifferentInitializers) << FirstII << FirstInitializer->getSourceRange(); ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldDifferentInitializers) << SecondII << SecondInitializer->getSourceRange(); Diagnosed = true; break; } } break; } case CXXMethod: { enum { DiagMethod, DiagConstructor, DiagDestructor, } FirstMethodType, SecondMethodType; auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) { if (isa<CXXConstructorDecl>(D)) return DiagConstructor; if (isa<CXXDestructorDecl>(D)) return DiagDestructor; return DiagMethod; }; const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl); const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl); FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod); SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod); auto FirstName = FirstMethod->getDeclName(); auto SecondName = SecondMethod->getDeclName(); if (FirstMethodType != SecondMethodType || FirstName != SecondName) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodName) << FirstMethodType << FirstName; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodName) << SecondMethodType << SecondName; Diagnosed = true; break; } const bool FirstDeleted = FirstMethod->isDeleted(); const bool SecondDeleted = SecondMethod->isDeleted(); if (FirstDeleted != SecondDeleted) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodDeleted) << FirstMethodType << FirstName << FirstDeleted; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodDeleted) << SecondMethodType << SecondName << SecondDeleted; Diagnosed = true; break; } const bool FirstVirtual = FirstMethod->isVirtualAsWritten(); const bool SecondVirtual = SecondMethod->isVirtualAsWritten(); const bool FirstPure = FirstMethod->isPure(); const bool SecondPure = SecondMethod->isPure(); if ((FirstVirtual || SecondVirtual) && (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodVirtual) << FirstMethodType << FirstName << FirstPure << FirstVirtual; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodVirtual) << SecondMethodType << SecondName << SecondPure << SecondVirtual; Diagnosed = true; break; } // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging, // FirstDecl is the canonical Decl of SecondDecl, so the storage // class needs to be checked instead. const auto FirstStorage = FirstMethod->getStorageClass(); const auto SecondStorage = SecondMethod->getStorageClass(); const bool FirstStatic = FirstStorage == SC_Static; const bool SecondStatic = SecondStorage == SC_Static; if (FirstStatic != SecondStatic) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodStatic) << FirstMethodType << FirstName << FirstStatic; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodStatic) << SecondMethodType << SecondName << SecondStatic; Diagnosed = true; break; } const bool FirstVolatile = FirstMethod->isVolatile(); const bool SecondVolatile = SecondMethod->isVolatile(); if (FirstVolatile != SecondVolatile) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodVolatile) << FirstMethodType << FirstName << FirstVolatile; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodVolatile) << SecondMethodType << SecondName << SecondVolatile; Diagnosed = true; break; } const bool FirstConst = FirstMethod->isConst(); const bool SecondConst = SecondMethod->isConst(); if (FirstConst != SecondConst) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodConst) << FirstMethodType << FirstName << FirstConst; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodConst) << SecondMethodType << SecondName << SecondConst; Diagnosed = true; break; } const bool FirstInline = FirstMethod->isInlineSpecified(); const bool SecondInline = SecondMethod->isInlineSpecified(); if (FirstInline != SecondInline) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodInline) << FirstMethodType << FirstName << FirstInline; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodInline) << SecondMethodType << SecondName << SecondInline; Diagnosed = true; break; } const unsigned FirstNumParameters = FirstMethod->param_size(); const unsigned SecondNumParameters = SecondMethod->param_size(); if (FirstNumParameters != SecondNumParameters) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodNumberParameters) << FirstMethodType << FirstName << FirstNumParameters; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodNumberParameters) << SecondMethodType << SecondName << SecondNumParameters; Diagnosed = true; break; } // Need this status boolean to know when break out of the switch. bool ParameterMismatch = false; for (unsigned I = 0; I < FirstNumParameters; ++I) { const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I); const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I); QualType FirstParamType = FirstParam->getType(); QualType SecondParamType = SecondParam->getType(); if (FirstParamType != SecondParamType && ComputeQualTypeODRHash(FirstParamType) != ComputeQualTypeODRHash(SecondParamType)) { if (const DecayedType *ParamDecayedType = FirstParamType->getAs<DecayedType>()) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterType) << FirstMethodType << FirstName << (I + 1) << FirstParamType << true << ParamDecayedType->getOriginalType(); } else { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterType) << FirstMethodType << FirstName << (I + 1) << FirstParamType << false; } if (const DecayedType *ParamDecayedType = SecondParamType->getAs<DecayedType>()) { ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterType) << SecondMethodType << SecondName << (I + 1) << SecondParamType << true << ParamDecayedType->getOriginalType(); } else { ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterType) << SecondMethodType << SecondName << (I + 1) << SecondParamType << false; } ParameterMismatch = true; break; } DeclarationName FirstParamName = FirstParam->getDeclName(); DeclarationName SecondParamName = SecondParam->getDeclName(); if (FirstParamName != SecondParamName) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterName) << FirstMethodType << FirstName << (I + 1) << FirstParamName; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterName) << SecondMethodType << SecondName << (I + 1) << SecondParamName; ParameterMismatch = true; break; } const Expr *FirstInit = FirstParam->getInit(); const Expr *SecondInit = SecondParam->getInit(); if ((FirstInit == nullptr) != (SecondInit == nullptr)) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterSingleDefaultArgument) << FirstMethodType << FirstName << (I + 1) << (FirstInit == nullptr) << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterSingleDefaultArgument) << SecondMethodType << SecondName << (I + 1) << (SecondInit == nullptr) << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); ParameterMismatch = true; break; } if (FirstInit && SecondInit && ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterDifferentDefaultArgument) << FirstMethodType << FirstName << (I + 1) << FirstInit->getSourceRange(); ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterDifferentDefaultArgument) << SecondMethodType << SecondName << (I + 1) << SecondInit->getSourceRange(); ParameterMismatch = true; break; } } if (ParameterMismatch) { Diagnosed = true; break; } break; } case TypeAlias: case TypeDef: { TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl); TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl); auto FirstName = FirstTD->getDeclName(); auto SecondName = SecondTD->getDeclName(); if (FirstName != SecondName) { ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(), TypedefName) << (FirstDiffType == TypeAlias) << FirstName; ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(), TypedefName) << (FirstDiffType == TypeAlias) << SecondName; Diagnosed = true; break; } QualType FirstType = FirstTD->getUnderlyingType(); QualType SecondType = SecondTD->getUnderlyingType(); if (ComputeQualTypeODRHash(FirstType) != ComputeQualTypeODRHash(SecondType)) { ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(), TypedefType) << (FirstDiffType == TypeAlias) << FirstName << FirstType; ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(), TypedefType) << (FirstDiffType == TypeAlias) << SecondName << SecondType; Diagnosed = true; break; } break; } case Var: { VarDecl *FirstVD = cast<VarDecl>(FirstDecl); VarDecl *SecondVD = cast<VarDecl>(SecondDecl); auto FirstName = FirstVD->getDeclName(); auto SecondName = SecondVD->getDeclName(); if (FirstName != SecondName) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarName) << FirstName; ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarName) << SecondName; Diagnosed = true; break; } QualType FirstType = FirstVD->getType(); QualType SecondType = SecondVD->getType(); if (ComputeQualTypeODRHash(FirstType) != ComputeQualTypeODRHash(SecondType)) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarType) << FirstName << FirstType; ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarType) << SecondName << SecondType; Diagnosed = true; break; } const Expr *FirstInit = FirstVD->getInit(); const Expr *SecondInit = SecondVD->getInit(); if ((FirstInit == nullptr) != (SecondInit == nullptr)) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarSingleInitializer) << FirstName << (FirstInit == nullptr) << (FirstInit ? FirstInit->getSourceRange(): SourceRange()); ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarSingleInitializer) << SecondName << (SecondInit == nullptr) << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); Diagnosed = true; break; } if (FirstInit && SecondInit && ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarDifferentInitializer) << FirstName << FirstInit->getSourceRange(); ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarDifferentInitializer) << SecondName << SecondInit->getSourceRange(); Diagnosed = true; break; } const bool FirstIsConstexpr = FirstVD->isConstexpr(); const bool SecondIsConstexpr = SecondVD->isConstexpr(); if (FirstIsConstexpr != SecondIsConstexpr) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarConstexpr) << FirstName << FirstIsConstexpr; ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarConstexpr) << SecondName << SecondIsConstexpr; Diagnosed = true; break; } break; } case Friend: { FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl); FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl); NamedDecl *FirstND = FirstFriend->getFriendDecl(); NamedDecl *SecondND = SecondFriend->getFriendDecl(); TypeSourceInfo *FirstTSI = FirstFriend->getFriendType(); TypeSourceInfo *SecondTSI = SecondFriend->getFriendType(); if (FirstND && SecondND) { ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(), FriendFunction) << FirstND; ODRDiagNote(SecondFriend->getFriendLoc(), SecondFriend->getSourceRange(), FriendFunction) << SecondND; Diagnosed = true; break; } if (FirstTSI && SecondTSI) { QualType FirstFriendType = FirstTSI->getType(); QualType SecondFriendType = SecondTSI->getType(); assert(ComputeQualTypeODRHash(FirstFriendType) != ComputeQualTypeODRHash(SecondFriendType)); ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(), FriendType) << FirstFriendType; ODRDiagNote(SecondFriend->getFriendLoc(), SecondFriend->getSourceRange(), FriendType) << SecondFriendType; Diagnosed = true; break; } ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(), FriendTypeFunction) << (FirstTSI == nullptr); ODRDiagNote(SecondFriend->getFriendLoc(), SecondFriend->getSourceRange(), FriendTypeFunction) << (SecondTSI == nullptr); Diagnosed = true; break; } } if (Diagnosed == true) continue; Diag(FirstDecl->getLocation(), diag::err_module_odr_violation_mismatch_decl_unknown) << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType << FirstDecl->getSourceRange(); Diag(SecondDecl->getLocation(), diag::note_module_odr_violation_mismatch_decl_unknown) << SecondModule << FirstDiffType << SecondDecl->getSourceRange(); Diagnosed = true; } if (!Diagnosed) { // All definitions are updates to the same declaration. This happens if a // module instantiates the declaration of a class template specialization // and two or more other modules instantiate its definition. // // FIXME: Indicate which modules had instantiations of this definition. // FIXME: How can this even happen? Diag(Merge.first->getLocation(), diag::err_module_odr_violation_different_instantiations) << Merge.first; } } } void ASTReader::StartedDeserializing() { if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) ReadTimer->startTimer(); } void ASTReader::FinishedDeserializing() { assert(NumCurrentElementsDeserializing && "FinishedDeserializing not paired with StartedDeserializing"); if (NumCurrentElementsDeserializing == 1) { // We decrease NumCurrentElementsDeserializing only after pending actions // are finished, to avoid recursively re-calling finishPendingActions(). finishPendingActions(); } --NumCurrentElementsDeserializing; if (NumCurrentElementsDeserializing == 0) { // Propagate exception specification updates along redeclaration chains. while (!PendingExceptionSpecUpdates.empty()) { auto Updates = std::move(PendingExceptionSpecUpdates); PendingExceptionSpecUpdates.clear(); for (auto Update : Updates) { ProcessingUpdatesRAIIObj ProcessingUpdates(*this); auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); auto ESI = FPT->getExtProtoInfo().ExceptionSpec; if (auto *Listener = getContext().getASTMutationListener()) Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); for (auto *Redecl : Update.second->redecls()) getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); } } if (ReadTimer) ReadTimer->stopTimer(); diagnoseOdrViolations(); // We are not in recursive loading, so it's safe to pass the "interesting" // decls to the consumer. if (Consumer) PassInterestingDeclsToConsumer(); } } void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { // Remove any fake results before adding any real ones. auto It = PendingFakeLookupResults.find(II); if (It != PendingFakeLookupResults.end()) { for (auto *ND : It->second) SemaObj->IdResolver.RemoveDecl(ND); // FIXME: this works around module+PCH performance issue. // Rather than erase the result from the map, which is O(n), just clear // the vector of NamedDecls. It->second.clear(); } } if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { SemaObj->TUScope->AddDecl(D); } else if (SemaObj->TUScope) { // Adding the decl to IdResolver may have failed because it was already in // (even though it was not added in scope). If it is already in, make sure // it gets in the scope as well. if (std::find(SemaObj->IdResolver.begin(Name), SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end()) SemaObj->TUScope->AddDecl(D); } } ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, StringRef isysroot, bool DisableValidation, bool AllowASTWithCompilerErrors, bool AllowConfigurationMismatch, bool ValidateSystemInputs, bool UseGlobalIndex, std::unique_ptr<llvm::Timer> ReadTimer) : Listener(DisableValidation ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) : cast<ASTReaderListener>(new PCHValidator(PP, *this))), SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), ContextObj(Context), ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr), PCMCache(PP.getPCMCache()), DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot), DisableValidation(DisableValidation), AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), AllowConfigurationMismatch(AllowConfigurationMismatch), ValidateSystemInputs(ValidateSystemInputs), UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { SourceMgr.setExternalSLocEntrySource(this); for (const auto &Ext : Extensions) { auto BlockName = Ext->getExtensionMetadata().BlockName; auto Known = ModuleFileExtensions.find(BlockName); if (Known != ModuleFileExtensions.end()) { Diags.Report(diag::warn_duplicate_module_file_extension) << BlockName; continue; } ModuleFileExtensions.insert({BlockName, Ext}); } } ASTReader::~ASTReader() { if (OwnsDeserializationListener) delete DeserializationListener; for (auto PStr: TokenLiteralDataLoaded) { delete PStr; } } IdentifierResolver &ASTReader::getIdResolver() { return SemaObj ? SemaObj->IdResolver : DummyIdResolver; } unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID) { Idx = 0; Record.clear(); return Cursor.readRecord(AbbrevID, Record); } Add a diagnostics if the pch/pcm is out of date before asserting. //===-- ASTReader.cpp - AST File Reader -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTReader class, which reads AST files. // //===----------------------------------------------------------------------===// #include "clang/Serialization/ASTReader.h" #include "ASTCommon.h" #include "ASTReaderInternals.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/ASTUnresolvedSet.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/ODRHash.h" #include "clang/AST/RawCommentList.h" #include "clang/AST/Type.h" #include "clang/AST/TypeLocVisitor.h" #include "clang/AST/UnresolvedSet.h" #include "clang/Basic/CommentOptions.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/ExceptionSpecificationType.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/MemoryBufferCache.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/Sanitizers.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/SourceManagerInternals.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/TokenKinds.h" #include "clang/Basic/Version.h" #include "clang/Basic/VersionTuple.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/ModuleMap.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Sema/Scope.h" #include "clang/Sema/Sema.h" #include "clang/Sema/Weak.h" #include "clang/Serialization/ASTDeserializationListener.h" #include "clang/Serialization/GlobalModuleIndex.h" #include "clang/Serialization/ModuleManager.h" #include "clang/Serialization/SerializationDiagnostic.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/Support/Compression.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Error.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/SaveAndRestore.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <iterator> #include <limits> #include <map> #include <memory> #include <new> #include <string> #include <system_error> #include <tuple> #include <utility> #include <vector> using namespace clang; using namespace clang::serialization; using namespace clang::serialization::reader; using llvm::BitstreamCursor; //===----------------------------------------------------------------------===// // ChainedASTReaderListener implementation //===----------------------------------------------------------------------===// bool ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) { return First->ReadFullVersionInformation(FullVersion) || Second->ReadFullVersionInformation(FullVersion); } void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) { First->ReadModuleName(ModuleName); Second->ReadModuleName(ModuleName); } void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) { First->ReadModuleMapFile(ModuleMapPath); Second->ReadModuleMapFile(ModuleMapPath); } bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) { return First->ReadLanguageOptions(LangOpts, Complain, AllowCompatibleDifferences) || Second->ReadLanguageOptions(LangOpts, Complain, AllowCompatibleDifferences); } bool ChainedASTReaderListener::ReadTargetOptions( const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) { return First->ReadTargetOptions(TargetOpts, Complain, AllowCompatibleDifferences) || Second->ReadTargetOptions(TargetOpts, Complain, AllowCompatibleDifferences); } bool ChainedASTReaderListener::ReadDiagnosticOptions( IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { return First->ReadDiagnosticOptions(DiagOpts, Complain) || Second->ReadDiagnosticOptions(DiagOpts, Complain); } bool ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) { return First->ReadFileSystemOptions(FSOpts, Complain) || Second->ReadFileSystemOptions(FSOpts, Complain); } bool ChainedASTReaderListener::ReadHeaderSearchOptions( const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) { return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, Complain) || Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, Complain); } bool ChainedASTReaderListener::ReadPreprocessorOptions( const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) { return First->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines) || Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines); } void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M, unsigned Value) { First->ReadCounter(M, Value); Second->ReadCounter(M, Value); } bool ChainedASTReaderListener::needsInputFileVisitation() { return First->needsInputFileVisitation() || Second->needsInputFileVisitation(); } bool ChainedASTReaderListener::needsSystemInputFileVisitation() { return First->needsSystemInputFileVisitation() || Second->needsSystemInputFileVisitation(); } void ChainedASTReaderListener::visitModuleFile(StringRef Filename, ModuleKind Kind) { First->visitModuleFile(Filename, Kind); Second->visitModuleFile(Filename, Kind); } bool ChainedASTReaderListener::visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) { bool Continue = false; if (First->needsInputFileVisitation() && (!isSystem || First->needsSystemInputFileVisitation())) Continue |= First->visitInputFile(Filename, isSystem, isOverridden, isExplicitModule); if (Second->needsInputFileVisitation() && (!isSystem || Second->needsSystemInputFileVisitation())) Continue |= Second->visitInputFile(Filename, isSystem, isOverridden, isExplicitModule); return Continue; } void ChainedASTReaderListener::readModuleFileExtension( const ModuleFileExtensionMetadata &Metadata) { First->readModuleFileExtension(Metadata); Second->readModuleFileExtension(Metadata); } //===----------------------------------------------------------------------===// // PCH validator implementation //===----------------------------------------------------------------------===// ASTReaderListener::~ASTReaderListener() {} /// \brief Compare the given set of language options against an existing set of /// language options. /// /// \param Diags If non-NULL, diagnostics will be emitted via this engine. /// \param AllowCompatibleDifferences If true, differences between compatible /// language options will be permitted. /// /// \returns true if the languagae options mis-match, false otherwise. static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences = true) { #define LANGOPT(Name, Bits, Default, Description) \ if (ExistingLangOpts.Name != LangOpts.Name) { \ if (Diags) \ Diags->Report(diag::err_pch_langopt_mismatch) \ << Description << LangOpts.Name << ExistingLangOpts.Name; \ return true; \ } #define VALUE_LANGOPT(Name, Bits, Default, Description) \ if (ExistingLangOpts.Name != LangOpts.Name) { \ if (Diags) \ Diags->Report(diag::err_pch_langopt_value_mismatch) \ << Description; \ return true; \ } #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \ if (Diags) \ Diags->Report(diag::err_pch_langopt_value_mismatch) \ << Description; \ return true; \ } #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \ if (!AllowCompatibleDifferences) \ LANGOPT(Name, Bits, Default, Description) #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \ if (!AllowCompatibleDifferences) \ ENUM_LANGOPT(Name, Bits, Default, Description) #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \ if (!AllowCompatibleDifferences) \ VALUE_LANGOPT(Name, Bits, Default, Description) #define BENIGN_LANGOPT(Name, Bits, Default, Description) #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description) #include "clang/Basic/LangOptions.def" if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) { if (Diags) Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features"; return true; } if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) { if (Diags) Diags->Report(diag::err_pch_langopt_value_mismatch) << "target Objective-C runtime"; return true; } if (ExistingLangOpts.CommentOpts.BlockCommandNames != LangOpts.CommentOpts.BlockCommandNames) { if (Diags) Diags->Report(diag::err_pch_langopt_value_mismatch) << "block command names"; return true; } // Sanitizer feature mismatches are treated as compatible differences. If // compatible differences aren't allowed, we still only want to check for // mismatches of non-modular sanitizers (the only ones which can affect AST // generation). if (!AllowCompatibleDifferences) { SanitizerMask ModularSanitizers = getPPTransparentSanitizers(); SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize; SanitizerSet ImportedSanitizers = LangOpts.Sanitize; ExistingSanitizers.clear(ModularSanitizers); ImportedSanitizers.clear(ModularSanitizers); if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) { const std::string Flag = "-fsanitize="; if (Diags) { #define SANITIZER(NAME, ID) \ { \ bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \ bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \ if (InExistingModule != InImportedModule) \ Diags->Report(diag::err_pch_targetopt_feature_mismatch) \ << InExistingModule << (Flag + NAME); \ } #include "clang/Basic/Sanitizers.def" } return true; } } return false; } /// \brief Compare the given set of target options against an existing set of /// target options. /// /// \param Diags If non-NULL, diagnostics will be emitted via this engine. /// /// \returns true if the target options mis-match, false otherwise. static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences = true) { #define CHECK_TARGET_OPT(Field, Name) \ if (TargetOpts.Field != ExistingTargetOpts.Field) { \ if (Diags) \ Diags->Report(diag::err_pch_targetopt_mismatch) \ << Name << TargetOpts.Field << ExistingTargetOpts.Field; \ return true; \ } // The triple and ABI must match exactly. CHECK_TARGET_OPT(Triple, "target"); CHECK_TARGET_OPT(ABI, "target ABI"); // We can tolerate different CPUs in many cases, notably when one CPU // supports a strict superset of another. When allowing compatible // differences skip this check. if (!AllowCompatibleDifferences) CHECK_TARGET_OPT(CPU, "target CPU"); #undef CHECK_TARGET_OPT // Compare feature sets. SmallVector<StringRef, 4> ExistingFeatures( ExistingTargetOpts.FeaturesAsWritten.begin(), ExistingTargetOpts.FeaturesAsWritten.end()); SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(), TargetOpts.FeaturesAsWritten.end()); std::sort(ExistingFeatures.begin(), ExistingFeatures.end()); std::sort(ReadFeatures.begin(), ReadFeatures.end()); // We compute the set difference in both directions explicitly so that we can // diagnose the differences differently. SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures; std::set_difference( ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(), ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures)); std::set_difference(ReadFeatures.begin(), ReadFeatures.end(), ExistingFeatures.begin(), ExistingFeatures.end(), std::back_inserter(UnmatchedReadFeatures)); // If we are allowing compatible differences and the read feature set is // a strict subset of the existing feature set, there is nothing to diagnose. if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty()) return false; if (Diags) { for (StringRef Feature : UnmatchedReadFeatures) Diags->Report(diag::err_pch_targetopt_feature_mismatch) << /* is-existing-feature */ false << Feature; for (StringRef Feature : UnmatchedExistingFeatures) Diags->Report(diag::err_pch_targetopt_feature_mismatch) << /* is-existing-feature */ true << Feature; } return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty(); } bool PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) { const LangOptions &ExistingLangOpts = PP.getLangOpts(); return checkLanguageOptions(LangOpts, ExistingLangOpts, Complain ? &Reader.Diags : nullptr, AllowCompatibleDifferences); } bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) { const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts(); return checkTargetOptions(TargetOpts, ExistingTargetOpts, Complain ? &Reader.Diags : nullptr, AllowCompatibleDifferences); } namespace { typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> > MacroDefinitionsMap; typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > DeclsMap; } // end anonymous namespace static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool Complain) { typedef DiagnosticsEngine::Level Level; // Check current mappings for new -Werror mappings, and the stored mappings // for cases that were explicitly mapped to *not* be errors that are now // errors because of options like -Werror. DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags }; for (DiagnosticsEngine *MappingSource : MappingSources) { for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) { diag::kind DiagID = DiagIDMappingPair.first; Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation()); if (CurLevel < DiagnosticsEngine::Error) continue; // not significant Level StoredLevel = StoredDiags.getDiagnosticLevel(DiagID, SourceLocation()); if (StoredLevel < DiagnosticsEngine::Error) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" + Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str(); return true; } } } return false; } static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) { diag::Severity Ext = Diags.getExtensionHandlingBehavior(); if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors()) return true; return Ext >= diag::Severity::Error; } static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool IsSystem, bool Complain) { // Top-level options if (IsSystem) { if (Diags.getSuppressSystemWarnings()) return false; // If -Wsystem-headers was not enabled before, be conservative if (StoredDiags.getSuppressSystemWarnings()) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers"; return true; } } if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror"; return true; } if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() && !StoredDiags.getEnableAllWarnings()) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror"; return true; } if (isExtHandlingFromDiagsError(Diags) && !isExtHandlingFromDiagsError(StoredDiags)) { if (Complain) Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors"; return true; } return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain); } /// Return the top import module if it is implicit, nullptr otherwise. static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP) { // If the original import came from a file explicitly generated by the user, // don't check the diagnostic mappings. // FIXME: currently this is approximated by checking whether this is not a // module import of an implicitly-loaded module file. // Note: ModuleMgr.rbegin() may not be the current module, but it must be in // the transitive closure of its imports, since unrelated modules cannot be // imported until after this module finishes validation. ModuleFile *TopImport = &*ModuleMgr.rbegin(); while (!TopImport->ImportedBy.empty()) TopImport = TopImport->ImportedBy[0]; if (TopImport->Kind != MK_ImplicitModule) return nullptr; StringRef ModuleName = TopImport->ModuleName; assert(!ModuleName.empty() && "diagnostic options read before module name"); Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName); assert(M && "missing module"); return M; } bool PCHValidator::ReadDiagnosticOptions( IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs()); IntrusiveRefCntPtr<DiagnosticsEngine> Diags( new DiagnosticsEngine(DiagIDs, DiagOpts.get())); // This should never fail, because we would have processed these options // before writing them to an ASTFile. ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false); ModuleManager &ModuleMgr = Reader.getModuleManager(); assert(ModuleMgr.size() >= 1 && "what ASTFile is this then"); Module *TopM = getTopImportImplicitModule(ModuleMgr, PP); if (!TopM) return false; // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that // contains the union of their flags. return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem, Complain); } /// \brief Collect the macro definitions provided by the given preprocessor /// options. static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl<StringRef> *MacroNames = nullptr) { for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { StringRef Macro = PPOpts.Macros[I].first; bool IsUndef = PPOpts.Macros[I].second; std::pair<StringRef, StringRef> MacroPair = Macro.split('='); StringRef MacroName = MacroPair.first; StringRef MacroBody = MacroPair.second; // For an #undef'd macro, we only care about the name. if (IsUndef) { if (MacroNames && !Macros.count(MacroName)) MacroNames->push_back(MacroName); Macros[MacroName] = std::make_pair("", true); continue; } // For a #define'd macro, figure out the actual definition. if (MacroName.size() == Macro.size()) MacroBody = "1"; else { // Note: GCC drops anything following an end-of-line character. StringRef::size_type End = MacroBody.find_first_of("\n\r"); MacroBody = MacroBody.substr(0, End); } if (MacroNames && !Macros.count(MacroName)) MacroNames->push_back(MacroName); Macros[MacroName] = std::make_pair(MacroBody, false); } } /// \brief Check the preprocessor options deserialized from the control block /// against the preprocessor options in an existing preprocessor. /// /// \param Diags If non-null, produce diagnostics for any mismatches incurred. /// \param Validate If true, validate preprocessor options. If false, allow /// macros defined by \p ExistingPPOpts to override those defined by /// \p PPOpts in SuggestedPredefines. static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts, bool Validate = true) { // Check macro definitions. MacroDefinitionsMap ASTFileMacros; collectMacroDefinitions(PPOpts, ASTFileMacros); MacroDefinitionsMap ExistingMacros; SmallVector<StringRef, 4> ExistingMacroNames; collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames); for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) { // Dig out the macro definition in the existing preprocessor options. StringRef MacroName = ExistingMacroNames[I]; std::pair<StringRef, bool> Existing = ExistingMacros[MacroName]; // Check whether we know anything about this macro name or not. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known = ASTFileMacros.find(MacroName); if (!Validate || Known == ASTFileMacros.end()) { // FIXME: Check whether this identifier was referenced anywhere in the // AST file. If so, we should reject the AST file. Unfortunately, this // information isn't in the control block. What shall we do about it? if (Existing.second) { SuggestedPredefines += "#undef "; SuggestedPredefines += MacroName.str(); SuggestedPredefines += '\n'; } else { SuggestedPredefines += "#define "; SuggestedPredefines += MacroName.str(); SuggestedPredefines += ' '; SuggestedPredefines += Existing.first.str(); SuggestedPredefines += '\n'; } continue; } // If the macro was defined in one but undef'd in the other, we have a // conflict. if (Existing.second != Known->second.second) { if (Diags) { Diags->Report(diag::err_pch_macro_def_undef) << MacroName << Known->second.second; } return true; } // If the macro was #undef'd in both, or if the macro bodies are identical, // it's fine. if (Existing.second || Existing.first == Known->second.first) continue; // The macro bodies differ; complain. if (Diags) { Diags->Report(diag::err_pch_macro_def_conflict) << MacroName << Known->second.first << Existing.first; } return true; } // Check whether we're using predefines. if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) { if (Diags) { Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines; } return true; } // Detailed record is important since it is used for the module cache hash. if (LangOpts.Modules && PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) { if (Diags) { Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord; } return true; } // Compute the #include and #include_macros lines we need. for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) { StringRef File = ExistingPPOpts.Includes[I]; if (File == ExistingPPOpts.ImplicitPCHInclude) continue; if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File) != PPOpts.Includes.end()) continue; SuggestedPredefines += "#include \""; SuggestedPredefines += File; SuggestedPredefines += "\"\n"; } for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) { StringRef File = ExistingPPOpts.MacroIncludes[I]; if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(), File) != PPOpts.MacroIncludes.end()) continue; SuggestedPredefines += "#__include_macros \""; SuggestedPredefines += File; SuggestedPredefines += "\"\n##\n"; } return false; } bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) { const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts(); return checkPreprocessorOptions(PPOpts, ExistingPPOpts, Complain? &Reader.Diags : nullptr, PP.getFileManager(), SuggestedPredefines, PP.getLangOpts()); } bool SimpleASTReaderListener::ReadPreprocessorOptions( const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) { return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), nullptr, PP.getFileManager(), SuggestedPredefines, PP.getLangOpts(), false); } /// Check the header search options deserialized from the control block /// against the header search options in an existing preprocessor. /// /// \param Diags If non-null, produce diagnostics for any mismatches incurred. static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, DiagnosticsEngine *Diags, const LangOptions &LangOpts) { if (LangOpts.Modules) { if (SpecificModuleCachePath != ExistingModuleCachePath) { if (Diags) Diags->Report(diag::err_pch_modulecache_mismatch) << SpecificModuleCachePath << ExistingModuleCachePath; return true; } } return false; } bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) { return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, PP.getHeaderSearchInfo().getModuleCachePath(), Complain ? &Reader.Diags : nullptr, PP.getLangOpts()); } void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) { PP.setCounterValue(Value); } //===----------------------------------------------------------------------===// // AST reader implementation //===----------------------------------------------------------------------===// void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership) { DeserializationListener = Listener; OwnsDeserializationListener = TakeOwnership; } unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) { return serialization::ComputeHash(Sel); } std::pair<unsigned, unsigned> ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) { using namespace llvm::support; unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); return std::make_pair(KeyLen, DataLen); } ASTSelectorLookupTrait::internal_key_type ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) { using namespace llvm::support; SelectorTable &SelTable = Reader.getContext().Selectors; unsigned N = endian::readNext<uint16_t, little, unaligned>(d); IdentifierInfo *FirstII = Reader.getLocalIdentifier( F, endian::readNext<uint32_t, little, unaligned>(d)); if (N == 0) return SelTable.getNullarySelector(FirstII); else if (N == 1) return SelTable.getUnarySelector(FirstII); SmallVector<IdentifierInfo *, 16> Args; Args.push_back(FirstII); for (unsigned I = 1; I != N; ++I) Args.push_back(Reader.getLocalIdentifier( F, endian::readNext<uint32_t, little, unaligned>(d))); return SelTable.getSelector(N, Args.data()); } ASTSelectorLookupTrait::data_type ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, unsigned DataLen) { using namespace llvm::support; data_type Result; Result.ID = Reader.getGlobalSelectorID( F, endian::readNext<uint32_t, little, unaligned>(d)); unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d); unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d); Result.InstanceBits = FullInstanceBits & 0x3; Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1; Result.FactoryBits = FullFactoryBits & 0x3; Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1; unsigned NumInstanceMethods = FullInstanceBits >> 3; unsigned NumFactoryMethods = FullFactoryBits >> 3; // Load instance methods for (unsigned I = 0; I != NumInstanceMethods; ++I) { if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( F, endian::readNext<uint32_t, little, unaligned>(d))) Result.Instance.push_back(Method); } // Load factory methods for (unsigned I = 0; I != NumFactoryMethods; ++I) { if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( F, endian::readNext<uint32_t, little, unaligned>(d))) Result.Factory.push_back(Method); } return Result; } unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) { return llvm::HashString(a); } std::pair<unsigned, unsigned> ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) { using namespace llvm::support; unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); return std::make_pair(KeyLen, DataLen); } ASTIdentifierLookupTraitBase::internal_key_type ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) { assert(n >= 2 && d[n-1] == '\0'); return StringRef((const char*) d, n-1); } /// \brief Whether the given identifier is "interesting". static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II, bool IsModule) { return II.hadMacroDefinition() || II.isPoisoned() || (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) || II.hasRevertedTokenIDToIdentifier() || (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) && II.getFETokenInfo<void>()); } static bool readBit(unsigned &Bits) { bool Value = Bits & 0x1; Bits >>= 1; return Value; } IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) { using namespace llvm::support; unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); return Reader.getGlobalIdentifierID(F, RawID >> 1); } static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) { if (!II.isFromAST()) { II.setIsFromAST(); bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr; if (isInterestingIdentifier(Reader, II, IsModule)) II.setChangedSinceDeserialization(); } } IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, const unsigned char* d, unsigned DataLen) { using namespace llvm::support; unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); bool IsInteresting = RawID & 0x01; // Wipe out the "is interesting" bit. RawID = RawID >> 1; // Build the IdentifierInfo and link the identifier ID with it. IdentifierInfo *II = KnownII; if (!II) { II = &Reader.getIdentifierTable().getOwn(k); KnownII = II; } markIdentifierFromAST(Reader, *II); Reader.markIdentifierUpToDate(II); IdentID ID = Reader.getGlobalIdentifierID(F, RawID); if (!IsInteresting) { // For uninteresting identifiers, there's nothing else to do. Just notify // the reader that we've finished loading this identifier. Reader.SetIdentifierInfo(ID, II); return II; } unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d); unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d); bool CPlusPlusOperatorKeyword = readBit(Bits); bool HasRevertedTokenIDToIdentifier = readBit(Bits); bool HasRevertedBuiltin = readBit(Bits); bool Poisoned = readBit(Bits); bool ExtensionToken = readBit(Bits); bool HadMacroDefinition = readBit(Bits); assert(Bits == 0 && "Extra bits in the identifier?"); DataLen -= 8; // Set or check the various bits in the IdentifierInfo structure. // Token IDs are read-only. if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) II->revertTokenIDToIdentifier(); if (!F.isModule()) II->setObjCOrBuiltinID(ObjCOrBuiltinID); else if (HasRevertedBuiltin && II->getBuiltinID()) { II->revertBuiltin(); assert((II->hasRevertedBuiltin() || II->getObjCOrBuiltinID() == ObjCOrBuiltinID) && "Incorrect ObjC keyword or builtin ID"); } assert(II->isExtensionToken() == ExtensionToken && "Incorrect extension token flag"); (void)ExtensionToken; if (Poisoned) II->setIsPoisoned(true); assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && "Incorrect C++ operator keyword flag"); (void)CPlusPlusOperatorKeyword; // If this identifier is a macro, deserialize the macro // definition. if (HadMacroDefinition) { uint32_t MacroDirectivesOffset = endian::readNext<uint32_t, little, unaligned>(d); DataLen -= 4; Reader.addPendingMacro(II, &F, MacroDirectivesOffset); } Reader.SetIdentifierInfo(ID, II); // Read all of the declarations visible at global scope with this // name. if (DataLen > 0) { SmallVector<uint32_t, 4> DeclIDs; for (; DataLen > 0; DataLen -= 4) DeclIDs.push_back(Reader.getGlobalDeclID( F, endian::readNext<uint32_t, little, unaligned>(d))); Reader.SetGloballyVisibleDecls(II, DeclIDs); } return II; } DeclarationNameKey::DeclarationNameKey(DeclarationName Name) : Kind(Name.getNameKind()) { switch (Kind) { case DeclarationName::Identifier: Data = (uint64_t)Name.getAsIdentifierInfo(); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); break; case DeclarationName::CXXOperatorName: Data = Name.getCXXOverloadedOperator(); break; case DeclarationName::CXXLiteralOperatorName: Data = (uint64_t)Name.getCXXLiteralIdentifier(); break; case DeclarationName::CXXDeductionGuideName: Data = (uint64_t)Name.getCXXDeductionGuideTemplate() ->getDeclName().getAsIdentifierInfo(); break; case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXUsingDirective: Data = 0; break; } } unsigned DeclarationNameKey::getHash() const { llvm::FoldingSetNodeID ID; ID.AddInteger(Kind); switch (Kind) { case DeclarationName::Identifier: case DeclarationName::CXXLiteralOperatorName: case DeclarationName::CXXDeductionGuideName: ID.AddString(((IdentifierInfo*)Data)->getName()); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: ID.AddInteger(serialization::ComputeHash(Selector(Data))); break; case DeclarationName::CXXOperatorName: ID.AddInteger((OverloadedOperatorKind)Data); break; case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXUsingDirective: break; } return ID.ComputeHash(); } ModuleFile * ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) { using namespace llvm::support; uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d); return Reader.getLocalModuleFile(F, ModuleFileID); } std::pair<unsigned, unsigned> ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) { using namespace llvm::support; unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); return std::make_pair(KeyLen, DataLen); } ASTDeclContextNameLookupTrait::internal_key_type ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { using namespace llvm::support; auto Kind = (DeclarationName::NameKind)*d++; uint64_t Data; switch (Kind) { case DeclarationName::Identifier: case DeclarationName::CXXLiteralOperatorName: case DeclarationName::CXXDeductionGuideName: Data = (uint64_t)Reader.getLocalIdentifier( F, endian::readNext<uint32_t, little, unaligned>(d)); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: Data = (uint64_t)Reader.getLocalSelector( F, endian::readNext<uint32_t, little, unaligned>( d)).getAsOpaquePtr(); break; case DeclarationName::CXXOperatorName: Data = *d++; // OverloadedOperatorKind break; case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXUsingDirective: Data = 0; break; } return DeclarationNameKey(Kind, Data); } void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val) { using namespace llvm::support; for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) { uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d); Val.insert(Reader.getGlobalDeclID(F, LocalID)); } } bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, DeclContext *DC) { assert(Offset != 0); SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(Offset); RecordData Record; StringRef Blob; unsigned Code = Cursor.ReadCode(); unsigned RecCode = Cursor.readRecord(Code, Record, &Blob); if (RecCode != DECL_CONTEXT_LEXICAL) { Error("Expected lexical block"); return true; } assert(!isa<TranslationUnitDecl>(DC) && "expected a TU_UPDATE_LEXICAL record for TU"); // If we are handling a C++ class template instantiation, we can see multiple // lexical updates for the same record. It's important that we select only one // of them, so that field numbering works properly. Just pick the first one we // see. auto &Lex = LexicalDecls[DC]; if (!Lex.first) { Lex = std::make_pair( &M, llvm::makeArrayRef( reinterpret_cast<const llvm::support::unaligned_uint32_t *>( Blob.data()), Blob.size() / 4)); } DC->setHasExternalLexicalStorage(true); return false; } bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, DeclID ID) { assert(Offset != 0); SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(Offset); RecordData Record; StringRef Blob; unsigned Code = Cursor.ReadCode(); unsigned RecCode = Cursor.readRecord(Code, Record, &Blob); if (RecCode != DECL_CONTEXT_VISIBLE) { Error("Expected visible lookup table block"); return true; } // We can't safely determine the primary context yet, so delay attaching the // lookup table until we're done with recursive deserialization. auto *Data = (const unsigned char*)Blob.data(); PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data}); return false; } void ASTReader::Error(StringRef Msg) const { Error(diag::err_fe_pch_malformed, Msg); if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { Diag(diag::note_module_cache_path) << PP.getHeaderSearchInfo().getModuleCachePath(); } } void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2) const { if (Diags.isDiagnosticInFlight()) Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2); else Diag(DiagID) << Arg1 << Arg2; } //===----------------------------------------------------------------------===// // Source Manager Deserialization //===----------------------------------------------------------------------===// /// \brief Read the line table in the source manager block. /// \returns true if there was an error. bool ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) { unsigned Idx = 0; LineTableInfo &LineTable = SourceMgr.getLineTable(); // Parse the file names std::map<int, int> FileIDs; FileIDs[-1] = -1; // For unspecified filenames. for (unsigned I = 0; Record[Idx]; ++I) { // Extract the file name auto Filename = ReadPath(F, Record, Idx); FileIDs[I] = LineTable.getLineTableFilenameID(Filename); } ++Idx; // Parse the line entries std::vector<LineEntry> Entries; while (Idx < Record.size()) { int FID = Record[Idx++]; assert(FID >= 0 && "Serialized line entries for non-local file."); // Remap FileID from 1-based old view. FID += F.SLocEntryBaseID - 1; // Extract the line entries unsigned NumEntries = Record[Idx++]; assert(NumEntries && "no line entries for file ID"); Entries.clear(); Entries.reserve(NumEntries); for (unsigned I = 0; I != NumEntries; ++I) { unsigned FileOffset = Record[Idx++]; unsigned LineNo = Record[Idx++]; int FilenameID = FileIDs[Record[Idx++]]; SrcMgr::CharacteristicKind FileKind = (SrcMgr::CharacteristicKind)Record[Idx++]; unsigned IncludeOffset = Record[Idx++]; Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, FileKind, IncludeOffset)); } LineTable.AddEntry(FileID::get(FID), Entries); } return false; } /// \brief Read a source manager block bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) { using namespace SrcMgr; BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; // Set the source-location entry cursor to the current position in // the stream. This cursor will be used to read the contents of the // source manager block initially, and then lazily read // source-location entries as needed. SLocEntryCursor = F.Stream; // The stream itself is going to skip over the source manager block. if (F.Stream.SkipBlock()) { Error("malformed block record in AST file"); return true; } // Enter the source manager block. if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) { Error("malformed source manager block record in AST file"); return true; } RecordData Record; while (true) { llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks(); switch (E.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return true; case llvm::BitstreamEntry::EndBlock: return false; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read a record. Record.clear(); StringRef Blob; switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) { default: // Default behavior: ignore. break; case SM_SLOC_FILE_ENTRY: case SM_SLOC_BUFFER_ENTRY: case SM_SLOC_EXPANSION_ENTRY: // Once we hit one of the source location entries, we're done. return false; } } } /// \brief If a header file is not found at the path that we expect it to be /// and the PCH file was moved from its original location, try to resolve the /// file by assuming that header+PCH were moved together and the header is in /// the same place relative to the PCH. static std::string resolveFileRelativeToOriginalDir(const std::string &Filename, const std::string &OriginalDir, const std::string &CurrDir) { assert(OriginalDir != CurrDir && "No point trying to resolve the file if the PCH dir didn't change"); using namespace llvm::sys; SmallString<128> filePath(Filename); fs::make_absolute(filePath); assert(path::is_absolute(OriginalDir)); SmallString<128> currPCHPath(CurrDir); path::const_iterator fileDirI = path::begin(path::parent_path(filePath)), fileDirE = path::end(path::parent_path(filePath)); path::const_iterator origDirI = path::begin(OriginalDir), origDirE = path::end(OriginalDir); // Skip the common path components from filePath and OriginalDir. while (fileDirI != fileDirE && origDirI != origDirE && *fileDirI == *origDirI) { ++fileDirI; ++origDirI; } for (; origDirI != origDirE; ++origDirI) path::append(currPCHPath, ".."); path::append(currPCHPath, fileDirI, fileDirE); path::append(currPCHPath, path::filename(Filename)); return currPCHPath.str(); } bool ASTReader::ReadSLocEntry(int ID) { if (ID == 0) return false; if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { Error("source location entry ID out-of-range for AST file"); return true; } // Local helper to read the (possibly-compressed) buffer data following the // entry record. auto ReadBuffer = [this]( BitstreamCursor &SLocEntryCursor, StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> { RecordData Record; StringRef Blob; unsigned Code = SLocEntryCursor.ReadCode(); unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob); if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { if (!llvm::zlib::isAvailable()) { Error("zlib is not available"); return nullptr; } SmallString<0> Uncompressed; if (llvm::Error E = llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) { Error("could not decompress embedded file contents: " + llvm::toString(std::move(E))); return nullptr; } return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name); } else if (RecCode == SM_SLOC_BUFFER_BLOB) { return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true); } else { Error("AST record has invalid code"); return nullptr; } }; ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second; F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]); BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; unsigned BaseOffset = F->SLocEntryBaseOffset; ++NumSLocEntriesRead; llvm::BitstreamEntry Entry = SLocEntryCursor.advance(); if (Entry.Kind != llvm::BitstreamEntry::Record) { Error("incorrectly-formatted source location entry in AST file"); return true; } RecordData Record; StringRef Blob; switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) { default: Error("incorrectly-formatted source location entry in AST file"); return true; case SM_SLOC_FILE_ENTRY: { // We will detect whether a file changed and return 'Failure' for it, but // we will also try to fail gracefully by setting up the SLocEntry. unsigned InputID = Record[4]; InputFile IF = getInputFile(*F, InputID, /*Complain=*/false); const FileEntry *File = IF.getFile(); bool OverriddenBuffer = IF.isOverridden(); // Note that we only check if a File was returned. If it was out-of-date // we have complained but we will continue creating a FileID to recover // gracefully. if (!File) return true; SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) { // This is the module's main file. IncludeLoc = getImportLocation(F); } SrcMgr::CharacteristicKind FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter, ID, BaseOffset + Record[0]); SrcMgr::FileInfo &FileInfo = const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile()); FileInfo.NumCreatedFIDs = Record[5]; if (Record[3]) FileInfo.setHasLineDirectives(); const DeclID *FirstDecl = F->FileSortedDecls + Record[6]; unsigned NumFileDecls = Record[7]; if (NumFileDecls && ContextObj) { assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?"); FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl, NumFileDecls)); } const SrcMgr::ContentCache *ContentCache = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter)); if (OverriddenBuffer && !ContentCache->BufferOverridden && ContentCache->ContentsEntry == ContentCache->OrigEntry && !ContentCache->getRawBuffer()) { auto Buffer = ReadBuffer(SLocEntryCursor, File->getName()); if (!Buffer) return true; SourceMgr.overrideFileContents(File, std::move(Buffer)); } break; } case SM_SLOC_BUFFER_ENTRY: { const char *Name = Blob.data(); unsigned Offset = Record[0]; SrcMgr::CharacteristicKind FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); if (IncludeLoc.isInvalid() && F->isModule()) { IncludeLoc = getImportLocation(F); } auto Buffer = ReadBuffer(SLocEntryCursor, Name); if (!Buffer) return true; SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID, BaseOffset + Offset, IncludeLoc); break; } case SM_SLOC_EXPANSION_ENTRY: { SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]); SourceMgr.createExpansionLoc(SpellingLoc, ReadSourceLocation(*F, Record[2]), ReadSourceLocation(*F, Record[3]), Record[4], ID, BaseOffset + Record[0]); break; } } return false; } std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) { if (ID == 0) return std::make_pair(SourceLocation(), ""); if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { Error("source location entry ID out-of-range for AST file"); return std::make_pair(SourceLocation(), ""); } // Find which module file this entry lands in. ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second; if (!M->isModule()) return std::make_pair(SourceLocation(), ""); // FIXME: Can we map this down to a particular submodule? That would be // ideal. return std::make_pair(M->ImportLoc, StringRef(M->ModuleName)); } /// \brief Find the location where the module F is imported. SourceLocation ASTReader::getImportLocation(ModuleFile *F) { if (F->ImportLoc.isValid()) return F->ImportLoc; // Otherwise we have a PCH. It's considered to be "imported" at the first // location of its includer. if (F->ImportedBy.empty() || !F->ImportedBy[0]) { // Main file is the importer. assert(SourceMgr.getMainFileID().isValid() && "missing main file"); return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); } return F->ImportedBy[0]->FirstLoc; } /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the /// specified cursor. Read the abbreviations that are at the top of the block /// and then leave the cursor pointing into the block. bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) { if (Cursor.EnterSubBlock(BlockID)) return true; while (true) { uint64_t Offset = Cursor.GetCurrentBitNo(); unsigned Code = Cursor.ReadCode(); // We expect all abbrevs to be at the start of the block. if (Code != llvm::bitc::DEFINE_ABBREV) { Cursor.JumpToBit(Offset); return false; } Cursor.ReadAbbrevRecord(); } } Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) { Token Tok; Tok.startToken(); Tok.setLocation(ReadSourceLocation(F, Record, Idx)); Tok.setLength(Record[Idx++]); if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++])) Tok.setIdentifierInfo(II); Tok.setKind((tok::TokenKind)Record[Idx++]); Tok.setFlag((Token::TokenFlags)Record[Idx++]); if (Tok.isLiteral()) { const RecordData& RD = reinterpret_cast<const RecordData&>(Record); std::string* Lit = new std::string(ReadString(RD, Idx)); TokenLiteralDataLoaded.push_back(Lit); Tok.setLiteralData(Lit->c_str()); } return Tok; } MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { BitstreamCursor &Stream = F.MacroCursor; // Keep track of where we are in the stream, then jump back there // after reading this macro. SavedStreamPosition SavedPosition(Stream); Stream.JumpToBit(Offset); RecordData Record; SmallVector<IdentifierInfo*, 16> MacroParams; MacroInfo *Macro = nullptr; while (true) { // Advance to the next record, but if we get to the end of the block, don't // pop it (removing all the abbreviations from the cursor) since we want to // be able to reseek within the block and read entries. unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd; llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return Macro; case llvm::BitstreamEntry::EndBlock: return Macro; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read a record. Record.clear(); PreprocessorRecordTypes RecType = (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record); switch (RecType) { case PP_MODULE_MACRO: case PP_MACRO_DIRECTIVE_HISTORY: return Macro; case PP_MACRO_OBJECT_LIKE: case PP_MACRO_FUNCTION_LIKE: { // If we already have a macro, that means that we've hit the end // of the definition of the macro we were looking for. We're // done. if (Macro) return Macro; unsigned NextIndex = 1; // Skip identifier ID. SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex); MacroInfo *MI = PP.AllocateMacroInfo(Loc); MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex)); MI->setIsUsed(Record[NextIndex++]); MI->setUsedForHeaderGuard(Record[NextIndex++]); if (RecType == PP_MACRO_FUNCTION_LIKE) { // Decode function-like macro info. bool isC99VarArgs = Record[NextIndex++]; bool isGNUVarArgs = Record[NextIndex++]; bool hasCommaPasting = Record[NextIndex++]; MacroParams.clear(); unsigned NumArgs = Record[NextIndex++]; for (unsigned i = 0; i != NumArgs; ++i) MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++])); // Install function-like macro info. MI->setIsFunctionLike(); if (isC99VarArgs) MI->setIsC99Varargs(); if (isGNUVarArgs) MI->setIsGNUVarargs(); if (hasCommaPasting) MI->setHasCommaPasting(); MI->setParameterList(MacroParams, PP.getPreprocessorAllocator()); } // Remember that we saw this macro last so that we add the tokens that // form its body to it. Macro = MI; if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() && Record[NextIndex]) { // We have a macro definition. Register the association PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]); PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); PreprocessingRecord::PPEntityID PPID = PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true); MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>( PPRec.getPreprocessedEntity(PPID)); if (PPDef) PPRec.RegisterMacroDefinition(Macro, PPDef); } ++NumMacrosRead; break; } case PP_TOKEN: { // If we see a TOKEN before a PP_MACRO_*, then the file is // erroneous, just pretend we didn't see this. if (!Macro) break; unsigned Idx = 0; Token Tok = ReadToken(F, Record, Idx); Macro->AddTokenToBody(Tok); break; } } } } PreprocessedEntityID ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const { if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::const_iterator I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS); assert(I != M.PreprocessedEntityRemap.end() && "Invalid index into preprocessed entity index remap"); return LocalID + I->second; } unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) { return llvm::hash_combine(ikey.Size, ikey.ModTime); } HeaderFileInfoTrait::internal_key_type HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) { internal_key_type ikey = {FE->getSize(), M.HasTimestamps ? FE->getModificationTime() : 0, FE->getName(), /*Imported*/ false}; return ikey; } bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) { if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime)) return false; if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename) return true; // Determine whether the actual files are equivalent. FileManager &FileMgr = Reader.getFileManager(); auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* { if (!Key.Imported) return FileMgr.getFile(Key.Filename); std::string Resolved = Key.Filename; Reader.ResolveImportedPath(M, Resolved); return FileMgr.getFile(Resolved); }; const FileEntry *FEA = GetFile(a); const FileEntry *FEB = GetFile(b); return FEA && FEA == FEB; } std::pair<unsigned, unsigned> HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) { using namespace llvm::support; unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d); unsigned DataLen = (unsigned) *d++; return std::make_pair(KeyLen, DataLen); } HeaderFileInfoTrait::internal_key_type HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) { using namespace llvm::support; internal_key_type ikey; ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d)); ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d)); ikey.Filename = (const char *)d; ikey.Imported = true; return ikey; } HeaderFileInfoTrait::data_type HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d, unsigned DataLen) { const unsigned char *End = d + DataLen; using namespace llvm::support; HeaderFileInfo HFI; unsigned Flags = *d++; // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. HFI.isImport |= (Flags >> 5) & 0x01; HFI.isPragmaOnce |= (Flags >> 4) & 0x01; HFI.DirInfo = (Flags >> 1) & 0x07; HFI.IndexHeaderMapHeader = Flags & 0x01; // FIXME: Find a better way to handle this. Maybe just store a // "has been included" flag? HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d), HFI.NumIncludes); HFI.ControllingMacroID = Reader.getGlobalIdentifierID( M, endian::readNext<uint32_t, little, unaligned>(d)); if (unsigned FrameworkOffset = endian::readNext<uint32_t, little, unaligned>(d)) { // The framework offset is 1 greater than the actual offset, // since 0 is used as an indicator for "no framework name". StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1); HFI.Framework = HS->getUniqueFrameworkName(FrameworkName); } assert((End - d) % 4 == 0 && "Wrong data length in HeaderFileInfo deserialization"); while (d != End) { uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d); auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3); LocalSMID >>= 2; // This header is part of a module. Associate it with the module to enable // implicit module import. SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID); Module *Mod = Reader.getSubmodule(GlobalSMID); FileManager &FileMgr = Reader.getFileManager(); ModuleMap &ModMap = Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap(); std::string Filename = key.Filename; if (key.Imported) Reader.ResolveImportedPath(M, Filename); // FIXME: This is not always the right filename-as-written, but we're not // going to use this information to rebuild the module, so it doesn't make // a lot of difference. Module::Header H = { key.Filename, FileMgr.getFile(Filename) }; ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true); HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader); } // This HeaderFileInfo was externally loaded. HFI.External = true; HFI.IsValid = true; return HFI; } void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint64_t MacroDirectivesOffset) { assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard"); PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset)); } void ASTReader::ReadDefinedMacros() { // Note that we are loading defined macros. Deserializing Macros(this); for (ModuleFile &I : llvm::reverse(ModuleMgr)) { BitstreamCursor &MacroCursor = I.MacroCursor; // If there was no preprocessor block, skip this file. if (MacroCursor.getBitcodeBytes().empty()) continue; BitstreamCursor Cursor = MacroCursor; Cursor.JumpToBit(I.MacroStartOffset); RecordData Record; while (true) { llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks(); switch (E.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return; case llvm::BitstreamEntry::EndBlock: goto NextCursor; case llvm::BitstreamEntry::Record: Record.clear(); switch (Cursor.readRecord(E.ID, Record)) { default: // Default behavior: ignore. break; case PP_MACRO_OBJECT_LIKE: case PP_MACRO_FUNCTION_LIKE: { IdentifierInfo *II = getLocalIdentifier(I, Record[0]); if (II->isOutOfDate()) updateOutOfDateIdentifier(*II); break; } case PP_TOKEN: // Ignore tokens. break; } break; } } NextCursor: ; } } namespace { /// \brief Visitor class used to look up identifirs in an AST file. class IdentifierLookupVisitor { StringRef Name; unsigned NameHash; unsigned PriorGeneration; unsigned &NumIdentifierLookups; unsigned &NumIdentifierLookupHits; IdentifierInfo *Found; public: IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, unsigned &NumIdentifierLookups, unsigned &NumIdentifierLookupHits) : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)), PriorGeneration(PriorGeneration), NumIdentifierLookups(NumIdentifierLookups), NumIdentifierLookupHits(NumIdentifierLookupHits), Found() { } bool operator()(ModuleFile &M) { // If we've already searched this module file, skip it now. if (M.Generation <= PriorGeneration) return true; ASTIdentifierLookupTable *IdTable = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; if (!IdTable) return false; ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, Found); ++NumIdentifierLookups; ASTIdentifierLookupTable::iterator Pos = IdTable->find_hashed(Name, NameHash, &Trait); if (Pos == IdTable->end()) return false; // Dereferencing the iterator has the effect of building the // IdentifierInfo node and populating it with the various // declarations it needs. ++NumIdentifierLookupHits; Found = *Pos; return true; } // \brief Retrieve the identifier info found within the module // files. IdentifierInfo *getIdentifierInfo() const { return Found; } }; } // end anonymous namespace void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) { // Note that we are loading an identifier. Deserializing AnIdentifier(this); unsigned PriorGeneration = 0; if (getContext().getLangOpts().Modules) PriorGeneration = IdentifierGeneration[&II]; // If there is a global index, look there first to determine which modules // provably do not have any results for this identifier. GlobalModuleIndex::HitSet Hits; GlobalModuleIndex::HitSet *HitsPtr = nullptr; if (!loadGlobalIndex()) { if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) { HitsPtr = &Hits; } } IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, NumIdentifierLookups, NumIdentifierLookupHits); ModuleMgr.visit(Visitor, HitsPtr); markIdentifierUpToDate(&II); } void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) { if (!II) return; II->setOutOfDate(false); // Update the generation for this identifier. if (getContext().getLangOpts().Modules) IdentifierGeneration[II] = getGenerationOrNull(); } void ASTReader::resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo) { ModuleFile &M = *PMInfo.M; BitstreamCursor &Cursor = M.MacroCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(PMInfo.MacroDirectivesOffset); struct ModuleMacroRecord { SubmoduleID SubModID; MacroInfo *MI; SmallVector<SubmoduleID, 8> Overrides; }; llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; // We expect to see a sequence of PP_MODULE_MACRO records listing exported // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete // macro histroy. RecordData Record; while (true) { llvm::BitstreamEntry Entry = Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); if (Entry.Kind != llvm::BitstreamEntry::Record) { Error("malformed block record in AST file"); return; } Record.clear(); switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) { case PP_MACRO_DIRECTIVE_HISTORY: break; case PP_MODULE_MACRO: { ModuleMacros.push_back(ModuleMacroRecord()); auto &Info = ModuleMacros.back(); Info.SubModID = getGlobalSubmoduleID(M, Record[0]); Info.MI = getMacro(getGlobalMacroID(M, Record[1])); for (int I = 2, N = Record.size(); I != N; ++I) Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I])); continue; } default: Error("malformed block record in AST file"); return; } // We found the macro directive history; that's the last record // for this macro. break; } // Module macros are listed in reverse dependency order. { std::reverse(ModuleMacros.begin(), ModuleMacros.end()); llvm::SmallVector<ModuleMacro*, 8> Overrides; for (auto &MMR : ModuleMacros) { Overrides.clear(); for (unsigned ModID : MMR.Overrides) { Module *Mod = getSubmodule(ModID); auto *Macro = PP.getModuleMacro(Mod, II); assert(Macro && "missing definition for overridden macro"); Overrides.push_back(Macro); } bool Inserted = false; Module *Owner = getSubmodule(MMR.SubModID); PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted); } } // Don't read the directive history for a module; we don't have anywhere // to put it. if (M.isModule()) return; // Deserialize the macro directives history in reverse source-order. MacroDirective *Latest = nullptr, *Earliest = nullptr; unsigned Idx = 0, N = Record.size(); while (Idx < N) { MacroDirective *MD = nullptr; SourceLocation Loc = ReadSourceLocation(M, Record, Idx); MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; switch (K) { case MacroDirective::MD_Define: { MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++])); MD = PP.AllocateDefMacroDirective(MI, Loc); break; } case MacroDirective::MD_Undefine: { MD = PP.AllocateUndefMacroDirective(Loc); break; } case MacroDirective::MD_Visibility: bool isPublic = Record[Idx++]; MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); break; } if (!Latest) Latest = MD; if (Earliest) Earliest->setPrevious(MD); Earliest = MD; } if (Latest) PP.setLoadedMacroDirective(II, Earliest, Latest); } ASTReader::InputFileInfo ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) { // Go find this input file. BitstreamCursor &Cursor = F.InputFilesCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(F.InputFileOffsets[ID-1]); unsigned Code = Cursor.ReadCode(); RecordData Record; StringRef Blob; unsigned Result = Cursor.readRecord(Code, Record, &Blob); assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE && "invalid record type for input file"); (void)Result; assert(Record[0] == ID && "Bogus stored ID or offset"); InputFileInfo R; R.StoredSize = static_cast<off_t>(Record[1]); R.StoredTime = static_cast<time_t>(Record[2]); R.Overridden = static_cast<bool>(Record[3]); R.Transient = static_cast<bool>(Record[4]); R.TopLevelModuleMap = static_cast<bool>(Record[5]); R.Filename = Blob; ResolveImportedPath(F, R.Filename); return R; } static unsigned moduleKindForDiagnostic(ModuleKind Kind); InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { // If this ID is bogus, just return an empty input file. if (ID == 0 || ID > F.InputFilesLoaded.size()) return InputFile(); // If we've already loaded this input file, return it. if (F.InputFilesLoaded[ID-1].getFile()) return F.InputFilesLoaded[ID-1]; if (F.InputFilesLoaded[ID-1].isNotFound()) return InputFile(); // Go find this input file. BitstreamCursor &Cursor = F.InputFilesCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(F.InputFileOffsets[ID-1]); InputFileInfo FI = readInputFileInfo(F, ID); off_t StoredSize = FI.StoredSize; time_t StoredTime = FI.StoredTime; bool Overridden = FI.Overridden; bool Transient = FI.Transient; StringRef Filename = FI.Filename; const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false); // If we didn't find the file, resolve it relative to the // original directory from which this AST file was created. if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() && F.OriginalDir != CurrentDir) { std::string Resolved = resolveFileRelativeToOriginalDir(Filename, F.OriginalDir, CurrentDir); if (!Resolved.empty()) File = FileMgr.getFile(Resolved); } // For an overridden file, create a virtual file with the stored // size/timestamp. if ((Overridden || Transient) && File == nullptr) File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime); if (File == nullptr) { if (Complain) { std::string ErrorStr = "could not find file '"; ErrorStr += Filename; ErrorStr += "' referenced by AST file '"; ErrorStr += F.FileName; ErrorStr += "'"; Error(ErrorStr); } // Record that we didn't find the file. F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); return InputFile(); } // Check if there was a request to override the contents of the file // that was part of the precompiled header. Overridding such a file // can lead to problems when lexing using the source locations from the // PCH. SourceManager &SM = getSourceManager(); // FIXME: Reject if the overrides are different. if ((!Overridden && !Transient) && SM.isFileOverridden(File)) { if (Complain) Error(diag::err_fe_pch_file_overridden, Filename); // After emitting the diagnostic, recover by disabling the override so // that the original file will be used. // // FIXME: This recovery is just as broken as the original state; there may // be another precompiled module that's using the overridden contents, or // we might be half way through parsing it. Instead, we should treat the // overridden contents as belonging to a separate FileEntry. SM.disableFileContentsOverride(File); // The FileEntry is a virtual file entry with the size of the contents // that would override the original contents. Set it to the original's // size/time. FileMgr.modifyFileEntry(const_cast<FileEntry*>(File), StoredSize, StoredTime); } bool IsOutOfDate = false; // For an overridden file, there is nothing to validate. if (!Overridden && // (StoredSize != File->getSize() || (StoredTime && StoredTime != File->getModificationTime() && !DisableValidation) )) { if (Complain) { // Build a list of the PCH imports that got us here (in reverse). SmallVector<ModuleFile *, 4> ImportStack(1, &F); while (ImportStack.back()->ImportedBy.size() > 0) ImportStack.push_back(ImportStack.back()->ImportedBy[0]); // The top-level PCH is stale. StringRef TopLevelPCHName(ImportStack.back()->FileName); unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind); if (DiagnosticKind == 0) Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName); else if (DiagnosticKind == 1) Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName); else Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName); // Print the import stack. if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) { Diag(diag::note_pch_required_by) << Filename << ImportStack[0]->FileName; for (unsigned I = 1; I < ImportStack.size(); ++I) Diag(diag::note_pch_required_by) << ImportStack[I-1]->FileName << ImportStack[I]->FileName; } if (!Diags.isDiagnosticInFlight()) Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; } IsOutOfDate = true; } // FIXME: If the file is overridden and we've already opened it, // issue an error (or split it into a separate FileEntry). // FIXME: Complain before hitting the assert. We should investigate why we // hit this unforeseen case. if ((Overridden || Transient) && IsOutOfDate) Error(diag::err_fe_pch_file_overridden, Filename); InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate); // Note that we've loaded this input file. F.InputFilesLoaded[ID-1] = IF; return IF; } /// \brief If we are loading a relocatable PCH or module file, and the filename /// is not an absolute path, add the system or module root to the beginning of /// the file name. void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) { // Resolve relative to the base directory, if we have one. if (!M.BaseDirectory.empty()) return ResolveImportedPath(Filename, M.BaseDirectory); } void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) { if (Filename.empty() || llvm::sys::path::is_absolute(Filename)) return; SmallString<128> Buffer; llvm::sys::path::append(Buffer, Prefix, Filename); Filename.assign(Buffer.begin(), Buffer.end()); } static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { switch (ARR) { case ASTReader::Failure: return true; case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); case ASTReader::ConfigurationMismatch: return !(Caps & ASTReader::ARR_ConfigurationMismatch); case ASTReader::HadErrors: return true; case ASTReader::Success: return false; } llvm_unreachable("unknown ASTReadResult"); } ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( BitstreamCursor &Stream, unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, std::string &SuggestedPredefines) { if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) return Failure; // Read all of the records in the options block. RecordData Record; ASTReadResult Result = Success; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: case llvm::BitstreamEntry::SubBlock: return Failure; case llvm::BitstreamEntry::EndBlock: return Result; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read and process a record. Record.clear(); switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) { case LANGUAGE_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (ParseLanguageOptions(Record, Complain, Listener, AllowCompatibleConfigurationMismatch)) Result = ConfigurationMismatch; break; } case TARGET_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (ParseTargetOptions(Record, Complain, Listener, AllowCompatibleConfigurationMismatch)) Result = ConfigurationMismatch; break; } case FILE_SYSTEM_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (!AllowCompatibleConfigurationMismatch && ParseFileSystemOptions(Record, Complain, Listener)) Result = ConfigurationMismatch; break; } case HEADER_SEARCH_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (!AllowCompatibleConfigurationMismatch && ParseHeaderSearchOptions(Record, Complain, Listener)) Result = ConfigurationMismatch; break; } case PREPROCESSOR_OPTIONS: bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; if (!AllowCompatibleConfigurationMismatch && ParsePreprocessorOptions(Record, Complain, Listener, SuggestedPredefines)) Result = ConfigurationMismatch; break; } } } ASTReader::ASTReadResult ASTReader::ReadControlBlock(ModuleFile &F, SmallVectorImpl<ImportedModule> &Loaded, const ModuleFile *ImportedBy, unsigned ClientLoadCapabilities) { BitstreamCursor &Stream = F.Stream; ASTReadResult Result = Success; if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } // Lambda to read the unhashed control block the first time it's called. // // For PCM files, the unhashed control block cannot be read until after the // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still // need to look ahead before reading the IMPORTS record. For consistency, // this block is always read somehow (see BitstreamEntry::EndBlock). bool HasReadUnhashedControlBlock = false; auto readUnhashedControlBlockOnce = [&]() { if (!HasReadUnhashedControlBlock) { HasReadUnhashedControlBlock = true; if (ASTReadResult Result = readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities)) return Result; } return Success; }; // Read all of the records and blocks in the control block. RecordData Record; unsigned NumInputs = 0; unsigned NumUserInputs = 0; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return Failure; case llvm::BitstreamEntry::EndBlock: { // Validate the module before returning. This call catches an AST with // no module name and no imports. if (ASTReadResult Result = readUnhashedControlBlockOnce()) return Result; // Validate input files. const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); // All user input files reside at the index range [0, NumUserInputs), and // system input files reside at [NumUserInputs, NumInputs). For explicitly // loaded module files, ignore missing inputs. bool Validate = !DisableValidation && F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule; bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; Complain &= Validate; // If we are reading a module, we will create a verification timestamp, // so we verify all input files. Otherwise, verify only user input // files. unsigned N = NumUserInputs; if (ValidateSystemInputs || (HSOpts.ModulesValidateOncePerBuildSession && F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp && F.Kind == MK_ImplicitModule)) N = NumInputs; for (unsigned I = 0; I < NumInputs; ++I) { if (I == N) Complain = false; InputFile IF = getInputFile(F, I+1, Complain); if (Validate && (!IF.getFile() || IF.isOutOfDate())) return OutOfDate; } if (Listener) Listener->visitModuleFile(F.FileName, F.Kind); if (Listener && Listener->needsInputFileVisitation()) { unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs : NumUserInputs; for (unsigned I = 0; I < N; ++I) { bool IsSystem = I >= NumUserInputs; InputFileInfo FI = readInputFileInfo(F, I+1); Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden, F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule); } } return Result; } case llvm::BitstreamEntry::SubBlock: switch (Entry.ID) { case INPUT_FILES_BLOCK_ID: F.InputFilesCursor = Stream; if (Stream.SkipBlock() || // Skip with the main cursor // Read the abbreviations ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } continue; case OPTIONS_BLOCK_ID: // If we're reading the first module for this group, check its options // are compatible with ours. For modules it imports, no further checking // is required, because we checked them when we built it. if (Listener && !ImportedBy) { // Should we allow the configuration of the module file to differ from // the configuration of the current translation unit in a compatible // way? // // FIXME: Allow this for files explicitly specified with -include-pch. bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; Result = ReadOptionsBlock(Stream, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, *Listener, SuggestedPredefines); if (Result == Failure) { Error("malformed block record in AST file"); return Result; } if (DisableValidation || (AllowConfigurationMismatch && Result == ConfigurationMismatch)) Result = Success; // If we can't load the module, exit early since we likely // will rebuild the module anyway. The stream may be in the // middle of a block. if (Result != Success) return Result; } else if (Stream.SkipBlock()) { Error("malformed block record in AST file"); return Failure; } continue; default: if (Stream.SkipBlock()) { Error("malformed block record in AST file"); return Failure; } continue; } case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read and process a record. Record.clear(); StringRef Blob; switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) { case METADATA: { if (Record[0] != VERSION_MAJOR && !DisableValidation) { if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old : diag::err_pch_version_too_new); return VersionMismatch; } bool hasErrors = Record[6]; if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) { Diag(diag::err_pch_with_compiler_errors); return HadErrors; } if (hasErrors) { Diags.ErrorOccurred = true; Diags.UncompilableErrorOccurred = true; Diags.UnrecoverableErrorOccurred = true; } F.RelocatablePCH = Record[4]; // Relative paths in a relocatable PCH are relative to our sysroot. if (F.RelocatablePCH) F.BaseDirectory = isysroot.empty() ? "/" : isysroot; F.HasTimestamps = Record[5]; const std::string &CurBranch = getClangFullRepositoryVersion(); StringRef ASTBranch = Blob; if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch; return VersionMismatch; } break; } case IMPORTS: { // Validate the AST before processing any imports (otherwise, untangling // them can be error-prone and expensive). A module will have a name and // will already have been validated, but this catches the PCH case. if (ASTReadResult Result = readUnhashedControlBlockOnce()) return Result; // Load each of the imported PCH files. unsigned Idx = 0, N = Record.size(); while (Idx < N) { // Read information about the AST file. ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; // The import location will be the local one for now; we will adjust // all import locations of module imports after the global source // location info are setup, in ReadAST. SourceLocation ImportLoc = ReadUntranslatedSourceLocation(Record[Idx++]); off_t StoredSize = (off_t)Record[Idx++]; time_t StoredModTime = (time_t)Record[Idx++]; ASTFileSignature StoredSignature = { {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++], (uint32_t)Record[Idx++], (uint32_t)Record[Idx++], (uint32_t)Record[Idx++]}}}; auto ImportedFile = ReadPath(F, Record, Idx); // Check if ImportedFile exists on disk if (!llvm::sys::fs::is_directory(ImportedFile)) { StringRef ModuleName = llvm::sys::path::filename(ImportedFile.c_str()); ModuleName.consume_back(".pcm"); // Get clang::Module pointer by looking up the module name clang::Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName, true, true); if (M) { std::string Path = PP.getHeaderSearchInfo().getModuleFileName(M->Name, PP.getHeaderSearchInfo().getModuleMap().getModuleMapFileForUniquing(M)->getName(), true); // FIXME: Add a hash comparison to check if ImportedFile's hash and the // new Modules Path's hash matches or not. if (!Path.empty()) ImportedFile = Path; } } // If our client can't cope with us being out of date, we can't cope with // our dependency being missing. unsigned Capabilities = ClientLoadCapabilities; if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Capabilities &= ~ARR_Missing; // Load the AST file. auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded, StoredSize, StoredModTime, StoredSignature, Capabilities); // If we diagnosed a problem, produce a backtrace. if (isDiagnosedResult(Result, Capabilities)) Diag(diag::note_module_file_imported_by) << F.FileName << !F.ModuleName.empty() << F.ModuleName; switch (Result) { case Failure: return Failure; // If we have to ignore the dependency, we'll have to ignore this too. case Missing: case OutOfDate: return OutOfDate; case VersionMismatch: return VersionMismatch; case ConfigurationMismatch: return ConfigurationMismatch; case HadErrors: return HadErrors; case Success: break; } } break; } case ORIGINAL_FILE: F.OriginalSourceFileID = FileID::get(Record[0]); F.ActualOriginalSourceFileName = Blob; F.OriginalSourceFileName = F.ActualOriginalSourceFileName; ResolveImportedPath(F, F.OriginalSourceFileName); break; case ORIGINAL_FILE_ID: F.OriginalSourceFileID = FileID::get(Record[0]); break; case ORIGINAL_PCH_DIR: F.OriginalDir = Blob; break; case MODULE_NAME: F.ModuleName = Blob; if (Listener) Listener->ReadModuleName(F.ModuleName); // Validate the AST as soon as we have a name so we can exit early on // failure. if (ASTReadResult Result = readUnhashedControlBlockOnce()) return Result; break; case MODULE_DIRECTORY: { assert(!F.ModuleName.empty() && "MODULE_DIRECTORY found before MODULE_NAME"); // If we've already loaded a module map file covering this module, we may // have a better path for it (relative to the current build). Module *M = PP.getHeaderSearchInfo().lookupModule( F.ModuleName, /*AllowSearch*/ true, /*AllowExtraModuleMapSearch*/ true); if (M && M->Directory) { // If we're implicitly loading a module, the base directory can't // change between the build and use. // Don't emit module relocation error if we have -fno-validate-pch if (!PP.getPreprocessorOpts().DisablePCHValidation && F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { const DirectoryEntry *BuildDir = PP.getFileManager().getDirectory(Blob); if (!BuildDir || BuildDir != M->Directory) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_imported_module_relocated) << F.ModuleName << Blob << M->Directory->getName(); return OutOfDate; } } F.BaseDirectory = M->Directory->getName(); } else { F.BaseDirectory = Blob; } break; } case MODULE_MAP_FILE: if (ASTReadResult Result = ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) return Result; break; case INPUT_FILE_OFFSETS: NumInputs = Record[0]; NumUserInputs = Record[1]; F.InputFileOffsets = (const llvm::support::unaligned_uint64_t *)Blob.data(); F.InputFilesLoaded.resize(NumInputs); F.NumUserInputFiles = NumUserInputs; break; } } } ASTReader::ASTReadResult ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { BitstreamCursor &Stream = F.Stream; if (Stream.EnterSubBlock(AST_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } // Read all of the records and blocks for the AST file. RecordData Record; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: Error("error at end of module block in AST file"); return Failure; case llvm::BitstreamEntry::EndBlock: { // Outside of C++, we do not store a lookup map for the translation unit. // Instead, mark it as needing a lookup map to be built if this module // contains any declarations lexically within it (which it always does!). // This usually has no cost, since we very rarely need the lookup map for // the translation unit outside C++. if (ASTContext *Ctx = ContextObj) { DeclContext *DC = Ctx->getTranslationUnitDecl(); if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus) DC->setMustBuildLookupTable(); } return Success; } case llvm::BitstreamEntry::SubBlock: switch (Entry.ID) { case DECLTYPES_BLOCK_ID: // We lazily load the decls block, but we want to set up the // DeclsCursor cursor to point into it. Clone our current bitcode // cursor to it, enter the block and read the abbrevs in that block. // With the main cursor, we just skip over it. F.DeclsCursor = Stream; if (Stream.SkipBlock() || // Skip with the main cursor. // Read the abbrevs. ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } break; case PREPROCESSOR_BLOCK_ID: F.MacroCursor = Stream; if (!PP.getExternalSource()) PP.setExternalSource(this); if (Stream.SkipBlock() || ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) { Error("malformed block record in AST file"); return Failure; } F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); break; case PREPROCESSOR_DETAIL_BLOCK_ID: F.PreprocessorDetailCursor = Stream; if (Stream.SkipBlock() || ReadBlockAbbrevs(F.PreprocessorDetailCursor, PREPROCESSOR_DETAIL_BLOCK_ID)) { Error("malformed preprocessor detail record in AST file"); return Failure; } F.PreprocessorDetailStartOffset = F.PreprocessorDetailCursor.GetCurrentBitNo(); if (!PP.getPreprocessingRecord()) PP.createPreprocessingRecord(); if (!PP.getPreprocessingRecord()->getExternalSource()) PP.getPreprocessingRecord()->SetExternalSource(*this); break; case SOURCE_MANAGER_BLOCK_ID: if (ReadSourceManagerBlock(F)) return Failure; break; case SUBMODULE_BLOCK_ID: if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities)) return Result; break; case COMMENTS_BLOCK_ID: { BitstreamCursor C = Stream; if (Stream.SkipBlock() || ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) { Error("malformed comments block in AST file"); return Failure; } CommentsCursors.push_back(std::make_pair(C, &F)); break; } default: if (Stream.SkipBlock()) { Error("malformed block record in AST file"); return Failure; } break; } continue; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read and process a record. Record.clear(); StringRef Blob; auto RecordType = (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob); // If we're not loading an AST context, we don't care about most records. if (!ContextObj) { switch (RecordType) { case IDENTIFIER_TABLE: case IDENTIFIER_OFFSET: case INTERESTING_IDENTIFIERS: case STATISTICS: case PP_CONDITIONAL_STACK: case PP_COUNTER_VALUE: case SOURCE_LOCATION_OFFSETS: case MODULE_OFFSET_MAP: case SOURCE_MANAGER_LINE_TABLE: case SOURCE_LOCATION_PRELOADS: case PPD_ENTITIES_OFFSETS: case HEADER_SEARCH_TABLE: case IMPORTED_MODULES: case MACRO_OFFSET: break; default: continue; } } switch (RecordType) { default: // Default behavior: ignore. break; case TYPE_OFFSET: { if (F.LocalNumTypes != 0) { Error("duplicate TYPE_OFFSET record in AST file"); return Failure; } F.TypeOffsets = (const uint32_t *)Blob.data(); F.LocalNumTypes = Record[0]; unsigned LocalBaseTypeIndex = Record[1]; F.BaseTypeIndex = getTotalNumTypes(); if (F.LocalNumTypes > 0) { // Introduce the global -> local mapping for types within this module. GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F)); // Introduce the local -> global mapping for types within this module. F.TypeRemap.insertOrReplace( std::make_pair(LocalBaseTypeIndex, F.BaseTypeIndex - LocalBaseTypeIndex)); NumTypesLoaded += F.LocalNumTypes; } break; } case DECL_OFFSET: { if (F.LocalNumDecls != 0) { Error("duplicate DECL_OFFSET record in AST file"); return Failure; } F.DeclOffsets = (const DeclOffset *)Blob.data(); F.LocalNumDecls = Record[0]; unsigned LocalBaseDeclID = Record[1]; F.BaseDeclID = getTotalNumDecls(); if (F.LocalNumDecls > 0) { // Introduce the global -> local mapping for declarations within this // module. GlobalDeclMap.insert( std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F)); // Introduce the local -> global mapping for declarations within this // module. F.DeclRemap.insertOrReplace( std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID)); // Introduce the global -> local mapping for declarations within this // module. F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID; NumDeclsLoaded += F.LocalNumDecls; } break; } case TU_UPDATE_LEXICAL: { DeclContext *TU = ContextObj->getTranslationUnitDecl(); LexicalContents Contents( reinterpret_cast<const llvm::support::unaligned_uint32_t *>( Blob.data()), static_cast<unsigned int>(Blob.size() / 4)); TULexicalDecls.push_back(std::make_pair(&F, Contents)); TU->setHasExternalLexicalStorage(true); break; } case UPDATE_VISIBLE: { unsigned Idx = 0; serialization::DeclID ID = ReadDeclID(F, Record, Idx); auto *Data = (const unsigned char*)Blob.data(); PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data}); // If we've already loaded the decl, perform the updates when we finish // loading this block. if (Decl *D = GetExistingDecl(ID)) PendingUpdateRecords.push_back( PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); break; } case IDENTIFIER_TABLE: F.IdentifierTableData = Blob.data(); if (Record[0]) { F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( (const unsigned char *)F.IdentifierTableData + Record[0], (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t), (const unsigned char *)F.IdentifierTableData, ASTIdentifierLookupTrait(*this, F)); PP.getIdentifierTable().setExternalIdentifierLookup(this); } break; case IDENTIFIER_OFFSET: { if (F.LocalNumIdentifiers != 0) { Error("duplicate IDENTIFIER_OFFSET record in AST file"); return Failure; } F.IdentifierOffsets = (const uint32_t *)Blob.data(); F.LocalNumIdentifiers = Record[0]; unsigned LocalBaseIdentifierID = Record[1]; F.BaseIdentifierID = getTotalNumIdentifiers(); if (F.LocalNumIdentifiers > 0) { // Introduce the global -> local mapping for identifiers within this // module. GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1, &F)); // Introduce the local -> global mapping for identifiers within this // module. F.IdentifierRemap.insertOrReplace( std::make_pair(LocalBaseIdentifierID, F.BaseIdentifierID - LocalBaseIdentifierID)); IdentifiersLoaded.resize(IdentifiersLoaded.size() + F.LocalNumIdentifiers); } break; } case INTERESTING_IDENTIFIERS: F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end()); break; case EAGERLY_DESERIALIZED_DECLS: // FIXME: Skip reading this record if our ASTConsumer doesn't care // about "interesting" decls (for instance, if we're building a module). for (unsigned I = 0, N = Record.size(); I != N; ++I) EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); break; case MODULAR_CODEGEN_DECLS: // FIXME: Skip reading this record if our ASTConsumer doesn't care about // them (ie: if we're not codegenerating this module). if (F.Kind == MK_MainFile) for (unsigned I = 0, N = Record.size(); I != N; ++I) EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); break; case SPECIAL_TYPES: if (SpecialTypes.empty()) { for (unsigned I = 0, N = Record.size(); I != N; ++I) SpecialTypes.push_back(getGlobalTypeID(F, Record[I])); break; } if (SpecialTypes.size() != Record.size()) { Error("invalid special-types record"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; ++I) { serialization::TypeID ID = getGlobalTypeID(F, Record[I]); if (!SpecialTypes[I]) SpecialTypes[I] = ID; // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate // merge step? } break; case STATISTICS: TotalNumStatements += Record[0]; TotalNumMacros += Record[1]; TotalLexicalDeclContexts += Record[2]; TotalVisibleDeclContexts += Record[3]; break; case UNUSED_FILESCOPED_DECLS: for (unsigned I = 0, N = Record.size(); I != N; ++I) UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I])); break; case DELEGATING_CTORS: for (unsigned I = 0, N = Record.size(); I != N; ++I) DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I])); break; case WEAK_UNDECLARED_IDENTIFIERS: if (Record.size() % 4 != 0) { Error("invalid weak identifiers record"); return Failure; } // FIXME: Ignore weak undeclared identifiers from non-original PCH // files. This isn't the way to do it :) WeakUndeclaredIdentifiers.clear(); // Translate the weak, undeclared identifiers into global IDs. for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { WeakUndeclaredIdentifiers.push_back( getGlobalIdentifierID(F, Record[I++])); WeakUndeclaredIdentifiers.push_back( getGlobalIdentifierID(F, Record[I++])); WeakUndeclaredIdentifiers.push_back( ReadSourceLocation(F, Record, I).getRawEncoding()); WeakUndeclaredIdentifiers.push_back(Record[I++]); } break; case SELECTOR_OFFSETS: { F.SelectorOffsets = (const uint32_t *)Blob.data(); F.LocalNumSelectors = Record[0]; unsigned LocalBaseSelectorID = Record[1]; F.BaseSelectorID = getTotalNumSelectors(); if (F.LocalNumSelectors > 0) { // Introduce the global -> local mapping for selectors within this // module. GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F)); // Introduce the local -> global mapping for selectors within this // module. F.SelectorRemap.insertOrReplace( std::make_pair(LocalBaseSelectorID, F.BaseSelectorID - LocalBaseSelectorID)); SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); } break; } case METHOD_POOL: F.SelectorLookupTableData = (const unsigned char *)Blob.data(); if (Record[0]) F.SelectorLookupTable = ASTSelectorLookupTable::Create( F.SelectorLookupTableData + Record[0], F.SelectorLookupTableData, ASTSelectorLookupTrait(*this, F)); TotalNumMethodPoolEntries += Record[1]; break; case REFERENCED_SELECTOR_POOL: if (!Record.empty()) { for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { ReferencedSelectorsData.push_back(getGlobalSelectorID(F, Record[Idx++])); ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx). getRawEncoding()); } } break; case PP_CONDITIONAL_STACK: if (!Record.empty()) { SmallVector<PPConditionalInfo, 4> ConditionalStack; for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { auto Loc = ReadSourceLocation(F, Record, Idx); bool WasSkipping = Record[Idx++]; bool FoundNonSkip = Record[Idx++]; bool FoundElse = Record[Idx++]; ConditionalStack.push_back( {Loc, WasSkipping, FoundNonSkip, FoundElse}); } PP.setReplayablePreambleConditionalStack(ConditionalStack); } break; case PP_COUNTER_VALUE: if (!Record.empty() && Listener) Listener->ReadCounter(F, Record[0]); break; case FILE_SORTED_DECLS: F.FileSortedDecls = (const DeclID *)Blob.data(); F.NumFileSortedDecls = Record[0]; break; case SOURCE_LOCATION_OFFSETS: { F.SLocEntryOffsets = (const uint32_t *)Blob.data(); F.LocalNumSLocEntries = Record[0]; unsigned SLocSpaceSize = Record[1]; std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, SLocSpaceSize); if (!F.SLocEntryBaseID) { Error("ran out of source locations"); break; } // Make our entry in the range map. BaseID is negative and growing, so // we invert it. Because we invert it, though, we need the other end of // the range. unsigned RangeStart = unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0); GlobalSLocOffsetMap.insert( std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset - SLocSpaceSize,&F)); // Initialize the remapping table. // Invalid stays invalid. F.SLocRemap.insertOrReplace(std::make_pair(0U, 0)); // This module. Base was 2 when being compiled. F.SLocRemap.insertOrReplace(std::make_pair(2U, static_cast<int>(F.SLocEntryBaseOffset - 2))); TotalNumSLocEntries += F.LocalNumSLocEntries; break; } case MODULE_OFFSET_MAP: F.ModuleOffsetMap = Blob; break; case SOURCE_MANAGER_LINE_TABLE: if (ParseLineTable(F, Record)) return Failure; break; case SOURCE_LOCATION_PRELOADS: { // Need to transform from the local view (1-based IDs) to the global view, // which is based off F.SLocEntryBaseID. if (!F.PreloadSLocEntries.empty()) { Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file"); return Failure; } F.PreloadSLocEntries.swap(Record); break; } case EXT_VECTOR_DECLS: for (unsigned I = 0, N = Record.size(); I != N; ++I) ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I])); break; case VTABLE_USES: if (Record.size() % 3 != 0) { Error("Invalid VTABLE_USES record"); return Failure; } // Later tables overwrite earlier ones. // FIXME: Modules will have some trouble with this. This is clearly not // the right way to do this. VTableUses.clear(); for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { VTableUses.push_back(getGlobalDeclID(F, Record[Idx++])); VTableUses.push_back( ReadSourceLocation(F, Record, Idx).getRawEncoding()); VTableUses.push_back(Record[Idx++]); } break; case PENDING_IMPLICIT_INSTANTIATIONS: if (PendingInstantiations.size() % 2 != 0) { Error("Invalid existing PendingInstantiations"); return Failure; } if (Record.size() % 2 != 0) { Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++])); PendingInstantiations.push_back( ReadSourceLocation(F, Record, I).getRawEncoding()); } break; case SEMA_DECL_REFS: if (Record.size() != 3) { Error("Invalid SEMA_DECL_REFS block"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; ++I) SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I])); break; case PPD_ENTITIES_OFFSETS: { F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); assert(Blob.size() % sizeof(PPEntityOffset) == 0); F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); unsigned LocalBasePreprocessedEntityID = Record[0]; unsigned StartingID; if (!PP.getPreprocessingRecord()) PP.createPreprocessingRecord(); if (!PP.getPreprocessingRecord()->getExternalSource()) PP.getPreprocessingRecord()->SetExternalSource(*this); StartingID = PP.getPreprocessingRecord() ->allocateLoadedEntities(F.NumPreprocessedEntities); F.BasePreprocessedEntityID = StartingID; if (F.NumPreprocessedEntities > 0) { // Introduce the global -> local mapping for preprocessed entities in // this module. GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F)); // Introduce the local -> global mapping for preprocessed entities in // this module. F.PreprocessedEntityRemap.insertOrReplace( std::make_pair(LocalBasePreprocessedEntityID, F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); } break; } case DECL_UPDATE_OFFSETS: { if (Record.size() % 2 != 0) { Error("invalid DECL_UPDATE_OFFSETS block in AST file"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; I += 2) { GlobalDeclID ID = getGlobalDeclID(F, Record[I]); DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1])); // If we've already loaded the decl, perform the updates when we finish // loading this block. if (Decl *D = GetExistingDecl(ID)) PendingUpdateRecords.push_back( PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); } break; } case OBJC_CATEGORIES_MAP: { if (F.LocalNumObjCCategoriesInMap != 0) { Error("duplicate OBJC_CATEGORIES_MAP record in AST file"); return Failure; } F.LocalNumObjCCategoriesInMap = Record[0]; F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); break; } case OBJC_CATEGORIES: F.ObjCCategories.swap(Record); break; case CUDA_SPECIAL_DECL_REFS: // Later tables overwrite earlier ones. // FIXME: Modules will have trouble with this. CUDASpecialDeclRefs.clear(); for (unsigned I = 0, N = Record.size(); I != N; ++I) CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I])); break; case HEADER_SEARCH_TABLE: { F.HeaderFileInfoTableData = Blob.data(); F.LocalNumHeaderFileInfos = Record[1]; if (Record[0]) { F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create( (const unsigned char *)F.HeaderFileInfoTableData + Record[0], (const unsigned char *)F.HeaderFileInfoTableData, HeaderFileInfoTrait(*this, F, &PP.getHeaderSearchInfo(), Blob.data() + Record[2])); PP.getHeaderSearchInfo().SetExternalSource(this); if (!PP.getHeaderSearchInfo().getExternalLookup()) PP.getHeaderSearchInfo().SetExternalLookup(this); } break; } case FP_PRAGMA_OPTIONS: // Later tables overwrite earlier ones. FPPragmaOptions.swap(Record); break; case OPENCL_EXTENSIONS: for (unsigned I = 0, E = Record.size(); I != E; ) { auto Name = ReadString(Record, I); auto &Opt = OpenCLExtensions.OptMap[Name]; Opt.Supported = Record[I++] != 0; Opt.Enabled = Record[I++] != 0; Opt.Avail = Record[I++]; Opt.Core = Record[I++]; } break; case OPENCL_EXTENSION_TYPES: for (unsigned I = 0, E = Record.size(); I != E;) { auto TypeID = static_cast<::TypeID>(Record[I++]); auto *Type = GetType(TypeID).getTypePtr(); auto NumExt = static_cast<unsigned>(Record[I++]); for (unsigned II = 0; II != NumExt; ++II) { auto Ext = ReadString(Record, I); OpenCLTypeExtMap[Type].insert(Ext); } } break; case OPENCL_EXTENSION_DECLS: for (unsigned I = 0, E = Record.size(); I != E;) { auto DeclID = static_cast<::DeclID>(Record[I++]); auto *Decl = GetDecl(DeclID); auto NumExt = static_cast<unsigned>(Record[I++]); for (unsigned II = 0; II != NumExt; ++II) { auto Ext = ReadString(Record, I); OpenCLDeclExtMap[Decl].insert(Ext); } } break; case TENTATIVE_DEFINITIONS: for (unsigned I = 0, N = Record.size(); I != N; ++I) TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I])); break; case KNOWN_NAMESPACES: for (unsigned I = 0, N = Record.size(); I != N; ++I) KnownNamespaces.push_back(getGlobalDeclID(F, Record[I])); break; case UNDEFINED_BUT_USED: if (UndefinedButUsed.size() % 2 != 0) { Error("Invalid existing UndefinedButUsed"); return Failure; } if (Record.size() % 2 != 0) { Error("invalid undefined-but-used record"); return Failure; } for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++])); UndefinedButUsed.push_back( ReadSourceLocation(F, Record, I).getRawEncoding()); } break; case DELETE_EXPRS_TO_ANALYZE: for (unsigned I = 0, N = Record.size(); I != N;) { DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++])); const uint64_t Count = Record[I++]; DelayedDeleteExprs.push_back(Count); for (uint64_t C = 0; C < Count; ++C) { DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding()); bool IsArrayForm = Record[I++] == 1; DelayedDeleteExprs.push_back(IsArrayForm); } } break; case IMPORTED_MODULES: { if (!F.isModule()) { // If we aren't loading a module (which has its own exports), make // all of the imported modules visible. // FIXME: Deal with macros-only imports. for (unsigned I = 0, N = Record.size(); I != N; /**/) { unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]); SourceLocation Loc = ReadSourceLocation(F, Record, I); if (GlobalID) { ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc)); if (DeserializationListener) DeserializationListener->ModuleImportRead(GlobalID, Loc); } } } break; } case MACRO_OFFSET: { if (F.LocalNumMacros != 0) { Error("duplicate MACRO_OFFSET record in AST file"); return Failure; } F.MacroOffsets = (const uint32_t *)Blob.data(); F.LocalNumMacros = Record[0]; unsigned LocalBaseMacroID = Record[1]; F.BaseMacroID = getTotalNumMacros(); if (F.LocalNumMacros > 0) { // Introduce the global -> local mapping for macros within this module. GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F)); // Introduce the local -> global mapping for macros within this module. F.MacroRemap.insertOrReplace( std::make_pair(LocalBaseMacroID, F.BaseMacroID - LocalBaseMacroID)); NumMacrosLoaded += F.LocalNumMacros; } break; } case LATE_PARSED_TEMPLATE: { LateParsedTemplates.append(Record.begin(), Record.end()); break; } case OPTIMIZE_PRAGMA_OPTIONS: if (Record.size() != 1) { Error("invalid pragma optimize record"); return Failure; } OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]); break; case MSSTRUCT_PRAGMA_OPTIONS: if (Record.size() != 1) { Error("invalid pragma ms_struct record"); return Failure; } PragmaMSStructState = Record[0]; break; case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: if (Record.size() != 2) { Error("invalid pragma ms_struct record"); return Failure; } PragmaMSPointersToMembersState = Record[0]; PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]); break; case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: for (unsigned I = 0, N = Record.size(); I != N; ++I) UnusedLocalTypedefNameCandidates.push_back( getGlobalDeclID(F, Record[I])); break; case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: if (Record.size() != 1) { Error("invalid cuda pragma options record"); return Failure; } ForceCUDAHostDeviceDepth = Record[0]; break; case PACK_PRAGMA_OPTIONS: { if (Record.size() < 3) { Error("invalid pragma pack record"); return Failure; } PragmaPackCurrentValue = Record[0]; PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]); unsigned NumStackEntries = Record[2]; unsigned Idx = 3; // Reset the stack when importing a new module. PragmaPackStack.clear(); for (unsigned I = 0; I < NumStackEntries; ++I) { PragmaPackStackEntry Entry; Entry.Value = Record[Idx++]; Entry.Location = ReadSourceLocation(F, Record[Idx++]); PragmaPackStrings.push_back(ReadString(Record, Idx)); Entry.SlotLabel = PragmaPackStrings.back(); PragmaPackStack.push_back(Entry); } break; } } } } void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { assert(!F.ModuleOffsetMap.empty() && "no module offset map to read"); // Additional remapping information. const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); F.ModuleOffsetMap = StringRef(); // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders. if (F.SLocRemap.find(0) == F.SLocRemap.end()) { F.SLocRemap.insert(std::make_pair(0U, 0)); F.SLocRemap.insert(std::make_pair(2U, 1)); } // Continuous range maps we may be updating in our module. typedef ContinuousRangeMap<uint32_t, int, 2>::Builder RemapBuilder; RemapBuilder SLocRemap(F.SLocRemap); RemapBuilder IdentifierRemap(F.IdentifierRemap); RemapBuilder MacroRemap(F.MacroRemap); RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); RemapBuilder SubmoduleRemap(F.SubmoduleRemap); RemapBuilder SelectorRemap(F.SelectorRemap); RemapBuilder DeclRemap(F.DeclRemap); RemapBuilder TypeRemap(F.TypeRemap); while (Data < DataEnd) { // FIXME: Looking up dependency modules by filename is horrible. using namespace llvm::support; uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data); StringRef Name = StringRef((const char*)Data, Len); Data += Len; ModuleFile *OM = ModuleMgr.lookup(Name); // Check if ModuleFile exists if (!OM) { StringRef ModuleName = llvm::sys::path::filename(Name); ModuleName.consume_back(".pcm"); clang::Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName, true, true); std::string Path; // If module definition exists in modulemap, search the modulepath in HeaderSearchInfo if (M) Path = PP.getHeaderSearchInfo().getModuleFileName(M->Name, PP.getHeaderSearchInfo().getModuleMap().getModuleMapFileForUniquing(M)->getName(), true); StringRef NewName = StringRef(Path); OM = ModuleMgr.lookup(NewName); if (!OM) { std::string Msg = "SourceLocation remap refers to unknown module, cannot find "; Msg.append(std::string(NewName)); Error(Msg); return; } } uint32_t SLocOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t IdentifierIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t MacroIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t PreprocessedEntityIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t SubmoduleIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t SelectorIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t DeclIDOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t TypeIndexOffset = endian::readNext<uint32_t, little, unaligned>(Data); uint32_t None = std::numeric_limits<uint32_t>::max(); auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, RemapBuilder &Remap) { if (Offset != None) Remap.insert(std::make_pair(Offset, static_cast<int>(BaseOffset - Offset))); }; mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap); mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap); mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, PreprocessedEntityRemap); mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap); mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap); // Global -> local mappings. F.GlobalToLocalDeclIDs[OM] = DeclIDOffset; } } ASTReader::ASTReadResult ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, const ModuleFile *ImportedBy, unsigned ClientLoadCapabilities) { unsigned Idx = 0; F.ModuleMapPath = ReadPath(F, Record, Idx); // Try to resolve ModuleName in the current header search context and // verify that it is found in the same module map file as we saved. If the // top-level AST file is a main file, skip this check because there is no // usable header search context. assert(!F.ModuleName.empty() && "MODULE_NAME should come before MODULE_MAP_FILE"); if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { // An implicitly-loaded module file should have its module listed in some // module map file that we've already loaded. Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); auto &Map = PP.getHeaderSearchInfo().getModuleMap(); const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr; // Don't emit module relocation error if we have -fno-validate-pch if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) { assert(ImportedBy && "top-level import should be verified"); if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) { if (auto *ASTFE = M ? M->getASTFile() : nullptr) // This module was defined by an imported (explicit) module. Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName << ASTFE->getName(); else // This module was built with a different module map. Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName << ImportedBy->FileName << F.ModuleMapPath; } return OutOfDate; } assert(M->Name == F.ModuleName && "found module with different name"); // Check the primary module map file. const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath); if (!PP.getPreprocessorOpts().DisablePCHValidation && (StoredModMap == nullptr || StoredModMap != ModMap)) { assert(ModMap && "found module is missing module map file"); assert(ImportedBy && "top-level import should be verified"); if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_imported_module_modmap_changed) << F.ModuleName << ImportedBy->FileName << ModMap->getName() << F.ModuleMapPath; return OutOfDate; } llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps; for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { // FIXME: we should use input files rather than storing names. std::string Filename = ReadPath(F, Record, Idx); const FileEntry *F = FileMgr.getFile(Filename, false, false); if (F == nullptr) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Error("could not find file '" + Filename +"' referenced by AST file"); return OutOfDate; } AdditionalStoredMaps.insert(F); } // Check any additional module map files (e.g. module.private.modulemap) // that are not in the pcm. if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { for (const FileEntry *ModMap : *AdditionalModuleMaps) { // Remove files that match // Note: SmallPtrSet::erase is really remove if (!AdditionalStoredMaps.erase(ModMap)) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_module_different_modmap) << F.ModuleName << /*new*/0 << ModMap->getName(); return OutOfDate; } } } // Check any additional module map files that are in the pcm, but not // found in header search. Cases that match are already removed. for (const FileEntry *ModMap : AdditionalStoredMaps) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_module_different_modmap) << F.ModuleName << /*not new*/1 << ModMap->getName(); return OutOfDate; } } if (Listener) Listener->ReadModuleMapFile(F.ModuleMapPath); return Success; } /// \brief Move the given method to the back of the global list of methods. static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { // Find the entry for this selector in the method pool. Sema::GlobalMethodPool::iterator Known = S.MethodPool.find(Method->getSelector()); if (Known == S.MethodPool.end()) return; // Retrieve the appropriate method list. ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first : Known->second.second; bool Found = false; for (ObjCMethodList *List = &Start; List; List = List->getNext()) { if (!Found) { if (List->getMethod() == Method) { Found = true; } else { // Keep searching. continue; } } if (List->getNext()) List->setMethod(List->getNext()->getMethod()); else List->setMethod(Method); } } void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?"); for (Decl *D : Names) { bool wasHidden = D->isHidden(); D->setVisibleDespiteOwningModule(); if (wasHidden && SemaObj) { if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) { moveMethodToBackOfGlobalList(*SemaObj, Method); } } } } void ASTReader::makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc) { llvm::SmallPtrSet<Module *, 4> Visited; SmallVector<Module *, 4> Stack; Stack.push_back(Mod); while (!Stack.empty()) { Mod = Stack.pop_back_val(); if (NameVisibility <= Mod->NameVisibility) { // This module already has this level of visibility (or greater), so // there is nothing more to do. continue; } if (!Mod->isAvailable()) { // Modules that aren't available cannot be made visible. continue; } // Update the module's name visibility. Mod->NameVisibility = NameVisibility; // If we've already deserialized any names from this module, // mark them as visible. HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod); if (Hidden != HiddenNamesMap.end()) { auto HiddenNames = std::move(*Hidden); HiddenNamesMap.erase(Hidden); makeNamesVisible(HiddenNames.second, HiddenNames.first); assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() && "making names visible added hidden names"); } // Push any exported modules onto the stack to be marked as visible. SmallVector<Module *, 16> Exports; Mod->getExportedModules(Exports); for (SmallVectorImpl<Module *>::iterator I = Exports.begin(), E = Exports.end(); I != E; ++I) { Module *Exported = *I; if (Visited.insert(Exported).second) Stack.push_back(Exported); } } } /// We've merged the definition \p MergedDef into the existing definition /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made /// visible. void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef) { // FIXME: This doesn't correctly handle the case where MergedDef is visible // in modules other than its owning module. We should instead give the // ASTContext a list of merged definitions for Def. if (Def->isHidden()) { // If MergedDef is visible or becomes visible, make the definition visible. if (!MergedDef->isHidden()) Def->setVisibleDespiteOwningModule(); else if (getContext().getLangOpts().ModulesLocalVisibility) { getContext().mergeDefinitionIntoModule( Def, MergedDef->getImportedOwningModule(), /*NotifyListeners*/ false); PendingMergedDefinitionsToDeduplicate.insert(Def); } else { auto SubmoduleID = MergedDef->getOwningModuleID(); assert(SubmoduleID && "hidden definition in no module"); HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def); } } } bool ASTReader::loadGlobalIndex() { if (GlobalIndex) return false; if (TriedLoadingGlobalIndex || !UseGlobalIndex || !PP.getLangOpts().Modules) return true; // Try to load the global index. TriedLoadingGlobalIndex = true; StringRef ModuleCachePath = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result = GlobalModuleIndex::readIndex(ModuleCachePath); if (!Result.first) return true; GlobalIndex.reset(Result.first); ModuleMgr.setGlobalIndex(GlobalIndex.get()); return false; } bool ASTReader::isGlobalIndexUnavailable() const { return PP.getLangOpts().Modules && UseGlobalIndex && !hasGlobalIndex() && TriedLoadingGlobalIndex; } static void updateModuleTimestamp(ModuleFile &MF) { // Overwrite the timestamp file contents so that file's mtime changes. std::string TimestampFilename = MF.getTimestampFilename(); std::error_code EC; llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text); if (EC) return; OS << "Timestamp file\n"; OS.close(); OS.clear_error(); // Avoid triggering a fatal error. } /// \brief Given a cursor at the start of an AST file, scan ahead and drop the /// cursor into the start of the given block ID, returning false on success and /// true on failure. static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { while (true) { llvm::BitstreamEntry Entry = Cursor.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: case llvm::BitstreamEntry::EndBlock: return true; case llvm::BitstreamEntry::Record: // Ignore top-level records. Cursor.skipRecord(Entry.ID); break; case llvm::BitstreamEntry::SubBlock: if (Entry.ID == BlockID) { if (Cursor.EnterSubBlock(BlockID)) return true; // Found it! return false; } if (Cursor.SkipBlock()) return true; } } } ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, SmallVectorImpl<ImportedSubmodule> *Imported) { llvm::SaveAndRestore<SourceLocation> SetCurImportLocRAII(CurrentImportLoc, ImportLoc); // Defer any pending actions until we get to the end of reading the AST file. Deserializing AnASTFile(this); // Bump the generation number. unsigned PreviousGeneration = 0; if (ContextObj) PreviousGeneration = incrementGeneration(*ContextObj); unsigned NumModules = ModuleMgr.size(); SmallVector<ImportedModule, 4> Loaded; switch (ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc, /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(), ClientLoadCapabilities)) { case Failure: case Missing: case OutOfDate: case VersionMismatch: case ConfigurationMismatch: case HadErrors: { llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet; for (const ImportedModule &IM : Loaded) LoadedSet.insert(IM.Mod); ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet, PP.getLangOpts().Modules ? &PP.getHeaderSearchInfo().getModuleMap() : nullptr); // If we find that any modules are unusable, the global index is going // to be out-of-date. Just remove it. GlobalIndex.reset(); ModuleMgr.setGlobalIndex(nullptr); return ReadResult; } case Success: break; } // Here comes stuff that we only do once the entire chain is loaded. // Load the AST blocks of all of the modules that we loaded. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(), MEnd = Loaded.end(); M != MEnd; ++M) { ModuleFile &F = *M->Mod; // Read the AST block. if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities)) return Result; // Read the extension blocks. while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) { if (ASTReadResult Result = ReadExtensionBlock(F)) return Result; } // Once read, set the ModuleFile bit base offset and update the size in // bits of all files we've seen. F.GlobalBitOffset = TotalModulesSizeInBits; TotalModulesSizeInBits += F.SizeInBits; GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F)); // Preload SLocEntries. for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) { int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID; // Load it through the SourceManager and don't call ReadSLocEntry() // directly because the entry may have already been loaded in which case // calling ReadSLocEntry() directly would trigger an assertion in // SourceManager. SourceMgr.getLoadedSLocEntryByID(Index); } // Map the original source file ID into the ID space of the current // compilation. if (F.OriginalSourceFileID.isValid()) { F.OriginalSourceFileID = FileID::get( F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1); } // Preload all the pending interesting identifiers by marking them out of // date. for (auto Offset : F.PreloadIdentifierOffsets) { const unsigned char *Data = reinterpret_cast<const unsigned char *>( F.IdentifierTableData + Offset); ASTIdentifierLookupTrait Trait(*this, F); auto KeyDataLen = Trait.ReadKeyDataLength(Data); auto Key = Trait.ReadKey(Data, KeyDataLen.first); auto &II = PP.getIdentifierTable().getOwn(Key); II.setOutOfDate(true); // Mark this identifier as being from an AST file so that we can track // whether we need to serialize it. markIdentifierFromAST(*this, II); // Associate the ID with the identifier so that the writer can reuse it. auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first); SetIdentifierInfo(ID, &II); } } // Setup the import locations and notify the module manager that we've // committed to these module files. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(), MEnd = Loaded.end(); M != MEnd; ++M) { ModuleFile &F = *M->Mod; ModuleMgr.moduleFileAccepted(&F); // Set the import location. F.DirectImportLoc = ImportLoc; // FIXME: We assume that locations from PCH / preamble do not need // any translation. if (!M->ImportedBy) F.ImportLoc = M->ImportLoc; else F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc); } if (!PP.getLangOpts().CPlusPlus || (Type != MK_ImplicitModule && Type != MK_ExplicitModule && Type != MK_PrebuiltModule)) { // Mark all of the identifiers in the identifier table as being out of date, // so that various accessors know to check the loaded modules when the // identifier is used. // // For C++ modules, we don't need information on many identifiers (just // those that provide macros or are poisoned), so we mark all of // the interesting ones via PreloadIdentifierOffsets. for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(), IdEnd = PP.getIdentifierTable().end(); Id != IdEnd; ++Id) Id->second->setOutOfDate(true); } // Mark selectors as out of date. for (auto Sel : SelectorGeneration) SelectorOutOfDate[Sel.first] = true; // Resolve any unresolved module exports. for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID); Module *ResolvedMod = getSubmodule(GlobalID); switch (Unresolved.Kind) { case UnresolvedModuleRef::Conflict: if (ResolvedMod) { Module::Conflict Conflict; Conflict.Other = ResolvedMod; Conflict.Message = Unresolved.String.str(); Unresolved.Mod->Conflicts.push_back(Conflict); } continue; case UnresolvedModuleRef::Import: if (ResolvedMod) Unresolved.Mod->Imports.insert(ResolvedMod); continue; case UnresolvedModuleRef::Export: if (ResolvedMod || Unresolved.IsWildcard) Unresolved.Mod->Exports.push_back( Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); continue; } } UnresolvedModuleRefs.clear(); if (Imported) Imported->append(ImportedModules.begin(), ImportedModules.end()); // FIXME: How do we load the 'use'd modules? They may not be submodules. // Might be unnecessary as use declarations are only used to build the // module itself. if (ContextObj) InitializeContext(); if (SemaObj) UpdateSema(); if (DeserializationListener) DeserializationListener->ReaderInitialized(this); ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); if (PrimaryModule.OriginalSourceFileID.isValid()) { // If this AST file is a precompiled preamble, then set the // preamble file ID of the source manager to the file source file // from which the preamble was built. if (Type == MK_Preamble) { SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); } else if (Type == MK_MainFile) { SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); } } // For any Objective-C class definitions we have already loaded, make sure // that we load any additional categories. if (ContextObj) { for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), ObjCClassesLoaded[I], PreviousGeneration); } } if (PP.getHeaderSearchInfo() .getHeaderSearchOpts() .ModulesValidateOncePerBuildSession) { // Now we are certain that the module and all modules it depends on are // up to date. Create or update timestamp files for modules that are // located in the module cache (not for PCH files that could be anywhere // in the filesystem). for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { ImportedModule &M = Loaded[I]; if (M.Mod->Kind == MK_ImplicitModule) { updateModuleTimestamp(*M.Mod); } } } return Success; } static ASTFileSignature readASTFileSignature(StringRef PCH); /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'. static bool startsWithASTFileMagic(BitstreamCursor &Stream) { return Stream.canSkipToPos(4) && Stream.Read(8) == 'C' && Stream.Read(8) == 'P' && Stream.Read(8) == 'C' && Stream.Read(8) == 'H'; } static unsigned moduleKindForDiagnostic(ModuleKind Kind) { switch (Kind) { case MK_PCH: return 0; // PCH case MK_ImplicitModule: case MK_ExplicitModule: case MK_PrebuiltModule: return 1; // module case MK_MainFile: case MK_Preamble: return 2; // main source file } llvm_unreachable("unknown module kind"); } ASTReader::ASTReadResult ASTReader::ReadASTCore(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities) { ModuleFile *M; std::string ErrorStr; ModuleManager::AddModuleResult AddResult = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, getGenerationOrNull(), ExpectedSize, ExpectedModTime, ExpectedSignature, readASTFileSignature, M, ErrorStr); switch (AddResult) { case ModuleManager::AlreadyLoaded: return Success; case ModuleManager::NewlyLoaded: // Load module file below. break; case ModuleManager::Missing: // The module file was missing; if the client can handle that, return // it. if (ClientLoadCapabilities & ARR_Missing) return Missing; // Otherwise, return an error. Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() << ErrorStr; return Failure; case ModuleManager::OutOfDate: // We couldn't load the module file because it is out-of-date. If the // client can handle out-of-date, return it. if (ClientLoadCapabilities & ARR_OutOfDate) return OutOfDate; // Otherwise, return an error. Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() << ErrorStr; return Failure; } assert(M && "Missing module file"); // FIXME: This seems rather a hack. Should CurrentDir be part of the // module? if (FileName != "-") { CurrentDir = llvm::sys::path::parent_path(FileName); if (CurrentDir.empty()) CurrentDir = "."; } ModuleFile &F = *M; BitstreamCursor &Stream = F.Stream; Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer)); F.SizeInBits = F.Buffer->getBufferSize() * 8; // Sniff for the signature. if (!startsWithASTFileMagic(Stream)) { Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type) << FileName; return Failure; } // This is used for compatibility with older PCH formats. bool HaveReadControlBlock = false; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: case llvm::BitstreamEntry::Record: case llvm::BitstreamEntry::EndBlock: Error("invalid record at top-level of AST file"); return Failure; case llvm::BitstreamEntry::SubBlock: break; } switch (Entry.ID) { case CONTROL_BLOCK_ID: HaveReadControlBlock = true; switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { case Success: // Check that we didn't try to load a non-module AST file as a module. // // FIXME: Should we also perform the converse check? Loading a module as // a PCH file sort of works, but it's a bit wonky. if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || Type == MK_PrebuiltModule) && F.ModuleName.empty()) { auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; if (Result != OutOfDate || (ClientLoadCapabilities & ARR_OutOfDate) == 0) Diag(diag::err_module_file_not_module) << FileName; return Result; } break; case Failure: return Failure; case Missing: return Missing; case OutOfDate: return OutOfDate; case VersionMismatch: return VersionMismatch; case ConfigurationMismatch: return ConfigurationMismatch; case HadErrors: return HadErrors; } break; case AST_BLOCK_ID: if (!HaveReadControlBlock) { if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) Diag(diag::err_pch_version_too_old); return VersionMismatch; } // Record that we've loaded this module. Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc)); return Success; case UNHASHED_CONTROL_BLOCK_ID: // This block is handled using look-ahead during ReadControlBlock. We // shouldn't get here! Error("malformed block record in AST file"); return Failure; default: if (Stream.SkipBlock()) { Error("malformed block record in AST file"); return Failure; } break; } } return Success; } ASTReader::ASTReadResult ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, unsigned ClientLoadCapabilities) { const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; ASTReadResult Result = readUnhashedControlBlockImpl( &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, Listener.get(), WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); // If F was directly imported by another module, it's implicitly validated by // the importing module. if (DisableValidation || WasImportedBy || (AllowConfigurationMismatch && Result == ConfigurationMismatch)) return Success; if (Result == Failure) { Error("malformed block record in AST file"); return Failure; } if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { // If this module has already been finalized in the PCMCache, we're stuck // with it; we can only load a single version of each module. // // This can happen when a module is imported in two contexts: in one, as a // user module; in another, as a system module (due to an import from // another module marked with the [system] flag). It usually indicates a // bug in the module map: this module should also be marked with [system]. // // If -Wno-system-headers (the default), and the first import is as a // system module, then validation will fail during the as-user import, // since -Werror flags won't have been validated. However, it's reasonable // to treat this consistently as a system module. // // If -Wsystem-headers, the PCM on disk was built with // -Wno-system-headers, and the first import is as a user module, then // validation will fail during the as-system import since the PCM on disk // doesn't guarantee that -Werror was respected. However, the -Werror // flags were checked during the initial as-user import. if (PCMCache.isBufferFinal(F.FileName)) { Diag(diag::warn_module_system_bit_conflict) << F.FileName; return Success; } } return Result; } ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener, bool ValidateDiagnosticOptions) { // Initialize a stream. BitstreamCursor Stream(StreamData); // Sniff for the signature. if (!startsWithASTFileMagic(Stream)) return Failure; // Scan for the UNHASHED_CONTROL_BLOCK_ID block. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) return Failure; // Read all of the records in the options block. RecordData Record; ASTReadResult Result = Success; while (1) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::Error: case llvm::BitstreamEntry::SubBlock: return Failure; case llvm::BitstreamEntry::EndBlock: return Result; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read and process a record. Record.clear(); switch ( (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) { case SIGNATURE: { if (F) std::copy(Record.begin(), Record.end(), F->Signature.data()); break; } case DIAGNOSTIC_OPTIONS: { bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; if (Listener && ValidateDiagnosticOptions && !AllowCompatibleConfigurationMismatch && ParseDiagnosticOptions(Record, Complain, *Listener)) Result = OutOfDate; // Don't return early. Read the signature. break; } case DIAG_PRAGMA_MAPPINGS: if (!F) break; if (F->PragmaDiagMappings.empty()) F->PragmaDiagMappings.swap(Record); else F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(), Record.begin(), Record.end()); break; } } } /// Parse a record and blob containing module file extension metadata. static bool parseModuleFileExtensionMetadata( const SmallVectorImpl<uint64_t> &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata) { if (Record.size() < 4) return true; Metadata.MajorVersion = Record[0]; Metadata.MinorVersion = Record[1]; unsigned BlockNameLen = Record[2]; unsigned UserInfoLen = Record[3]; if (BlockNameLen + UserInfoLen > Blob.size()) return true; Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, Blob.data() + BlockNameLen + UserInfoLen); return false; } ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) { BitstreamCursor &Stream = F.Stream; RecordData Record; while (true) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: if (Stream.SkipBlock()) return Failure; continue; case llvm::BitstreamEntry::EndBlock: return Success; case llvm::BitstreamEntry::Error: return HadErrors; case llvm::BitstreamEntry::Record: break; } Record.clear(); StringRef Blob; unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); switch (RecCode) { case EXTENSION_METADATA: { ModuleFileExtensionMetadata Metadata; if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) return Failure; // Find a module file extension with this block name. auto Known = ModuleFileExtensions.find(Metadata.BlockName); if (Known == ModuleFileExtensions.end()) break; // Form a reader. if (auto Reader = Known->second->createExtensionReader(Metadata, *this, F, Stream)) { F.ExtensionReaders.push_back(std::move(Reader)); } break; } } } return Success; } void ASTReader::InitializeContext() { assert(ContextObj && "no context to initialize"); ASTContext &Context = *ContextObj; // If there's a listener, notify them that we "read" the translation unit. if (DeserializationListener) DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, Context.getTranslationUnitDecl()); // FIXME: Find a better way to deal with collisions between these // built-in types. Right now, we just ignore the problem. // Load the special types. if (SpecialTypes.size() >= NumSpecialTypeIDs) { if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { if (!Context.CFConstantStringTypeDecl) Context.setCFConstantStringType(GetType(String)); } if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) { QualType FileType = GetType(File); if (FileType.isNull()) { Error("FILE type is NULL"); return; } if (!Context.FILEDecl) { if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) Context.setFILEDecl(Typedef->getDecl()); else { const TagType *Tag = FileType->getAs<TagType>(); if (!Tag) { Error("Invalid FILE type in AST file"); return; } Context.setFILEDecl(Tag->getDecl()); } } } if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { QualType Jmp_bufType = GetType(Jmp_buf); if (Jmp_bufType.isNull()) { Error("jmp_buf type is NULL"); return; } if (!Context.jmp_bufDecl) { if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) Context.setjmp_bufDecl(Typedef->getDecl()); else { const TagType *Tag = Jmp_bufType->getAs<TagType>(); if (!Tag) { Error("Invalid jmp_buf type in AST file"); return; } Context.setjmp_bufDecl(Tag->getDecl()); } } } if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { QualType Sigjmp_bufType = GetType(Sigjmp_buf); if (Sigjmp_bufType.isNull()) { Error("sigjmp_buf type is NULL"); return; } if (!Context.sigjmp_bufDecl) { if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) Context.setsigjmp_bufDecl(Typedef->getDecl()); else { const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); assert(Tag && "Invalid sigjmp_buf type in AST file"); Context.setsigjmp_bufDecl(Tag->getDecl()); } } } if (unsigned ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { if (Context.ObjCIdRedefinitionType.isNull()) Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef); } if (unsigned ObjCClassRedef = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { if (Context.ObjCClassRedefinitionType.isNull()) Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef); } if (unsigned ObjCSelRedef = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { if (Context.ObjCSelRedefinitionType.isNull()) Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef); } if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { QualType Ucontext_tType = GetType(Ucontext_t); if (Ucontext_tType.isNull()) { Error("ucontext_t type is NULL"); return; } if (!Context.ucontext_tDecl) { if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) Context.setucontext_tDecl(Typedef->getDecl()); else { const TagType *Tag = Ucontext_tType->getAs<TagType>(); assert(Tag && "Invalid ucontext_t type in AST file"); Context.setucontext_tDecl(Tag->getDecl()); } } } } ReadPragmaDiagnosticMappings(Context.getDiagnostics()); // If there were any CUDA special declarations, deserialize them. if (!CUDASpecialDeclRefs.empty()) { assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); Context.setcudaConfigureCallDecl( cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); } // Re-export any modules that were imported by a non-module AST file. // FIXME: This does not make macro-only imports visible again. for (auto &Import : ImportedModules) { if (Module *Imported = getSubmodule(Import.ID)) { makeModuleVisible(Imported, Module::AllVisible, /*ImportLoc=*/Import.ImportLoc); if (Import.ImportLoc.isValid()) PP.makeModuleVisible(Imported, Import.ImportLoc); // FIXME: should we tell Sema to make the module visible too? } } ImportedModules.clear(); } void ASTReader::finalizeForWriting() { // Nothing to do for now. } /// \brief Reads and return the signature record from \p PCH's control block, or /// else returns 0. static ASTFileSignature readASTFileSignature(StringRef PCH) { BitstreamCursor Stream(PCH); if (!startsWithASTFileMagic(Stream)) return ASTFileSignature(); // Scan for the UNHASHED_CONTROL_BLOCK_ID block. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) return ASTFileSignature(); // Scan for SIGNATURE inside the diagnostic options block. ASTReader::RecordData Record; while (true) { llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); if (Entry.Kind != llvm::BitstreamEntry::Record) return ASTFileSignature(); Record.clear(); StringRef Blob; if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob)) return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2], (uint32_t)Record[3], (uint32_t)Record[4]}}}; } } /// \brief Retrieve the name of the original source file name /// directly from the AST file, without actually loading the AST /// file. std::string ASTReader::getOriginalSourceFile( const std::string &ASTFileName, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { // Open the AST file. auto Buffer = FileMgr.getBufferForFile(ASTFileName); if (!Buffer) { Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << Buffer.getError().message(); return std::string(); } // Initialize the stream BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer)); // Sniff for the signature. if (!startsWithASTFileMagic(Stream)) { Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName; return std::string(); } // Scan for the CONTROL_BLOCK_ID block. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) { Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; return std::string(); } // Scan for ORIGINAL_FILE inside the control block. RecordData Record; while (true) { llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); if (Entry.Kind == llvm::BitstreamEntry::EndBlock) return std::string(); if (Entry.Kind != llvm::BitstreamEntry::Record) { Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; return std::string(); } Record.clear(); StringRef Blob; if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE) return Blob.str(); } } namespace { class SimplePCHValidator : public ASTReaderListener { const LangOptions &ExistingLangOpts; const TargetOptions &ExistingTargetOpts; const PreprocessorOptions &ExistingPPOpts; std::string ExistingModuleCachePath; FileManager &FileMgr; public: SimplePCHValidator(const LangOptions &ExistingLangOpts, const TargetOptions &ExistingTargetOpts, const PreprocessorOptions &ExistingPPOpts, StringRef ExistingModuleCachePath, FileManager &FileMgr) : ExistingLangOpts(ExistingLangOpts), ExistingTargetOpts(ExistingTargetOpts), ExistingPPOpts(ExistingPPOpts), ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) { } bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override { return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr, AllowCompatibleDifferences); } bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override { return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr, AllowCompatibleDifferences); } bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override { return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, ExistingModuleCachePath, nullptr, ExistingLangOpts); } bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override { return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr, SuggestedPredefines, ExistingLangOpts); } }; } // end anonymous namespace bool ASTReader::readASTFileControlBlock( StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions) { // Open the AST file. // FIXME: This allows use of the VFS; we do not allow use of the // VFS when actually loading a module. auto Buffer = FileMgr.getBufferForFile(Filename); if (!Buffer) { return true; } // Initialize the stream StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer); BitstreamCursor Stream(Bytes); // Sniff for the signature. if (!startsWithASTFileMagic(Stream)) return true; // Scan for the CONTROL_BLOCK_ID block. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) return true; bool NeedsInputFiles = Listener.needsInputFileVisitation(); bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); bool NeedsImports = Listener.needsImportVisitation(); BitstreamCursor InputFilesCursor; RecordData Record; std::string ModuleDir; bool DoneWithControlBlock = false; while (!DoneWithControlBlock) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: { switch (Entry.ID) { case OPTIONS_BLOCK_ID: { std::string IgnoredSuggestedPredefines; if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate, /*AllowCompatibleConfigurationMismatch*/ false, Listener, IgnoredSuggestedPredefines) != Success) return true; break; } case INPUT_FILES_BLOCK_ID: InputFilesCursor = Stream; if (Stream.SkipBlock() || (NeedsInputFiles && ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))) return true; break; default: if (Stream.SkipBlock()) return true; break; } continue; } case llvm::BitstreamEntry::EndBlock: DoneWithControlBlock = true; break; case llvm::BitstreamEntry::Error: return true; case llvm::BitstreamEntry::Record: break; } if (DoneWithControlBlock) break; Record.clear(); StringRef Blob; unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); switch ((ControlRecordTypes)RecCode) { case METADATA: { if (Record[0] != VERSION_MAJOR) return true; if (Listener.ReadFullVersionInformation(Blob)) return true; break; } case MODULE_NAME: Listener.ReadModuleName(Blob); break; case MODULE_DIRECTORY: ModuleDir = Blob; break; case MODULE_MAP_FILE: { unsigned Idx = 0; auto Path = ReadString(Record, Idx); ResolveImportedPath(Path, ModuleDir); Listener.ReadModuleMapFile(Path); break; } case INPUT_FILE_OFFSETS: { if (!NeedsInputFiles) break; unsigned NumInputFiles = Record[0]; unsigned NumUserFiles = Record[1]; const uint64_t *InputFileOffs = (const uint64_t *)Blob.data(); for (unsigned I = 0; I != NumInputFiles; ++I) { // Go find this input file. bool isSystemFile = I >= NumUserFiles; if (isSystemFile && !NeedsSystemInputFiles) break; // the rest are system input files BitstreamCursor &Cursor = InputFilesCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(InputFileOffs[I]); unsigned Code = Cursor.ReadCode(); RecordData Record; StringRef Blob; bool shouldContinue = false; switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) { case INPUT_FILE: bool Overridden = static_cast<bool>(Record[3]); std::string Filename = Blob; ResolveImportedPath(Filename, ModuleDir); shouldContinue = Listener.visitInputFile( Filename, isSystemFile, Overridden, /*IsExplicitModule*/false); break; } if (!shouldContinue) break; } break; } case IMPORTS: { if (!NeedsImports) break; unsigned Idx = 0, N = Record.size(); while (Idx < N) { // Read information about the AST file. Idx += 5; // ImportLoc, Size, ModTime, Signature std::string Filename = ReadString(Record, Idx); ResolveImportedPath(Filename, ModuleDir); Listener.visitImport(Filename); } break; } default: // No other validation to perform. break; } } // Look for module file extension blocks, if requested. if (FindModuleFileExtensions) { BitstreamCursor SavedStream = Stream; while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) { bool DoneWithExtensionBlock = false; while (!DoneWithExtensionBlock) { llvm::BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: if (Stream.SkipBlock()) return true; continue; case llvm::BitstreamEntry::EndBlock: DoneWithExtensionBlock = true; continue; case llvm::BitstreamEntry::Error: return true; case llvm::BitstreamEntry::Record: break; } Record.clear(); StringRef Blob; unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); switch (RecCode) { case EXTENSION_METADATA: { ModuleFileExtensionMetadata Metadata; if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) return true; Listener.readModuleFileExtension(Metadata); break; } } } } Stream = SavedStream; } // Scan for the UNHASHED_CONTROL_BLOCK_ID block. if (readUnhashedControlBlockImpl( nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate, /*AllowCompatibleConfigurationMismatch*/ false, &Listener, ValidateDiagnosticOptions) != Success) return true; return false; } bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath) { SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, ExistingModuleCachePath, FileMgr); return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr, /*FindModuleFileExtensions=*/false, validator, /*ValidateDiagnosticOptions=*/true); } ASTReader::ASTReadResult ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { // Enter the submodule block. if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) { Error("malformed submodule block record in AST file"); return Failure; } ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); bool First = true; Module *CurrentModule = nullptr; Module::ModuleKind ModuleKind = Module::ModuleMapModule; RecordData Record; while (true) { llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return Failure; case llvm::BitstreamEntry::EndBlock: return Success; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read a record. StringRef Blob; Record.clear(); auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob); if ((Kind == SUBMODULE_METADATA) != First) { Error("submodule metadata record should be at beginning of block"); return Failure; } First = false; // Submodule information is only valid if we have a current module. // FIXME: Should we error on these cases? if (!CurrentModule && Kind != SUBMODULE_METADATA && Kind != SUBMODULE_DEFINITION) continue; switch (Kind) { default: // Default behavior: ignore. break; case SUBMODULE_DEFINITION: { if (Record.size() < 8) { Error("malformed module definition"); return Failure; } StringRef Name = Blob; unsigned Idx = 0; SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]); SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]); bool IsFramework = Record[Idx++]; bool IsExplicit = Record[Idx++]; bool IsSystem = Record[Idx++]; bool IsExternC = Record[Idx++]; bool InferSubmodules = Record[Idx++]; bool InferExplicitSubmodules = Record[Idx++]; bool InferExportWildcard = Record[Idx++]; bool ConfigMacrosExhaustive = Record[Idx++]; Module *ParentModule = nullptr; if (Parent) ParentModule = getSubmodule(Parent); // Retrieve this (sub)module from the module map, creating it if // necessary. CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit) .first; // FIXME: set the definition loc for CurrentModule, or call // ModMap.setInferredModuleAllowedBy() SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; if (GlobalIndex >= SubmodulesLoaded.size() || SubmodulesLoaded[GlobalIndex]) { Error("too many submodules"); return Failure; } if (!ParentModule) { if (const FileEntry *CurFile = CurrentModule->getASTFile()) { // Don't emit module relocation error if we have -fno-validate-pch if (!PP.getPreprocessorOpts().DisablePCHValidation && CurFile != F.File) { if (!Diags.isDiagnosticInFlight()) { Diag(diag::err_module_file_conflict) << CurrentModule->getTopLevelModuleName() << CurFile->getName() << F.File->getName(); } return Failure; } } CurrentModule->setASTFile(F.File); CurrentModule->PresumedModuleMapFile = F.ModuleMapPath; } CurrentModule->Kind = ModuleKind; CurrentModule->Signature = F.Signature; CurrentModule->IsFromModuleFile = true; CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; CurrentModule->IsExternC = IsExternC; CurrentModule->InferSubmodules = InferSubmodules; CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; CurrentModule->InferExportWildcard = InferExportWildcard; CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; if (DeserializationListener) DeserializationListener->ModuleRead(GlobalID, CurrentModule); SubmodulesLoaded[GlobalIndex] = CurrentModule; // Clear out data that will be replaced by what is in the module file. CurrentModule->LinkLibraries.clear(); CurrentModule->ConfigMacros.clear(); CurrentModule->UnresolvedConflicts.clear(); CurrentModule->Conflicts.clear(); // The module is available unless it's missing a requirement; relevant // requirements will be (re-)added by SUBMODULE_REQUIRES records. // Missing headers that were present when the module was built do not // make it unavailable -- if we got this far, this must be an explicitly // imported module file. CurrentModule->Requirements.clear(); CurrentModule->MissingHeaders.clear(); CurrentModule->IsMissingRequirement = ParentModule && ParentModule->IsMissingRequirement; CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement; break; } case SUBMODULE_UMBRELLA_HEADER: { std::string Filename = Blob; ResolveImportedPath(F, Filename); if (auto *Umbrella = PP.getFileManager().getFile(Filename)) { if (!CurrentModule->getUmbrellaHeader()) ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob); else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Error("mismatched umbrella headers in submodule"); return OutOfDate; } } break; } case SUBMODULE_HEADER: case SUBMODULE_EXCLUDED_HEADER: case SUBMODULE_PRIVATE_HEADER: // We lazily associate headers with their modules via the HeaderInfo table. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead // of complete filenames or remove it entirely. break; case SUBMODULE_TEXTUAL_HEADER: case SUBMODULE_PRIVATE_TEXTUAL_HEADER: // FIXME: Textual headers are not marked in the HeaderInfo table. Load // them here. break; case SUBMODULE_TOPHEADER: { CurrentModule->addTopHeaderFilename(Blob); break; } case SUBMODULE_UMBRELLA_DIR: { std::string Dirname = Blob; ResolveImportedPath(F, Dirname); if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) { if (!CurrentModule->getUmbrellaDir()) ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob); else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) { if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) Error("mismatched umbrella directories in submodule"); return OutOfDate; } } break; } case SUBMODULE_METADATA: { F.BaseSubmoduleID = getTotalNumSubmodules(); F.LocalNumSubmodules = Record[0]; unsigned LocalBaseSubmoduleID = Record[1]; if (F.LocalNumSubmodules > 0) { // Introduce the global -> local mapping for submodules within this // module. GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F)); // Introduce the local -> global mapping for submodules within this // module. F.SubmoduleRemap.insertOrReplace( std::make_pair(LocalBaseSubmoduleID, F.BaseSubmoduleID - LocalBaseSubmoduleID)); SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules); } ModuleKind = (Module::ModuleKind)Record[2]; break; } case SUBMODULE_IMPORTS: { for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { UnresolvedModuleRef Unresolved; Unresolved.File = &F; Unresolved.Mod = CurrentModule; Unresolved.ID = Record[Idx]; Unresolved.Kind = UnresolvedModuleRef::Import; Unresolved.IsWildcard = false; UnresolvedModuleRefs.push_back(Unresolved); } break; } case SUBMODULE_EXPORTS: { for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) { UnresolvedModuleRef Unresolved; Unresolved.File = &F; Unresolved.Mod = CurrentModule; Unresolved.ID = Record[Idx]; Unresolved.Kind = UnresolvedModuleRef::Export; Unresolved.IsWildcard = Record[Idx + 1]; UnresolvedModuleRefs.push_back(Unresolved); } // Once we've loaded the set of exports, there's no reason to keep // the parsed, unresolved exports around. CurrentModule->UnresolvedExports.clear(); break; } case SUBMODULE_REQUIRES: { CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(), PP.getTargetInfo()); break; } case SUBMODULE_LINK_LIBRARY: CurrentModule->LinkLibraries.push_back( Module::LinkLibrary(Blob, Record[0])); break; case SUBMODULE_CONFIG_MACRO: CurrentModule->ConfigMacros.push_back(Blob.str()); break; case SUBMODULE_CONFLICT: { UnresolvedModuleRef Unresolved; Unresolved.File = &F; Unresolved.Mod = CurrentModule; Unresolved.ID = Record[0]; Unresolved.Kind = UnresolvedModuleRef::Conflict; Unresolved.IsWildcard = false; Unresolved.String = Blob; UnresolvedModuleRefs.push_back(Unresolved); break; } case SUBMODULE_INITIALIZERS: if (!ContextObj) break; SmallVector<uint32_t, 16> Inits; for (auto &ID : Record) Inits.push_back(getGlobalDeclID(F, ID)); ContextObj->addLazyModuleInitializers(CurrentModule, Inits); break; } } } /// \brief Parse the record that corresponds to a LangOptions data /// structure. /// /// This routine parses the language options from the AST file and then gives /// them to the AST listener if one is set. /// /// \returns true if the listener deems the file unacceptable, false otherwise. bool ASTReader::ParseLanguageOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, bool AllowCompatibleDifferences) { LangOptions LangOpts; unsigned Idx = 0; #define LANGOPT(Name, Bits, Default, Description) \ LangOpts.Name = Record[Idx++]; #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++])); #include "clang/Basic/LangOptions.def" #define SANITIZER(NAME, ID) \ LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]); #include "clang/Basic/Sanitizers.def" for (unsigned N = Record[Idx++]; N; --N) LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx)); ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++]; VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx); LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion); LangOpts.CurrentModule = ReadString(Record, Idx); // Comment options. for (unsigned N = Record[Idx++]; N; --N) { LangOpts.CommentOpts.BlockCommandNames.push_back( ReadString(Record, Idx)); } LangOpts.CommentOpts.ParseAllComments = Record[Idx++]; // OpenMP offloading options. for (unsigned N = Record[Idx++]; N; --N) { LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx))); } LangOpts.OMPHostIRFile = ReadString(Record, Idx); return Listener.ReadLanguageOptions(LangOpts, Complain, AllowCompatibleDifferences); } bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, bool AllowCompatibleDifferences) { unsigned Idx = 0; TargetOptions TargetOpts; TargetOpts.Triple = ReadString(Record, Idx); TargetOpts.CPU = ReadString(Record, Idx); TargetOpts.ABI = ReadString(Record, Idx); for (unsigned N = Record[Idx++]; N; --N) { TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx)); } for (unsigned N = Record[Idx++]; N; --N) { TargetOpts.Features.push_back(ReadString(Record, Idx)); } return Listener.ReadTargetOptions(TargetOpts, Complain, AllowCompatibleDifferences); } bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener) { IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions); unsigned Idx = 0; #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++]; #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ DiagOpts->set##Name(static_cast<Type>(Record[Idx++])); #include "clang/Basic/DiagnosticOptions.def" for (unsigned N = Record[Idx++]; N; --N) DiagOpts->Warnings.push_back(ReadString(Record, Idx)); for (unsigned N = Record[Idx++]; N; --N) DiagOpts->Remarks.push_back(ReadString(Record, Idx)); return Listener.ReadDiagnosticOptions(DiagOpts, Complain); } bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener) { FileSystemOptions FSOpts; unsigned Idx = 0; FSOpts.WorkingDir = ReadString(Record, Idx); return Listener.ReadFileSystemOptions(FSOpts, Complain); } bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener) { HeaderSearchOptions HSOpts; unsigned Idx = 0; HSOpts.Sysroot = ReadString(Record, Idx); // Include entries. for (unsigned N = Record[Idx++]; N; --N) { std::string Path = ReadString(Record, Idx); frontend::IncludeDirGroup Group = static_cast<frontend::IncludeDirGroup>(Record[Idx++]); bool IsFramework = Record[Idx++]; bool IgnoreSysRoot = Record[Idx++]; HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework, IgnoreSysRoot); } // System header prefixes. for (unsigned N = Record[Idx++]; N; --N) { std::string Prefix = ReadString(Record, Idx); bool IsSystemHeader = Record[Idx++]; HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader); } HSOpts.ResourceDir = ReadString(Record, Idx); HSOpts.ModuleCachePath = ReadString(Record, Idx); HSOpts.ModuleUserBuildPath = ReadString(Record, Idx); HSOpts.DisableModuleHash = Record[Idx++]; HSOpts.ImplicitModuleMaps = Record[Idx++]; HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++]; HSOpts.UseBuiltinIncludes = Record[Idx++]; HSOpts.UseStandardSystemIncludes = Record[Idx++]; HSOpts.UseStandardCXXIncludes = Record[Idx++]; HSOpts.UseLibcxx = Record[Idx++]; std::string SpecificModuleCachePath = ReadString(Record, Idx); return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, Complain); } bool ASTReader::ParsePreprocessorOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, std::string &SuggestedPredefines) { PreprocessorOptions PPOpts; unsigned Idx = 0; // Macro definitions/undefs for (unsigned N = Record[Idx++]; N; --N) { std::string Macro = ReadString(Record, Idx); bool IsUndef = Record[Idx++]; PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef)); } // Includes for (unsigned N = Record[Idx++]; N; --N) { PPOpts.Includes.push_back(ReadString(Record, Idx)); } // Macro Includes for (unsigned N = Record[Idx++]; N; --N) { PPOpts.MacroIncludes.push_back(ReadString(Record, Idx)); } PPOpts.UsePredefines = Record[Idx++]; PPOpts.DetailedRecord = Record[Idx++]; PPOpts.ImplicitPCHInclude = ReadString(Record, Idx); PPOpts.ImplicitPTHInclude = ReadString(Record, Idx); PPOpts.ObjCXXARCStandardLibrary = static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]); SuggestedPredefines.clear(); return Listener.ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines); } std::pair<ModuleFile *, unsigned> ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) { GlobalPreprocessedEntityMapType::iterator I = GlobalPreprocessedEntityMap.find(GlobalIndex); assert(I != GlobalPreprocessedEntityMap.end() && "Corrupted global preprocessed entity map"); ModuleFile *M = I->second; unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID; return std::make_pair(M, LocalIndex); } llvm::iterator_range<PreprocessingRecord::iterator> ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const { if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord()) return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID, Mod.NumPreprocessedEntities); return llvm::make_range(PreprocessingRecord::iterator(), PreprocessingRecord::iterator()); } llvm::iterator_range<ASTReader::ModuleDeclIterator> ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) { return llvm::make_range( ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls), ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls + Mod.NumFileSortedDecls)); } PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) { PreprocessedEntityID PPID = Index+1; std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); ModuleFile &M = *PPInfo.first; unsigned LocalIndex = PPInfo.second; const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; if (!PP.getPreprocessingRecord()) { Error("no preprocessing record"); return nullptr; } SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset); llvm::BitstreamEntry Entry = M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); if (Entry.Kind != llvm::BitstreamEntry::Record) return nullptr; // Read the record. SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()), TranslateSourceLocation(M, PPOffs.getEnd())); PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); StringRef Blob; RecordData Record; PreprocessorDetailRecordTypes RecType = (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord( Entry.ID, Record, &Blob); switch (RecType) { case PPD_MACRO_EXPANSION: { bool isBuiltin = Record[0]; IdentifierInfo *Name = nullptr; MacroDefinitionRecord *Def = nullptr; if (isBuiltin) Name = getLocalIdentifier(M, Record[1]); else { PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(M, Record[1]); Def = cast<MacroDefinitionRecord>( PPRec.getLoadedPreprocessedEntity(GlobalID - 1)); } MacroExpansion *ME; if (isBuiltin) ME = new (PPRec) MacroExpansion(Name, Range); else ME = new (PPRec) MacroExpansion(Def, Range); return ME; } case PPD_MACRO_DEFINITION: { // Decode the identifier info and then check again; if the macro is // still defined and associated with the identifier, IdentifierInfo *II = getLocalIdentifier(M, Record[0]); MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range); if (DeserializationListener) DeserializationListener->MacroDefinitionRead(PPID, MD); return MD; } case PPD_INCLUSION_DIRECTIVE: { const char *FullFileNameStart = Blob.data() + Record[0]; StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]); const FileEntry *File = nullptr; if (!FullFileName.empty()) File = PP.getFileManager().getFile(FullFileName); // FIXME: Stable encoding InclusionDirective::InclusionKind Kind = static_cast<InclusionDirective::InclusionKind>(Record[2]); InclusionDirective *ID = new (PPRec) InclusionDirective(PPRec, Kind, StringRef(Blob.data(), Record[0]), Record[1], Record[3], File, Range); return ID; } } llvm_unreachable("Invalid PreprocessorDetailRecordTypes"); } /// \brief \arg SLocMapI points at a chunk of a module that contains no /// preprocessed entities or the entities it contains are not the ones we are /// looking for. Find the next module that contains entities and return the ID /// of the first entry. PreprocessedEntityID ASTReader::findNextPreprocessedEntity( GlobalSLocOffsetMapType::const_iterator SLocMapI) const { ++SLocMapI; for (GlobalSLocOffsetMapType::const_iterator EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) { ModuleFile &M = *SLocMapI->second; if (M.NumPreprocessedEntities) return M.BasePreprocessedEntityID; } return getTotalNumPreprocessedEntities(); } namespace { struct PPEntityComp { const ASTReader &Reader; ModuleFile &M; PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { } bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const { SourceLocation LHS = getLoc(L); SourceLocation RHS = getLoc(R); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } bool operator()(const PPEntityOffset &L, SourceLocation RHS) const { SourceLocation LHS = getLoc(L); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } bool operator()(SourceLocation LHS, const PPEntityOffset &R) const { SourceLocation RHS = getLoc(R); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } SourceLocation getLoc(const PPEntityOffset &PPE) const { return Reader.TranslateSourceLocation(M, PPE.getBegin()); } }; } // end anonymous namespace PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const { if (SourceMgr.isLocalSourceLocation(Loc)) return getTotalNumPreprocessedEntities(); GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find( SourceManager::MaxLoadedOffset - Loc.getOffset() - 1); assert(SLocMapI != GlobalSLocOffsetMap.end() && "Corrupted global sloc offset map"); if (SLocMapI->second->NumPreprocessedEntities == 0) return findNextPreprocessedEntity(SLocMapI); ModuleFile &M = *SLocMapI->second; typedef const PPEntityOffset *pp_iterator; pp_iterator pp_begin = M.PreprocessedEntityOffsets; pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities; size_t Count = M.NumPreprocessedEntities; size_t Half; pp_iterator First = pp_begin; pp_iterator PPI; if (EndsAfter) { PPI = std::upper_bound(pp_begin, pp_end, Loc, PPEntityComp(*this, M)); } else { // Do a binary search manually instead of using std::lower_bound because // The end locations of entities may be unordered (when a macro expansion // is inside another macro argument), but for this case it is not important // whether we get the first macro expansion or its containing macro. while (Count > 0) { Half = Count / 2; PPI = First; std::advance(PPI, Half); if (SourceMgr.isBeforeInTranslationUnit( TranslateSourceLocation(M, PPI->getEnd()), Loc)) { First = PPI; ++First; Count = Count - Half - 1; } else Count = Half; } } if (PPI == pp_end) return findNextPreprocessedEntity(SLocMapI); return M.BasePreprocessedEntityID + (PPI - pp_begin); } /// \brief Returns a pair of [Begin, End) indices of preallocated /// preprocessed entities that \arg Range encompasses. std::pair<unsigned, unsigned> ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) { if (Range.isInvalid()) return std::make_pair(0,0); assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); PreprocessedEntityID BeginID = findPreprocessedEntity(Range.getBegin(), false); PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true); return std::make_pair(BeginID, EndID); } /// \brief Optionally returns true or false if the preallocated preprocessed /// entity with index \arg Index came from file \arg FID. Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, FileID FID) { if (FID.isInvalid()) return false; std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); ModuleFile &M = *PPInfo.first; unsigned LocalIndex = PPInfo.second; const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin()); if (Loc.isInvalid()) return false; if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID)) return true; else return false; } namespace { /// \brief Visitor used to search for information about a header file. class HeaderFileInfoVisitor { const FileEntry *FE; Optional<HeaderFileInfo> HFI; public: explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) { } bool operator()(ModuleFile &M) { HeaderFileInfoLookupTable *Table = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable); if (!Table) return false; // Look in the on-disk hash table for an entry for this file name. HeaderFileInfoLookupTable::iterator Pos = Table->find(FE); if (Pos == Table->end()) return false; HFI = *Pos; return true; } Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } }; } // end anonymous namespace HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) { HeaderFileInfoVisitor Visitor(FE); ModuleMgr.visit(Visitor); if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) return *HFI; return HeaderFileInfo(); } void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) { using DiagState = DiagnosticsEngine::DiagState; SmallVector<DiagState *, 32> DiagStates; for (ModuleFile &F : ModuleMgr) { unsigned Idx = 0; auto &Record = F.PragmaDiagMappings; if (Record.empty()) continue; DiagStates.clear(); auto ReadDiagState = [&](const DiagState &BasedOn, SourceLocation Loc, bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * { unsigned BackrefID = Record[Idx++]; if (BackrefID != 0) return DiagStates[BackrefID - 1]; // A new DiagState was created here. Diag.DiagStates.push_back(BasedOn); DiagState *NewState = &Diag.DiagStates.back(); DiagStates.push_back(NewState); unsigned Size = Record[Idx++]; assert(Idx + Size * 2 <= Record.size() && "Invalid data, not enough diag/map pairs"); while (Size--) { unsigned DiagID = Record[Idx++]; DiagnosticMapping NewMapping = DiagnosticMapping::deserialize(Record[Idx++]); if (!NewMapping.isPragma() && !IncludeNonPragmaStates) continue; DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID); // If this mapping was specified as a warning but the severity was // upgraded due to diagnostic settings, simulate the current diagnostic // settings (and use a warning). if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) { NewMapping.setSeverity(diag::Severity::Warning); NewMapping.setUpgradedFromWarning(false); } Mapping = NewMapping; } return NewState; }; // Read the first state. DiagState *FirstState; if (F.Kind == MK_ImplicitModule) { // Implicitly-built modules are reused with different diagnostic // settings. Use the initial diagnostic state from Diag to simulate this // compilation's diagnostic settings. FirstState = Diag.DiagStatesByLoc.FirstDiagState; DiagStates.push_back(FirstState); // Skip the initial diagnostic state from the serialized module. assert(Record[1] == 0 && "Invalid data, unexpected backref in initial state"); Idx = 3 + Record[2] * 2; assert(Idx < Record.size() && "Invalid data, not enough state change pairs in initial state"); } else if (F.isModule()) { // For an explicit module, preserve the flags from the module build // command line (-w, -Weverything, -Werror, ...) along with any explicit // -Wblah flags. unsigned Flags = Record[Idx++]; DiagState Initial; Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1; Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1; Initial.WarningsAsErrors = Flags & 1; Flags >>= 1; Initial.EnableAllWarnings = Flags & 1; Flags >>= 1; Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1; Initial.ExtBehavior = (diag::Severity)Flags; FirstState = ReadDiagState(Initial, SourceLocation(), true); // Set up the root buffer of the module to start with the initial // diagnostic state of the module itself, to cover files that contain no // explicit transitions (for which we did not serialize anything). Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID] .StateTransitions.push_back({FirstState, 0}); } else { // For prefix ASTs, start with whatever the user configured on the // command line. Idx++; // Skip flags. FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, SourceLocation(), false); } // Read the state transitions. unsigned NumLocations = Record[Idx++]; while (NumLocations--) { assert(Idx < Record.size() && "Invalid data, missing pragma diagnostic states"); SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]); auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc); assert(IDAndOffset.second == 0 && "not a start location for a FileID"); unsigned Transitions = Record[Idx++]; // Note that we don't need to set up Parent/ParentOffset here, because // we won't be changing the diagnostic state within imported FileIDs // (other than perhaps appending to the main source file, which has no // parent). auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first]; F.StateTransitions.reserve(F.StateTransitions.size() + Transitions); for (unsigned I = 0; I != Transitions; ++I) { unsigned Offset = Record[Idx++]; auto *State = ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false); F.StateTransitions.push_back({State, Offset}); } } // Read the final state. assert(Idx < Record.size() && "Invalid data, missing final pragma diagnostic state"); SourceLocation CurStateLoc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]); auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false); if (!F.isModule()) { Diag.DiagStatesByLoc.CurDiagState = CurState; Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc; // Preserve the property that the imaginary root file describes the // current state. auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions; if (T.empty()) T.push_back({CurState, 0}); else T[0].State = CurState; } // Don't try to read these mappings again. Record.clear(); } } /// \brief Get the correct cursor and offset for loading a type. ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index); assert(I != GlobalTypeMap.end() && "Corrupted global type map"); ModuleFile *M = I->second; return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]); } /// \brief Read and return the type with the given index.. /// /// The index is the type ID, shifted and minus the number of predefs. This /// routine actually reads the record corresponding to the type at the given /// location. It is a helper routine for GetType, which deals with reading type /// IDs. QualType ASTReader::readTypeRecord(unsigned Index) { assert(ContextObj && "reading type with no AST context"); ASTContext &Context = *ContextObj; RecordLocation Loc = TypeCursorForIndex(Index); BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; // Keep track of where we are in the stream, then jump back there // after reading this type. SavedStreamPosition SavedPosition(DeclsCursor); ReadingKindTracker ReadingKind(Read_Type, *this); // Note that we are loading a type record. Deserializing AType(this); unsigned Idx = 0; DeclsCursor.JumpToBit(Loc.Offset); RecordData Record; unsigned Code = DeclsCursor.ReadCode(); switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) { case TYPE_EXT_QUAL: { if (Record.size() != 2) { Error("Incorrect encoding of extended qualifier type"); return QualType(); } QualType Base = readType(*Loc.F, Record, Idx); Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]); return Context.getQualifiedType(Base, Quals); } case TYPE_COMPLEX: { if (Record.size() != 1) { Error("Incorrect encoding of complex type"); return QualType(); } QualType ElemType = readType(*Loc.F, Record, Idx); return Context.getComplexType(ElemType); } case TYPE_POINTER: { if (Record.size() != 1) { Error("Incorrect encoding of pointer type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); return Context.getPointerType(PointeeType); } case TYPE_DECAYED: { if (Record.size() != 1) { Error("Incorrect encoding of decayed type"); return QualType(); } QualType OriginalType = readType(*Loc.F, Record, Idx); QualType DT = Context.getAdjustedParameterType(OriginalType); if (!isa<DecayedType>(DT)) Error("Decayed type does not decay"); return DT; } case TYPE_ADJUSTED: { if (Record.size() != 2) { Error("Incorrect encoding of adjusted type"); return QualType(); } QualType OriginalTy = readType(*Loc.F, Record, Idx); QualType AdjustedTy = readType(*Loc.F, Record, Idx); return Context.getAdjustedType(OriginalTy, AdjustedTy); } case TYPE_BLOCK_POINTER: { if (Record.size() != 1) { Error("Incorrect encoding of block pointer type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); return Context.getBlockPointerType(PointeeType); } case TYPE_LVALUE_REFERENCE: { if (Record.size() != 2) { Error("Incorrect encoding of lvalue reference type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); return Context.getLValueReferenceType(PointeeType, Record[1]); } case TYPE_RVALUE_REFERENCE: { if (Record.size() != 1) { Error("Incorrect encoding of rvalue reference type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); return Context.getRValueReferenceType(PointeeType); } case TYPE_MEMBER_POINTER: { if (Record.size() != 2) { Error("Incorrect encoding of member pointer type"); return QualType(); } QualType PointeeType = readType(*Loc.F, Record, Idx); QualType ClassType = readType(*Loc.F, Record, Idx); if (PointeeType.isNull() || ClassType.isNull()) return QualType(); return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr()); } case TYPE_CONSTANT_ARRAY: { QualType ElementType = readType(*Loc.F, Record, Idx); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; unsigned Idx = 3; llvm::APInt Size = ReadAPInt(Record, Idx); return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals); } case TYPE_INCOMPLETE_ARRAY: { QualType ElementType = readType(*Loc.F, Record, Idx); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals); } case TYPE_VARIABLE_ARRAY: { QualType ElementType = readType(*Loc.F, Record, Idx); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]); SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]); return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F), ASM, IndexTypeQuals, SourceRange(LBLoc, RBLoc)); } case TYPE_VECTOR: { if (Record.size() != 3) { Error("incorrect encoding of vector type in AST file"); return QualType(); } QualType ElementType = readType(*Loc.F, Record, Idx); unsigned NumElements = Record[1]; unsigned VecKind = Record[2]; return Context.getVectorType(ElementType, NumElements, (VectorType::VectorKind)VecKind); } case TYPE_EXT_VECTOR: { if (Record.size() != 3) { Error("incorrect encoding of extended vector type in AST file"); return QualType(); } QualType ElementType = readType(*Loc.F, Record, Idx); unsigned NumElements = Record[1]; return Context.getExtVectorType(ElementType, NumElements); } case TYPE_FUNCTION_NO_PROTO: { if (Record.size() != 7) { Error("incorrect encoding of no-proto function type"); return QualType(); } QualType ResultType = readType(*Loc.F, Record, Idx); FunctionType::ExtInfo Info(Record[1], Record[2], Record[3], (CallingConv)Record[4], Record[5], Record[6]); return Context.getFunctionNoProtoType(ResultType, Info); } case TYPE_FUNCTION_PROTO: { QualType ResultType = readType(*Loc.F, Record, Idx); FunctionProtoType::ExtProtoInfo EPI; EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1], /*hasregparm*/ Record[2], /*regparm*/ Record[3], static_cast<CallingConv>(Record[4]), /*produces*/ Record[5], /*nocallersavedregs*/ Record[6]); unsigned Idx = 7; EPI.Variadic = Record[Idx++]; EPI.HasTrailingReturn = Record[Idx++]; EPI.TypeQuals = Record[Idx++]; EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]); SmallVector<QualType, 8> ExceptionStorage; readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx); unsigned NumParams = Record[Idx++]; SmallVector<QualType, 16> ParamTypes; for (unsigned I = 0; I != NumParams; ++I) ParamTypes.push_back(readType(*Loc.F, Record, Idx)); SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos; if (Idx != Record.size()) { for (unsigned I = 0; I != NumParams; ++I) ExtParameterInfos.push_back( FunctionProtoType::ExtParameterInfo ::getFromOpaqueValue(Record[Idx++])); EPI.ExtParameterInfos = ExtParameterInfos.data(); } assert(Idx == Record.size()); return Context.getFunctionType(ResultType, ParamTypes, EPI); } case TYPE_UNRESOLVED_USING: { unsigned Idx = 0; return Context.getTypeDeclType( ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx)); } case TYPE_TYPEDEF: { if (Record.size() != 2) { Error("incorrect encoding of typedef type"); return QualType(); } unsigned Idx = 0; TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx); QualType Canonical = readType(*Loc.F, Record, Idx); if (!Canonical.isNull()) Canonical = Context.getCanonicalType(Canonical); return Context.getTypedefType(Decl, Canonical); } case TYPE_TYPEOF_EXPR: return Context.getTypeOfExprType(ReadExpr(*Loc.F)); case TYPE_TYPEOF: { if (Record.size() != 1) { Error("incorrect encoding of typeof(type) in AST file"); return QualType(); } QualType UnderlyingType = readType(*Loc.F, Record, Idx); return Context.getTypeOfType(UnderlyingType); } case TYPE_DECLTYPE: { QualType UnderlyingType = readType(*Loc.F, Record, Idx); return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType); } case TYPE_UNARY_TRANSFORM: { QualType BaseType = readType(*Loc.F, Record, Idx); QualType UnderlyingType = readType(*Loc.F, Record, Idx); UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2]; return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind); } case TYPE_AUTO: { QualType Deduced = readType(*Loc.F, Record, Idx); AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++]; bool IsDependent = Deduced.isNull() ? Record[Idx++] : false; return Context.getAutoType(Deduced, Keyword, IsDependent); } case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: { TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); QualType Deduced = readType(*Loc.F, Record, Idx); bool IsDependent = Deduced.isNull() ? Record[Idx++] : false; return Context.getDeducedTemplateSpecializationType(Name, Deduced, IsDependent); } case TYPE_RECORD: { if (Record.size() != 2) { Error("incorrect encoding of record type"); return QualType(); } unsigned Idx = 0; bool IsDependent = Record[Idx++]; RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx); RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl()); QualType T = Context.getRecordType(RD); const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); return T; } case TYPE_ENUM: { if (Record.size() != 2) { Error("incorrect encoding of enum type"); return QualType(); } unsigned Idx = 0; bool IsDependent = Record[Idx++]; QualType T = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx)); const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); return T; } case TYPE_ATTRIBUTED: { if (Record.size() != 3) { Error("incorrect encoding of attributed type"); return QualType(); } QualType modifiedType = readType(*Loc.F, Record, Idx); QualType equivalentType = readType(*Loc.F, Record, Idx); AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]); return Context.getAttributedType(kind, modifiedType, equivalentType); } case TYPE_PAREN: { if (Record.size() != 1) { Error("incorrect encoding of paren type"); return QualType(); } QualType InnerType = readType(*Loc.F, Record, Idx); return Context.getParenType(InnerType); } case TYPE_PACK_EXPANSION: { if (Record.size() != 2) { Error("incorrect encoding of pack expansion type"); return QualType(); } QualType Pattern = readType(*Loc.F, Record, Idx); if (Pattern.isNull()) return QualType(); Optional<unsigned> NumExpansions; if (Record[1]) NumExpansions = Record[1] - 1; return Context.getPackExpansionType(Pattern, NumExpansions); } case TYPE_ELABORATED: { unsigned Idx = 0; ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); QualType NamedType = readType(*Loc.F, Record, Idx); return Context.getElaboratedType(Keyword, NNS, NamedType); } case TYPE_OBJC_INTERFACE: { unsigned Idx = 0; ObjCInterfaceDecl *ItfD = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx); return Context.getObjCInterfaceType(ItfD->getCanonicalDecl()); } case TYPE_OBJC_TYPE_PARAM: { unsigned Idx = 0; ObjCTypeParamDecl *Decl = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx); unsigned NumProtos = Record[Idx++]; SmallVector<ObjCProtocolDecl*, 4> Protos; for (unsigned I = 0; I != NumProtos; ++I) Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx)); return Context.getObjCTypeParamType(Decl, Protos); } case TYPE_OBJC_OBJECT: { unsigned Idx = 0; QualType Base = readType(*Loc.F, Record, Idx); unsigned NumTypeArgs = Record[Idx++]; SmallVector<QualType, 4> TypeArgs; for (unsigned I = 0; I != NumTypeArgs; ++I) TypeArgs.push_back(readType(*Loc.F, Record, Idx)); unsigned NumProtos = Record[Idx++]; SmallVector<ObjCProtocolDecl*, 4> Protos; for (unsigned I = 0; I != NumProtos; ++I) Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx)); bool IsKindOf = Record[Idx++]; return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf); } case TYPE_OBJC_OBJECT_POINTER: { unsigned Idx = 0; QualType Pointee = readType(*Loc.F, Record, Idx); return Context.getObjCObjectPointerType(Pointee); } case TYPE_SUBST_TEMPLATE_TYPE_PARM: { unsigned Idx = 0; QualType Parm = readType(*Loc.F, Record, Idx); QualType Replacement = readType(*Loc.F, Record, Idx); return Context.getSubstTemplateTypeParmType( cast<TemplateTypeParmType>(Parm), Context.getCanonicalType(Replacement)); } case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: { unsigned Idx = 0; QualType Parm = readType(*Loc.F, Record, Idx); TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx); return Context.getSubstTemplateTypeParmPackType( cast<TemplateTypeParmType>(Parm), ArgPack); } case TYPE_INJECTED_CLASS_NAME: { CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx); QualType TST = readType(*Loc.F, Record, Idx); // probably derivable // FIXME: ASTContext::getInjectedClassNameType is not currently suitable // for AST reading, too much interdependencies. const Type *T = nullptr; for (auto *DI = D; DI; DI = DI->getPreviousDecl()) { if (const Type *Existing = DI->getTypeForDecl()) { T = Existing; break; } } if (!T) { T = new (Context, TypeAlignment) InjectedClassNameType(D, TST); for (auto *DI = D; DI; DI = DI->getPreviousDecl()) DI->setTypeForDecl(T); } return QualType(T, 0); } case TYPE_TEMPLATE_TYPE_PARM: { unsigned Idx = 0; unsigned Depth = Record[Idx++]; unsigned Index = Record[Idx++]; bool Pack = Record[Idx++]; TemplateTypeParmDecl *D = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx); return Context.getTemplateTypeParmType(Depth, Index, Pack, D); } case TYPE_DEPENDENT_NAME: { unsigned Idx = 0; ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx); QualType Canon = readType(*Loc.F, Record, Idx); if (!Canon.isNull()) Canon = Context.getCanonicalType(Canon); return Context.getDependentNameType(Keyword, NNS, Name, Canon); } case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: { unsigned Idx = 0; ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx); unsigned NumArgs = Record[Idx++]; SmallVector<TemplateArgument, 8> Args; Args.reserve(NumArgs); while (NumArgs--) Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx)); return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name, Args); } case TYPE_DEPENDENT_SIZED_ARRAY: { unsigned Idx = 0; // ArrayType QualType ElementType = readType(*Loc.F, Record, Idx); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[Idx++]; unsigned IndexTypeQuals = Record[Idx++]; // DependentSizedArrayType Expr *NumElts = ReadExpr(*Loc.F); SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx); return Context.getDependentSizedArrayType(ElementType, NumElts, ASM, IndexTypeQuals, Brackets); } case TYPE_TEMPLATE_SPECIALIZATION: { unsigned Idx = 0; bool IsDependent = Record[Idx++]; TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); SmallVector<TemplateArgument, 8> Args; ReadTemplateArgumentList(Args, *Loc.F, Record, Idx); QualType Underlying = readType(*Loc.F, Record, Idx); QualType T; if (Underlying.isNull()) T = Context.getCanonicalTemplateSpecializationType(Name, Args); else T = Context.getTemplateSpecializationType(Name, Args, Underlying); const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); return T; } case TYPE_ATOMIC: { if (Record.size() != 1) { Error("Incorrect encoding of atomic type"); return QualType(); } QualType ValueType = readType(*Loc.F, Record, Idx); return Context.getAtomicType(ValueType); } case TYPE_PIPE: { if (Record.size() != 2) { Error("Incorrect encoding of pipe type"); return QualType(); } // Reading the pipe element type. QualType ElementType = readType(*Loc.F, Record, Idx); unsigned ReadOnly = Record[1]; return Context.getPipeType(ElementType, ReadOnly); } case TYPE_DEPENDENT_SIZED_EXT_VECTOR: { unsigned Idx = 0; // DependentSizedExtVectorType QualType ElementType = readType(*Loc.F, Record, Idx); Expr *SizeExpr = ReadExpr(*Loc.F); SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx); return Context.getDependentSizedExtVectorType(ElementType, SizeExpr, AttrLoc); } } llvm_unreachable("Invalid TypeCode!"); } void ASTReader::readExceptionSpec(ModuleFile &ModuleFile, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI, const RecordData &Record, unsigned &Idx) { ExceptionSpecificationType EST = static_cast<ExceptionSpecificationType>(Record[Idx++]); ESI.Type = EST; if (EST == EST_Dynamic) { for (unsigned I = 0, N = Record[Idx++]; I != N; ++I) Exceptions.push_back(readType(ModuleFile, Record, Idx)); ESI.Exceptions = Exceptions; } else if (EST == EST_ComputedNoexcept) { ESI.NoexceptExpr = ReadExpr(ModuleFile); } else if (EST == EST_Uninstantiated) { ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); } else if (EST == EST_Unevaluated) { ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); } } class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> { ModuleFile *F; ASTReader *Reader; const ASTReader::RecordData &Record; unsigned &Idx; SourceLocation ReadSourceLocation() { return Reader->ReadSourceLocation(*F, Record, Idx); } TypeSourceInfo *GetTypeSourceInfo() { return Reader->GetTypeSourceInfo(*F, Record, Idx); } NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() { return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx); } public: TypeLocReader(ModuleFile &F, ASTReader &Reader, const ASTReader::RecordData &Record, unsigned &Idx) : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {} // We want compile-time assurance that we've enumerated all of // these, so unfortunately we have to declare them first, then // define them out-of-line. #define ABSTRACT_TYPELOC(CLASS, PARENT) #define TYPELOC(CLASS, PARENT) \ void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); #include "clang/AST/TypeLocNodes.def" void VisitFunctionTypeLoc(FunctionTypeLoc); void VisitArrayTypeLoc(ArrayTypeLoc); }; void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { // nothing to do } void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { TL.setBuiltinLoc(ReadSourceLocation()); if (TL.needsExtraLocalData()) { TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++])); TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++])); TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++])); TL.setModeAttr(Record[Idx++]); } } void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { TL.setStarLoc(ReadSourceLocation()); } void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) { // nothing to do } void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { // nothing to do } void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { TL.setCaretLoc(ReadSourceLocation()); } void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { TL.setAmpLoc(ReadSourceLocation()); } void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { TL.setAmpAmpLoc(ReadSourceLocation()); } void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { TL.setStarLoc(ReadSourceLocation()); TL.setClassTInfo(GetTypeSourceInfo()); } void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { TL.setLBracketLoc(ReadSourceLocation()); TL.setRBracketLoc(ReadSourceLocation()); if (Record[Idx++]) TL.setSizeExpr(Reader->ReadExpr(*F)); else TL.setSizeExpr(nullptr); } void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { VisitArrayTypeLoc(TL); } void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { VisitArrayTypeLoc(TL); } void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { VisitArrayTypeLoc(TL); } void TypeLocReader::VisitDependentSizedArrayTypeLoc( DependentSizedArrayTypeLoc TL) { VisitArrayTypeLoc(TL); } void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( DependentSizedExtVectorTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { TL.setLocalRangeBegin(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx), Reader->ReadSourceLocation(*F, Record, Idx))); TL.setLocalRangeEnd(ReadSourceLocation()); for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) { TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx)); } } void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { VisitFunctionTypeLoc(TL); } void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { VisitFunctionTypeLoc(TL); } void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { TL.setTypeofLoc(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); } void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { TL.setTypeofLoc(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); TL.setUnderlyingTInfo(GetTypeSourceInfo()); } void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { TL.setKWLoc(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); TL.setUnderlyingTInfo(GetTypeSourceInfo()); } void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc( DeducedTemplateSpecializationTypeLoc TL) { TL.setTemplateNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { TL.setAttrNameLoc(ReadSourceLocation()); if (TL.hasAttrOperand()) { SourceRange range; range.setBegin(ReadSourceLocation()); range.setEnd(ReadSourceLocation()); TL.setAttrOperandParensRange(range); } if (TL.hasAttrExprOperand()) { if (Record[Idx++]) TL.setAttrExprOperand(Reader->ReadExpr(*F)); else TL.setAttrExprOperand(nullptr); } else if (TL.hasAttrEnumOperand()) TL.setAttrEnumOperandLoc(ReadSourceLocation()); } void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( SubstTemplateTypeParmTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( SubstTemplateTypeParmPackTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitTemplateSpecializationTypeLoc( TemplateSpecializationTypeLoc TL) { TL.setTemplateKeywordLoc(ReadSourceLocation()); TL.setTemplateNameLoc(ReadSourceLocation()); TL.setLAngleLoc(ReadSourceLocation()); TL.setRAngleLoc(ReadSourceLocation()); for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) TL.setArgLocInfo( i, Reader->GetTemplateArgumentLocInfo( *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx)); } void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); } void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { TL.setElaboratedKeywordLoc(ReadSourceLocation()); TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); } void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { TL.setElaboratedKeywordLoc(ReadSourceLocation()); TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( DependentTemplateSpecializationTypeLoc TL) { TL.setElaboratedKeywordLoc(ReadSourceLocation()); TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); TL.setTemplateKeywordLoc(ReadSourceLocation()); TL.setTemplateNameLoc(ReadSourceLocation()); TL.setLAngleLoc(ReadSourceLocation()); TL.setRAngleLoc(ReadSourceLocation()); for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) TL.setArgLocInfo( I, Reader->GetTemplateArgumentLocInfo( *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx)); } void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { TL.setEllipsisLoc(ReadSourceLocation()); } void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { TL.setNameLoc(ReadSourceLocation()); } void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { if (TL.getNumProtocols()) { TL.setProtocolLAngleLoc(ReadSourceLocation()); TL.setProtocolRAngleLoc(ReadSourceLocation()); } for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) TL.setProtocolLoc(i, ReadSourceLocation()); } void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { TL.setHasBaseTypeAsWritten(Record[Idx++]); TL.setTypeArgsLAngleLoc(ReadSourceLocation()); TL.setTypeArgsRAngleLoc(ReadSourceLocation()); for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) TL.setTypeArgTInfo(i, GetTypeSourceInfo()); TL.setProtocolLAngleLoc(ReadSourceLocation()); TL.setProtocolRAngleLoc(ReadSourceLocation()); for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) TL.setProtocolLoc(i, ReadSourceLocation()); } void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { TL.setStarLoc(ReadSourceLocation()); } void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) { TL.setKWLoc(ReadSourceLocation()); TL.setLParenLoc(ReadSourceLocation()); TL.setRParenLoc(ReadSourceLocation()); } void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) { TL.setKWLoc(ReadSourceLocation()); } TypeSourceInfo * ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record, unsigned &Idx) { QualType InfoTy = readType(F, Record, Idx); if (InfoTy.isNull()) return nullptr; TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy); TypeLocReader TLR(F, *this, Record, Idx); for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc()) TLR.Visit(TL); return TInfo; } QualType ASTReader::GetType(TypeID ID) { assert(ContextObj && "reading type with no AST context"); ASTContext &Context = *ContextObj; unsigned FastQuals = ID & Qualifiers::FastMask; unsigned Index = ID >> Qualifiers::FastWidth; if (Index < NUM_PREDEF_TYPE_IDS) { QualType T; switch ((PredefinedTypeIDs)Index) { case PREDEF_TYPE_NULL_ID: return QualType(); case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break; case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break; case PREDEF_TYPE_CHAR_U_ID: case PREDEF_TYPE_CHAR_S_ID: // FIXME: Check that the signedness of CharTy is correct! T = Context.CharTy; break; case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break; case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break; case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break; case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break; case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break; case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break; case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break; case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break; case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break; case PREDEF_TYPE_INT_ID: T = Context.IntTy; break; case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break; case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break; case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break; case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break; case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break; case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break; case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break; case PREDEF_TYPE_FLOAT128_ID: T = Context.Float128Ty; break; case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break; case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break; case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break; case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break; case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break; case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break; case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break; case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break; case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break; case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break; case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break; #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case PREDEF_TYPE_##Id##_ID: \ T = Context.SingletonId; \ break; #include "clang/Basic/OpenCLImageTypes.def" case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break; case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break; case PREDEF_TYPE_CLK_EVENT_ID: T = Context.OCLClkEventTy; break; case PREDEF_TYPE_QUEUE_ID: T = Context.OCLQueueTy; break; case PREDEF_TYPE_RESERVE_ID_ID: T = Context.OCLReserveIDTy; break; case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break; case PREDEF_TYPE_AUTO_RREF_DEDUCT: T = Context.getAutoRRefDeductType(); break; case PREDEF_TYPE_ARC_UNBRIDGED_CAST: T = Context.ARCUnbridgedCastTy; break; case PREDEF_TYPE_BUILTIN_FN: T = Context.BuiltinFnTy; break; case PREDEF_TYPE_OMP_ARRAY_SECTION: T = Context.OMPArraySectionTy; break; } assert(!T.isNull() && "Unknown predefined type"); return T.withFastQualifiers(FastQuals); } Index -= NUM_PREDEF_TYPE_IDS; assert(Index < NumTypesLoaded && "Type index out-of-range"); if (TypesLoaded.find(Index) == TypesLoaded.end()) { QualType QualTy = readTypeRecord(Index); TypesLoaded.insert({Index, QualTy}); if (TypesLoaded.find(Index) == TypesLoaded.end()) return QualType(); QualTy->setFromAST(); if (DeserializationListener) DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID), QualTy); } return TypesLoaded.find(Index)->second.withFastQualifiers(FastQuals); } QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) { return GetType(getGlobalTypeID(F, LocalID)); } serialization::TypeID ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const { unsigned FastQuals = LocalID & Qualifiers::FastMask; unsigned LocalIndex = LocalID >> Qualifiers::FastWidth; if (LocalIndex < NUM_PREDEF_TYPE_IDS) return LocalID; if (!F.ModuleOffsetMap.empty()) ReadModuleOffsetMap(F); ContinuousRangeMap<uint32_t, int, 2>::iterator I = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS); assert(I != F.TypeRemap.end() && "Invalid index into type index remap"); unsigned GlobalIndex = LocalIndex + I->second; return (GlobalIndex << Qualifiers::FastWidth) | FastQuals; } TemplateArgumentLocInfo ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind, const RecordData &Record, unsigned &Index) { switch (Kind) { case TemplateArgument::Expression: return ReadExpr(F); case TemplateArgument::Type: return GetTypeSourceInfo(F, Record, Index); case TemplateArgument::Template: { NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Index); SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, SourceLocation()); } case TemplateArgument::TemplateExpansion: { NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Index); SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index); return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, EllipsisLoc); } case TemplateArgument::Null: case TemplateArgument::Integral: case TemplateArgument::Declaration: case TemplateArgument::NullPtr: case TemplateArgument::Pack: // FIXME: Is this right? return TemplateArgumentLocInfo(); } llvm_unreachable("unexpected template argument loc"); } TemplateArgumentLoc ASTReader::ReadTemplateArgumentLoc(ModuleFile &F, const RecordData &Record, unsigned &Index) { TemplateArgument Arg = ReadTemplateArgument(F, Record, Index); if (Arg.getKind() == TemplateArgument::Expression) { if (Record[Index++]) // bool InfoHasSameExpr. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); } return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(), Record, Index)); } const ASTTemplateArgumentListInfo* ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F, const RecordData &Record, unsigned &Index) { SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index); SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index); unsigned NumArgsAsWritten = Record[Index++]; TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc); for (unsigned i = 0; i != NumArgsAsWritten; ++i) TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index)); return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo); } Decl *ASTReader::GetExternalDecl(uint32_t ID) { return GetDecl(ID); } void ASTReader::CompleteRedeclChain(const Decl *D) { if (NumCurrentElementsDeserializing) { // We arrange to not care about the complete redeclaration chain while we're // deserializing. Just remember that the AST has marked this one as complete // but that it's not actually complete yet, so we know we still need to // complete it later. PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D)); return; } const DeclContext *DC = D->getDeclContext()->getRedeclContext(); // If this is a named declaration, complete it by looking it up // within its context. // // FIXME: Merging a function definition should merge // all mergeable entities within it. if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) || isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) { if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) { if (!getContext().getLangOpts().CPlusPlus && isa<TranslationUnitDecl>(DC)) { // Outside of C++, we don't have a lookup table for the TU, so update // the identifier instead. (For C++ modules, we don't store decls // in the serialized identifier table, so we do the lookup in the TU.) auto *II = Name.getAsIdentifierInfo(); assert(II && "non-identifier name in C?"); if (II->isOutOfDate()) updateOutOfDateIdentifier(*II); } else DC->lookup(Name); } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) { // Find all declarations of this kind from the relevant context. for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) { auto *DC = cast<DeclContext>(DCDecl); SmallVector<Decl*, 8> Decls; FindExternalLexicalDecls( DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls); } } } RedeclarableTemplateDecl *Template = nullptr; ArrayRef<TemplateArgument> Args; if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { Template = CTSD->getSpecializedTemplate(); Args = CTSD->getTemplateArgs().asArray(); } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) { Template = VTSD->getSpecializedTemplate(); Args = VTSD->getTemplateArgs().asArray(); } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { if (auto *Tmplt = FD->getPrimaryTemplate()) { Template = Tmplt; Args = FD->getTemplateSpecializationArgs()->asArray(); } } if (Template) Template->loadLazySpecializationsImpl(Args); } CXXCtorInitializer ** ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { RecordLocation Loc = getLocalBitOffset(Offset); BitstreamCursor &Cursor = Loc.F->DeclsCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(Loc.Offset); ReadingKindTracker ReadingKind(Read_Decl, *this); RecordData Record; unsigned Code = Cursor.ReadCode(); unsigned RecCode = Cursor.readRecord(Code, Record); if (RecCode != DECL_CXX_CTOR_INITIALIZERS) { Error("malformed AST file: missing C++ ctor initializers"); return nullptr; } unsigned Idx = 0; return ReadCXXCtorInitializers(*Loc.F, Record, Idx); } CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { assert(ContextObj && "reading base specifiers with no AST context"); ASTContext &Context = *ContextObj; RecordLocation Loc = getLocalBitOffset(Offset); BitstreamCursor &Cursor = Loc.F->DeclsCursor; SavedStreamPosition SavedPosition(Cursor); Cursor.JumpToBit(Loc.Offset); ReadingKindTracker ReadingKind(Read_Decl, *this); RecordData Record; unsigned Code = Cursor.ReadCode(); unsigned RecCode = Cursor.readRecord(Code, Record); if (RecCode != DECL_CXX_BASE_SPECIFIERS) { Error("malformed AST file: missing C++ base specifiers"); return nullptr; } unsigned Idx = 0; unsigned NumBases = Record[Idx++]; void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases); CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; for (unsigned I = 0; I != NumBases; ++I) Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx); return Bases; } serialization::DeclID ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const { if (LocalID < NUM_PREDEF_DECL_IDS) return LocalID; if (!F.ModuleOffsetMap.empty()) ReadModuleOffsetMap(F); ContinuousRangeMap<uint32_t, int, 2>::iterator I = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS); assert(I != F.DeclRemap.end() && "Invalid index into decl index remap"); return LocalID + I->second; } bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const { // Predefined decls aren't from any module. if (ID < NUM_PREDEF_DECL_IDS) return false; return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID && ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls; } ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) { if (!D->isFromASTFile()) return nullptr; GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID()); assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); return I->second; } SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) { if (ID < NUM_PREDEF_DECL_IDS) return SourceLocation(); unsigned Index = ID - NUM_PREDEF_DECL_IDS; if (Index > NumDeclsLoaded) { Error("declaration ID out-of-range for AST file"); return SourceLocation(); } auto FindRes = DeclsLoaded.find(Index); if (FindRes != DeclsLoaded.end()) return FindRes->second->getLocation(); SourceLocation Loc; DeclCursorForID(ID, Loc); return Loc; } static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) { switch (ID) { case PREDEF_DECL_NULL_ID: return nullptr; case PREDEF_DECL_TRANSLATION_UNIT_ID: return Context.getTranslationUnitDecl(); case PREDEF_DECL_OBJC_ID_ID: return Context.getObjCIdDecl(); case PREDEF_DECL_OBJC_SEL_ID: return Context.getObjCSelDecl(); case PREDEF_DECL_OBJC_CLASS_ID: return Context.getObjCClassDecl(); case PREDEF_DECL_OBJC_PROTOCOL_ID: return Context.getObjCProtocolDecl(); case PREDEF_DECL_INT_128_ID: return Context.getInt128Decl(); case PREDEF_DECL_UNSIGNED_INT_128_ID: return Context.getUInt128Decl(); case PREDEF_DECL_OBJC_INSTANCETYPE_ID: return Context.getObjCInstanceTypeDecl(); case PREDEF_DECL_BUILTIN_VA_LIST_ID: return Context.getBuiltinVaListDecl(); case PREDEF_DECL_VA_LIST_TAG: return Context.getVaListTagDecl(); case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID: return Context.getBuiltinMSVaListDecl(); case PREDEF_DECL_EXTERN_C_CONTEXT_ID: return Context.getExternCContextDecl(); case PREDEF_DECL_MAKE_INTEGER_SEQ_ID: return Context.getMakeIntegerSeqDecl(); case PREDEF_DECL_CF_CONSTANT_STRING_ID: return Context.getCFConstantStringDecl(); case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID: return Context.getCFConstantStringTagDecl(); case PREDEF_DECL_TYPE_PACK_ELEMENT_ID: return Context.getTypePackElementDecl(); } llvm_unreachable("PredefinedDeclIDs unknown enum value"); } Decl *ASTReader::GetExistingDecl(DeclID ID) { assert(ContextObj && "reading decl with no AST context"); if (ID < NUM_PREDEF_DECL_IDS) { Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID); if (D) { // Track that we have merged the declaration with ID \p ID into the // pre-existing predefined declaration \p D. auto &Merged = KeyDecls[D->getCanonicalDecl()]; if (Merged.empty()) Merged.push_back(ID); } return D; } unsigned Index = ID - NUM_PREDEF_DECL_IDS; if (Index >= NumDeclsLoaded) { assert(0 && "declaration ID out-of-range for AST file"); Error("declaration ID out-of-range for AST file"); return nullptr; } auto FindRes = DeclsLoaded.find(Index); if (FindRes == DeclsLoaded.end()) return nullptr; return FindRes->second; } Decl *ASTReader::GetDecl(DeclID ID) { if (ID < NUM_PREDEF_DECL_IDS) return GetExistingDecl(ID); unsigned Index = ID - NUM_PREDEF_DECL_IDS; if (Index >= NumDeclsLoaded) { assert(0 && "declaration ID out-of-range for AST file"); Error("declaration ID out-of-range for AST file"); return nullptr; } if (DeclsLoaded.find(Index) == DeclsLoaded.end()) { ReadDeclRecord(ID); if (DeserializationListener) DeserializationListener->DeclRead(ID, DeclsLoaded.find(Index)->second); } return DeclsLoaded.find(Index)->second; } DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, DeclID GlobalID) { if (GlobalID < NUM_PREDEF_DECL_IDS) return GlobalID; GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID); assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); ModuleFile *Owner = I->second; llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos = M.GlobalToLocalDeclIDs.find(Owner); if (Pos == M.GlobalToLocalDeclIDs.end()) return 0; return GlobalID - Owner->BaseDeclID + Pos->second; } serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F, const RecordData &Record, unsigned &Idx) { if (Idx >= Record.size()) { Error("Corrupted AST file"); return 0; } return getGlobalDeclID(F, Record[Idx++]); } /// \brief Resolve the offset of a statement into a statement. /// /// This operation will read a new statement from the external /// source each time it is called, and is meant to be used via a /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { // Switch case IDs are per Decl. ClearSwitchCaseIDs(); // Offset here is a global offset across the entire chain. RecordLocation Loc = getLocalBitOffset(Offset); Loc.F->DeclsCursor.JumpToBit(Loc.Offset); assert(NumCurrentElementsDeserializing == 0 && "should not be called while already deserializing"); Deserializing D(this); return ReadStmtFromStream(*Loc.F); } void ASTReader::FindExternalLexicalDecls( const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl<Decl *> &Decls) { bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {}; auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) { assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries"); for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) { auto K = (Decl::Kind)+LexicalDecls[I]; if (!IsKindWeWant(K)) continue; auto ID = (serialization::DeclID)+LexicalDecls[I + 1]; // Don't add predefined declarations to the lexical context more // than once. if (ID < NUM_PREDEF_DECL_IDS) { if (PredefsVisited[ID]) continue; PredefsVisited[ID] = true; } if (Decl *D = GetLocalDecl(*M, ID)) { assert(D->getKind() == K && "wrong kind for lexical decl"); if (!DC->isDeclInLexicalTraversal(D)) Decls.push_back(D); } } }; if (isa<TranslationUnitDecl>(DC)) { for (auto Lexical : TULexicalDecls) Visit(Lexical.first, Lexical.second); } else { auto I = LexicalDecls.find(DC); if (I != LexicalDecls.end()) Visit(I->second.first, I->second.second); } ++NumLexicalDeclContextsRead; } namespace { class DeclIDComp { ASTReader &Reader; ModuleFile &Mod; public: DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {} bool operator()(LocalDeclID L, LocalDeclID R) const { SourceLocation LHS = getLocation(L); SourceLocation RHS = getLocation(R); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } bool operator()(SourceLocation LHS, LocalDeclID R) const { SourceLocation RHS = getLocation(R); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } bool operator()(LocalDeclID L, SourceLocation RHS) const { SourceLocation LHS = getLocation(L); return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); } SourceLocation getLocation(LocalDeclID ID) const { return Reader.getSourceManager().getFileLoc( Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID))); } }; } // end anonymous namespace void ASTReader::FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl<Decl *> &Decls) { SourceManager &SM = getSourceManager(); llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File); if (I == FileDeclIDs.end()) return; FileDeclsInfo &DInfo = I->second; if (DInfo.Decls.empty()) return; SourceLocation BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset); SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length); DeclIDComp DIDComp(*this, *DInfo.Mod); ArrayRef<serialization::LocalDeclID>::iterator BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(), BeginLoc, DIDComp); if (BeginIt != DInfo.Decls.begin()) --BeginIt; // If we are pointing at a top-level decl inside an objc container, we need // to backtrack until we find it otherwise we will fail to report that the // region overlaps with an objc container. while (BeginIt != DInfo.Decls.begin() && GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt)) ->isTopLevelDeclInObjCContainer()) --BeginIt; ArrayRef<serialization::LocalDeclID>::iterator EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(), EndLoc, DIDComp); if (EndIt != DInfo.Decls.end()) ++EndIt; for (ArrayRef<serialization::LocalDeclID>::iterator DIt = BeginIt; DIt != EndIt; ++DIt) Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt))); } bool ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) { assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() && "DeclContext has no visible decls in storage"); if (!Name) return false; auto It = Lookups.find(DC); if (It == Lookups.end()) return false; Deserializing LookupResults(this); // Load the list of declarations. SmallVector<NamedDecl *, 64> Decls; for (DeclID ID : It->second.Table.find(Name)) { NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); if (ND->getDeclName() == Name) Decls.push_back(ND); } ++NumVisibleDeclContextsRead; SetExternalVisibleDeclsForName(DC, Name, Decls); return !Decls.empty(); } void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) { if (!DC->hasExternalVisibleStorage()) return; auto It = Lookups.find(DC); assert(It != Lookups.end() && "have external visible storage but no lookup tables"); DeclsMap Decls; for (DeclID ID : It->second.Table.findAll()) { NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); Decls[ND->getDeclName()].push_back(ND); } ++NumVisibleDeclContextsRead; for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) { SetExternalVisibleDeclsForName(DC, I->first, I->second); } const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false); } const serialization::reader::DeclContextLookupTable * ASTReader::getLoadedLookupTables(DeclContext *Primary) const { auto I = Lookups.find(Primary); return I == Lookups.end() ? nullptr : &I->second; } /// \brief Under non-PCH compilation the consumer receives the objc methods /// before receiving the implementation, and codegen depends on this. /// We simulate this by deserializing and passing to consumer the methods of the /// implementation before passing the deserialized implementation decl. static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer) { assert(ImplD && Consumer); for (auto *I : ImplD->methods()) Consumer->HandleInterestingDecl(DeclGroupRef(I)); Consumer->HandleInterestingDecl(DeclGroupRef(ImplD)); } void ASTReader::PassInterestingDeclToConsumer(Decl *D) { if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) PassObjCImplDeclToConsumer(ImplD, Consumer); else Consumer->HandleInterestingDecl(DeclGroupRef(D)); } void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { this->Consumer = Consumer; if (Consumer) PassInterestingDeclsToConsumer(); if (DeserializationListener) DeserializationListener->ReaderInitialized(this); } void ASTReader::PrintStats() { std::fprintf(stderr, "*** AST File Statistics:\n"); unsigned NumTypesLoaded = TypesLoaded.size(); unsigned NumDeclsLoaded = DeclsLoaded.size(); unsigned NumIdentifiersLoaded = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(), IdentifiersLoaded.end(), (IdentifierInfo *)nullptr); unsigned NumMacrosLoaded = MacrosLoaded.size(); unsigned NumSelectorsLoaded = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(), SelectorsLoaded.end(), Selector()); if (unsigned TotalNumSLocEntries = getTotalNumSLocs()) std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n", NumSLocEntriesRead, TotalNumSLocEntries, ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); if (!TypesLoaded.empty()) std::fprintf(stderr, " %u/%u types read (%f%%)\n", NumTypesLoaded, (unsigned)TypesLoaded.size(), ((float)NumTypesLoaded/TypesLoaded.size() * 100)); if (!DeclsLoaded.empty()) std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", NumDeclsLoaded, (unsigned)DeclsLoaded.size(), ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); if (!IdentifiersLoaded.empty()) std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); if (!MacrosLoaded.empty()) std::fprintf(stderr, " %u/%u macros read (%f%%)\n", NumMacrosLoaded, (unsigned)MacrosLoaded.size(), ((float)NumMacrosLoaded/MacrosLoaded.size() * 100)); if (!SelectorsLoaded.empty()) std::fprintf(stderr, " %u/%u selectors read (%f%%)\n", NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); if (TotalNumStatements) std::fprintf(stderr, " %u/%u statements read (%f%%)\n", NumStatementsRead, TotalNumStatements, ((float)NumStatementsRead/TotalNumStatements * 100)); if (TotalNumMacros) std::fprintf(stderr, " %u/%u macros read (%f%%)\n", NumMacrosRead, TotalNumMacros, ((float)NumMacrosRead/TotalNumMacros * 100)); if (TotalLexicalDeclContexts) std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n", NumLexicalDeclContextsRead, TotalLexicalDeclContexts, ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts * 100)); if (TotalVisibleDeclContexts) std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n", NumVisibleDeclContextsRead, TotalVisibleDeclContexts, ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts * 100)); if (TotalNumMethodPoolEntries) { std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n", NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries * 100)); } if (NumMethodPoolLookups) { std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n", NumMethodPoolHits, NumMethodPoolLookups, ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0)); } if (NumMethodPoolTableLookups) { std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n", NumMethodPoolTableHits, NumMethodPoolTableLookups, ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups * 100.0)); } if (NumIdentifierLookupHits) { std::fprintf(stderr, " %u / %u identifier table lookups succeeded (%f%%)\n", NumIdentifierLookupHits, NumIdentifierLookups, (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups); } if (GlobalIndex) { std::fprintf(stderr, "\n"); GlobalIndex->printStats(); } std::fprintf(stderr, "\n"); dump(); std::fprintf(stderr, "\n"); } template<typename Key, typename ModuleFile, unsigned InitialCapacity> LLVM_DUMP_METHOD static void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> &Map) { if (Map.begin() == Map.end()) return; typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType; llvm::errs() << Name << ":\n"; for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); I != IEnd; ++I) { llvm::errs() << " " << I->first << " -> " << I->second->FileName << "\n"; } } LLVM_DUMP_METHOD void ASTReader::dump() { llvm::errs() << "*** PCH/ModuleFile Remappings:\n"; dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap); dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap); dumpModuleIDMap("Global type map", GlobalTypeMap); dumpModuleIDMap("Global declaration map", GlobalDeclMap); dumpModuleIDMap("Global identifier map", GlobalIdentifierMap); dumpModuleIDMap("Global macro map", GlobalMacroMap); dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap); dumpModuleIDMap("Global selector map", GlobalSelectorMap); dumpModuleIDMap("Global preprocessed entity map", GlobalPreprocessedEntityMap); llvm::errs() << "\n*** PCH/Modules Loaded:"; for (ModuleFile &M : ModuleMgr) M.dump(); } /// Return the amount of memory used by memory buffers, breaking down /// by heap-backed versus mmap'ed memory. void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { for (ModuleFile &I : ModuleMgr) { if (llvm::MemoryBuffer *buf = I.Buffer) { size_t bytes = buf->getBufferSize(); switch (buf->getBufferKind()) { case llvm::MemoryBuffer::MemoryBuffer_Malloc: sizes.malloc_bytes += bytes; break; case llvm::MemoryBuffer::MemoryBuffer_MMap: sizes.mmap_bytes += bytes; break; } } } } void ASTReader::InitializeSema(Sema &S) { SemaObj = &S; S.addExternalSource(this); // Makes sure any declarations that were deserialized "too early" // still get added to the identifier's declaration chains. for (uint64_t ID : PreloadedDeclIDs) { NamedDecl *D = cast<NamedDecl>(GetDecl(ID)); pushExternalDeclIntoScope(D, D->getDeclName()); } PreloadedDeclIDs.clear(); // FIXME: What happens if these are changed by a module import? if (!FPPragmaOptions.empty()) { assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS"); SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]); } SemaObj->OpenCLFeatures.copy(OpenCLExtensions); SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap; SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap; UpdateSema(); } void ASTReader::UpdateSema() { assert(SemaObj && "no Sema to update"); // Load the offsets of the declarations that Sema references. // They will be lazily deserialized when needed. if (!SemaDeclRefs.empty()) { assert(SemaDeclRefs.size() % 3 == 0); for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) { if (!SemaObj->StdNamespace) SemaObj->StdNamespace = SemaDeclRefs[I]; if (!SemaObj->StdBadAlloc) SemaObj->StdBadAlloc = SemaDeclRefs[I+1]; if (!SemaObj->StdAlignValT) SemaObj->StdAlignValT = SemaDeclRefs[I+2]; } SemaDeclRefs.clear(); } // Update the state of pragmas. Use the same API as if we had encountered the // pragma in the source. if(OptimizeOffPragmaLocation.isValid()) SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation); if (PragmaMSStructState != -1) SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState); if (PointersToMembersPragmaLocation.isValid()) { SemaObj->ActOnPragmaMSPointersToMembers( (LangOptions::PragmaMSPointersToMembersKind) PragmaMSPointersToMembersState, PointersToMembersPragmaLocation); } SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth; if (PragmaPackCurrentValue) { // The bottom of the stack might have a default value. It must be adjusted // to the current value to ensure that the packing state is preserved after // popping entries that were included/imported from a PCH/module. bool DropFirst = false; if (!PragmaPackStack.empty() && PragmaPackStack.front().Location.isInvalid()) { assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue && "Expected a default alignment value"); SemaObj->PackStack.Stack.emplace_back( PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue, SemaObj->PackStack.CurrentPragmaLocation); DropFirst = true; } for (const auto &Entry : llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0)) SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value, Entry.Location); if (PragmaPackCurrentLocation.isInvalid()) { assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue && "Expected a default alignment value"); // Keep the current values. } else { SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue; SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation; } } } IdentifierInfo *ASTReader::get(StringRef Name) { // Note that we are loading an identifier. Deserializing AnIdentifier(this); IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, NumIdentifierLookups, NumIdentifierLookupHits); // We don't need to do identifier table lookups in C++ modules (we preload // all interesting declarations, and don't need to use the scope for name // lookups). Perform the lookup in PCH files, though, since we don't build // a complete initial identifier table if we're carrying on from a PCH. if (PP.getLangOpts().CPlusPlus) { for (auto F : ModuleMgr.pch_modules()) if (Visitor(*F)) break; } else { // If there is a global index, look there first to determine which modules // provably do not have any results for this identifier. GlobalModuleIndex::HitSet Hits; GlobalModuleIndex::HitSet *HitsPtr = nullptr; if (!loadGlobalIndex()) { if (GlobalIndex->lookupIdentifier(Name, Hits)) { HitsPtr = &Hits; } } ModuleMgr.visit(Visitor, HitsPtr); } IdentifierInfo *II = Visitor.getIdentifierInfo(); markIdentifierUpToDate(II); return II; } namespace clang { /// \brief An identifier-lookup iterator that enumerates all of the /// identifiers stored within a set of AST files. class ASTIdentifierIterator : public IdentifierIterator { /// \brief The AST reader whose identifiers are being enumerated. const ASTReader &Reader; /// \brief The current index into the chain of AST files stored in /// the AST reader. unsigned Index; /// \brief The current position within the identifier lookup table /// of the current AST file. ASTIdentifierLookupTable::key_iterator Current; /// \brief The end position within the identifier lookup table of /// the current AST file. ASTIdentifierLookupTable::key_iterator End; /// \brief Whether to skip any modules in the ASTReader. bool SkipModules; public: explicit ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules = false); StringRef Next() override; }; } // end namespace clang ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules) : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { } StringRef ASTIdentifierIterator::Next() { while (Current == End) { // If we have exhausted all of our AST files, we're done. if (Index == 0) return StringRef(); --Index; ModuleFile &F = Reader.ModuleMgr[Index]; if (SkipModules && F.isModule()) continue; ASTIdentifierLookupTable *IdTable = (ASTIdentifierLookupTable *)F.IdentifierLookupTable; Current = IdTable->key_begin(); End = IdTable->key_end(); } // We have any identifiers remaining in the current AST file; return // the next one. StringRef Result = *Current; ++Current; return Result; } namespace { /// A utility for appending two IdentifierIterators. class ChainedIdentifierIterator : public IdentifierIterator { std::unique_ptr<IdentifierIterator> Current; std::unique_ptr<IdentifierIterator> Queued; public: ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, std::unique_ptr<IdentifierIterator> Second) : Current(std::move(First)), Queued(std::move(Second)) {} StringRef Next() override { if (!Current) return StringRef(); StringRef result = Current->Next(); if (!result.empty()) return result; // Try the queued iterator, which may itself be empty. Current.reset(); std::swap(Current, Queued); return Next(); } }; } // end anonymous namespace. IdentifierIterator *ASTReader::getIdentifiers() { if (!loadGlobalIndex()) { std::unique_ptr<IdentifierIterator> ReaderIter( new ASTIdentifierIterator(*this, /*SkipModules=*/true)); std::unique_ptr<IdentifierIterator> ModulesIter( GlobalIndex->createIdentifierIterator()); return new ChainedIdentifierIterator(std::move(ReaderIter), std::move(ModulesIter)); } return new ASTIdentifierIterator(*this); } namespace clang { namespace serialization { class ReadMethodPoolVisitor { ASTReader &Reader; Selector Sel; unsigned PriorGeneration; unsigned InstanceBits; unsigned FactoryBits; bool InstanceHasMoreThanOneDecl; bool FactoryHasMoreThanOneDecl; SmallVector<ObjCMethodDecl *, 4> InstanceMethods; SmallVector<ObjCMethodDecl *, 4> FactoryMethods; public: ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration) : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration), InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false), FactoryHasMoreThanOneDecl(false) {} bool operator()(ModuleFile &M) { if (!M.SelectorLookupTable) return false; // If we've already searched this module file, skip it now. if (M.Generation <= PriorGeneration) return true; ++Reader.NumMethodPoolTableLookups; ASTSelectorLookupTable *PoolTable = (ASTSelectorLookupTable*)M.SelectorLookupTable; ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); if (Pos == PoolTable->end()) return false; ++Reader.NumMethodPoolTableHits; ++Reader.NumSelectorsRead; // FIXME: Not quite happy with the statistics here. We probably should // disable this tracking when called via LoadSelector. // Also, should entries without methods count as misses? ++Reader.NumMethodPoolEntriesRead; ASTSelectorLookupTrait::data_type Data = *Pos; if (Reader.DeserializationListener) Reader.DeserializationListener->SelectorRead(Data.ID, Sel); InstanceMethods.append(Data.Instance.begin(), Data.Instance.end()); FactoryMethods.append(Data.Factory.begin(), Data.Factory.end()); InstanceBits = Data.InstanceBits; FactoryBits = Data.FactoryBits; InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; return true; } /// \brief Retrieve the instance methods found by this visitor. ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { return InstanceMethods; } /// \brief Retrieve the instance methods found by this visitor. ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { return FactoryMethods; } unsigned getInstanceBits() const { return InstanceBits; } unsigned getFactoryBits() const { return FactoryBits; } bool instanceHasMoreThanOneDecl() const { return InstanceHasMoreThanOneDecl; } bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } }; } // end namespace serialization } // end namespace clang /// \brief Add the given set of methods to the method list. static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, ObjCMethodList &List) { for (unsigned I = 0, N = Methods.size(); I != N; ++I) { S.addMethodToGlobalList(&List, Methods[I]); } } void ASTReader::ReadMethodPool(Selector Sel) { // Get the selector generation and update it to the current generation. unsigned &Generation = SelectorGeneration[Sel]; unsigned PriorGeneration = Generation; Generation = getGenerationOrNull(); SelectorOutOfDate[Sel] = false; // Search for methods defined with this selector. ++NumMethodPoolLookups; ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); ModuleMgr.visit(Visitor); if (Visitor.getInstanceMethods().empty() && Visitor.getFactoryMethods().empty()) return; ++NumMethodPoolHits; if (!getSema()) return; Sema &S = *getSema(); Sema::GlobalMethodPool::iterator Pos = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first; Pos->second.first.setBits(Visitor.getInstanceBits()); Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); Pos->second.second.setBits(Visitor.getFactoryBits()); Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); // Add methods to the global pool *after* setting hasMoreThanOneDecl, since // when building a module we keep every method individually and may need to // update hasMoreThanOneDecl as we add the methods. addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first); addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second); } void ASTReader::updateOutOfDateSelector(Selector Sel) { if (SelectorOutOfDate[Sel]) ReadMethodPool(Sel); } void ASTReader::ReadKnownNamespaces( SmallVectorImpl<NamespaceDecl *> &Namespaces) { Namespaces.clear(); for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { if (NamespaceDecl *Namespace = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) Namespaces.push_back(Namespace); } } void ASTReader::ReadUndefinedButUsed( llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++])); SourceLocation Loc = SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]); Undefined.insert(std::make_pair(D, Loc)); } } void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & Exprs) { for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++])); uint64_t Count = DelayedDeleteExprs[Idx++]; for (uint64_t C = 0; C < Count; ++C) { SourceLocation DeleteLoc = SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]); const bool IsArrayForm = DelayedDeleteExprs[Idx++]; Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm)); } } } void ASTReader::ReadTentativeDefinitions( SmallVectorImpl<VarDecl *> &TentativeDefs) { for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I])); if (Var) TentativeDefs.push_back(Var); } TentativeDefinitions.clear(); } void ASTReader::ReadUnusedFileScopedDecls( SmallVectorImpl<const DeclaratorDecl *> &Decls) { for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { DeclaratorDecl *D = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); if (D) Decls.push_back(D); } UnusedFileScopedDecls.clear(); } void ASTReader::ReadDelegatingConstructors( SmallVectorImpl<CXXConstructorDecl *> &Decls) { for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { CXXConstructorDecl *D = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); if (D) Decls.push_back(D); } DelegatingCtorDecls.clear(); } void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])); if (D) Decls.push_back(D); } ExtVectorDecls.clear(); } void ASTReader::ReadUnusedLocalTypedefNameCandidates( llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; ++I) { TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( GetDecl(UnusedLocalTypedefNameCandidates[I])); if (D) Decls.insert(D); } UnusedLocalTypedefNameCandidates.clear(); } void ASTReader::ReadReferencedSelectors( SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) { if (ReferencedSelectorsData.empty()) return; // If there are @selector references added them to its pool. This is for // implementation of -Wselector. unsigned int DataSize = ReferencedSelectorsData.size()-1; unsigned I = 0; while (I < DataSize) { Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]); SourceLocation SelLoc = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]); Sels.push_back(std::make_pair(Sel, SelLoc)); } ReferencedSelectorsData.clear(); } void ASTReader::ReadWeakUndeclaredIdentifiers( SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) { if (WeakUndeclaredIdentifiers.empty()) return; for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { IdentifierInfo *WeakId = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); IdentifierInfo *AliasId = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); SourceLocation Loc = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]); bool Used = WeakUndeclaredIdentifiers[I++]; WeakInfo WI(AliasId, Loc); WI.setUsed(Used); WeakIDs.push_back(std::make_pair(WeakId, WI)); } WeakUndeclaredIdentifiers.clear(); } void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { ExternalVTableUse VT; VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++])); VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]); VT.DefinitionRequired = VTableUses[Idx++]; VTables.push_back(VT); } VTableUses.clear(); } void ASTReader::ReadPendingInstantiations( SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) { for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++])); SourceLocation Loc = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]); Pending.push_back(std::make_pair(D, Loc)); } PendingInstantiations.clear(); } void ASTReader::ReadLateParsedTemplates( llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> &LPTMap) { for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N; /* In loop */) { FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++])); auto LT = llvm::make_unique<LateParsedTemplate>(); LT->D = GetDecl(LateParsedTemplates[Idx++]); ModuleFile *F = getOwningModuleFile(LT->D); assert(F && "No module"); unsigned TokN = LateParsedTemplates[Idx++]; LT->Toks.reserve(TokN); for (unsigned T = 0; T < TokN; ++T) LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx)); LPTMap.insert(std::make_pair(FD, std::move(LT))); } LateParsedTemplates.clear(); } void ASTReader::LoadSelector(Selector Sel) { // It would be complicated to avoid reading the methods anyway. So don't. ReadMethodPool(Sel); } void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { assert(ID && "Non-zero identifier ID required"); assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range"); IdentifiersLoaded[ID - 1] = II; if (DeserializationListener) DeserializationListener->IdentifierRead(ID, II); } /// \brief Set the globally-visible declarations associated with the given /// identifier. /// /// If the AST reader is currently in a state where the given declaration IDs /// cannot safely be resolved, they are queued until it is safe to resolve /// them. /// /// \param II an IdentifierInfo that refers to one or more globally-visible /// declarations. /// /// \param DeclIDs the set of declaration IDs with the name @p II that are /// visible at global scope. /// /// \param Decls if non-null, this vector will be populated with the set of /// deserialized declarations. These declarations will not be pushed into /// scope. void ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl<uint32_t> &DeclIDs, SmallVectorImpl<Decl *> *Decls) { if (NumCurrentElementsDeserializing && !Decls) { PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end()); return; } for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { if (!SemaObj) { // Queue this declaration so that it will be added to the // translation unit scope and identifier's declaration chain // once a Sema object is known. PreloadedDeclIDs.push_back(DeclIDs[I]); continue; } NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); // If we're simply supposed to record the declarations, do so now. if (Decls) { Decls->push_back(D); continue; } // Introduce this declaration into the translation-unit scope // and add it to the declaration chain for this identifier, so // that (unqualified) name lookup will find it. pushExternalDeclIntoScope(D, II); } } IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { if (ID == 0) return nullptr; if (IdentifiersLoaded.empty()) { Error("no identifier table in AST file"); return nullptr; } ID -= 1; if (!IdentifiersLoaded[ID]) { GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1); assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map"); ModuleFile *M = I->second; unsigned Index = ID - M->BaseIdentifierID; const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index]; // All of the strings in the AST file are preceded by a 16-bit length. // Extract that 16-bit length to avoid having to execute strlen(). // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as // unsigned integers. This is important to avoid integer overflow when // we cast them to 'unsigned'. const unsigned char *StrLenPtr = (const unsigned char*) Str - 2; unsigned StrLen = (((unsigned) StrLenPtr[0]) | (((unsigned) StrLenPtr[1]) << 8)) - 1; auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen)); IdentifiersLoaded[ID] = &II; markIdentifierFromAST(*this, II); if (DeserializationListener) DeserializationListener->IdentifierRead(ID + 1, &II); } return IdentifiersLoaded[ID]; } IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) { return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID)); } IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) { if (LocalID < NUM_PREDEF_IDENT_IDS) return LocalID; if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::iterator I = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS); assert(I != M.IdentifierRemap.end() && "Invalid index into identifier index remap"); return LocalID + I->second; } MacroInfo *ASTReader::getMacro(MacroID ID) { if (ID == 0) return nullptr; if (!NumMacrosLoaded) { Error("no macro table in AST file"); return nullptr; } ID -= NUM_PREDEF_MACRO_IDS; auto FindRes = MacrosLoaded.find(ID); if (FindRes == MacrosLoaded.end()) { GlobalMacroMapType::iterator I = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS); assert(I != GlobalMacroMap.end() && "Corrupted global macro map"); ModuleFile *M = I->second; unsigned Index = ID - M->BaseMacroID; MacroInfo *MI = ReadMacroRecord(*M, M->MacroOffsets[Index]); MacrosLoaded.insert({ID, MI}); if (DeserializationListener) DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS, MI); } FindRes = MacrosLoaded.find(ID); if (FindRes == MacrosLoaded.end()) return nullptr; return FindRes->second; } MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { if (LocalID < NUM_PREDEF_MACRO_IDS) return LocalID; if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::iterator I = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS); assert(I != M.MacroRemap.end() && "Invalid index into macro index remap"); return LocalID + I->second; } serialization::SubmoduleID ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) { if (LocalID < NUM_PREDEF_SUBMODULE_IDS) return LocalID; if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::iterator I = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS); assert(I != M.SubmoduleRemap.end() && "Invalid index into submodule index remap"); return LocalID + I->second; } Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { assert(GlobalID == 0 && "Unhandled global submodule ID"); return nullptr; } if (GlobalID > SubmodulesLoaded.size()) { Error("submodule ID out of range in AST file"); return nullptr; } return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; } Module *ASTReader::getModule(unsigned ID) { return getSubmodule(ID); } ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) { if (ID & 1) { // It's a module, look it up by submodule ID. auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1)); return I == GlobalSubmoduleMap.end() ? nullptr : I->second; } else { // It's a prefix (preamble, PCH, ...). Look it up by index. unsigned IndexFromEnd = ID >> 1; assert(IndexFromEnd && "got reference to unknown module file"); return getModuleManager().pch_modules().end()[-IndexFromEnd]; } } unsigned ASTReader::getModuleFileID(ModuleFile *F) { if (!F) return 1; // For a file representing a module, use the submodule ID of the top-level // module as the file ID. For any other kind of file, the number of such // files loaded beforehand will be the same on reload. // FIXME: Is this true even if we have an explicit module file and a PCH? if (F->isModule()) return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; auto PCHModules = getModuleManager().pch_modules(); auto I = std::find(PCHModules.begin(), PCHModules.end(), F); assert(I != PCHModules.end() && "emitting reference to unknown file"); return (I - PCHModules.end()) << 1; } llvm::Optional<ExternalASTSource::ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) { if (const Module *M = getSubmodule(ID)) return ExternalASTSource::ASTSourceDescriptor(*M); // If there is only a single PCH, return it instead. // Chained PCH are not supported. const auto &PCHChain = ModuleMgr.pch_modules(); if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { ModuleFile &MF = ModuleMgr.getPrimaryModule(); StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName); StringRef FileName = llvm::sys::path::filename(MF.FileName); return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName, MF.Signature); } return None; } ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) { auto I = BodySource.find(FD); if (I == BodySource.end()) return EK_ReplyHazy; return I->second ? EK_Never : EK_Always; } Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { return DecodeSelector(getGlobalSelectorID(M, LocalID)); } Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { if (ID == 0) return Selector(); if (ID > SelectorsLoaded.size()) { Error("selector ID out of range in AST file"); return Selector(); } if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { // Load this selector from the selector table. GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); ModuleFile &M = *I->second; ASTSelectorLookupTrait Trait(*this, M); unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; SelectorsLoaded[ID - 1] = Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); if (DeserializationListener) DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); } return SelectorsLoaded[ID - 1]; } Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { return DecodeSelector(ID); } uint32_t ASTReader::GetNumExternalSelectors() { // ID 0 (the null selector) is considered an external selector. return getTotalNumSelectors() + 1; } serialization::SelectorID ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { if (LocalID < NUM_PREDEF_SELECTOR_IDS) return LocalID; if (!M.ModuleOffsetMap.empty()) ReadModuleOffsetMap(M); ContinuousRangeMap<uint32_t, int, 2>::iterator I = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS); assert(I != M.SelectorRemap.end() && "Invalid index into selector index remap"); return LocalID + I->second; } DeclarationName ASTReader::ReadDeclarationName(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++]; switch (Kind) { case DeclarationName::Identifier: return DeclarationName(GetIdentifierInfo(F, Record, Idx)); case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: return DeclarationName(ReadSelector(F, Record, Idx)); case DeclarationName::CXXConstructorName: return Context.DeclarationNames.getCXXConstructorName( Context.getCanonicalType(readType(F, Record, Idx))); case DeclarationName::CXXDestructorName: return Context.DeclarationNames.getCXXDestructorName( Context.getCanonicalType(readType(F, Record, Idx))); case DeclarationName::CXXDeductionGuideName: return Context.DeclarationNames.getCXXDeductionGuideName( ReadDeclAs<TemplateDecl>(F, Record, Idx)); case DeclarationName::CXXConversionFunctionName: return Context.DeclarationNames.getCXXConversionFunctionName( Context.getCanonicalType(readType(F, Record, Idx))); case DeclarationName::CXXOperatorName: return Context.DeclarationNames.getCXXOperatorName( (OverloadedOperatorKind)Record[Idx++]); case DeclarationName::CXXLiteralOperatorName: return Context.DeclarationNames.getCXXLiteralOperatorName( GetIdentifierInfo(F, Record, Idx)); case DeclarationName::CXXUsingDirective: return DeclarationName::getUsingDirectiveName(); } llvm_unreachable("Invalid NameKind!"); } void ASTReader::ReadDeclarationNameLoc(ModuleFile &F, DeclarationNameLoc &DNLoc, DeclarationName Name, const RecordData &Record, unsigned &Idx) { switch (Name.getNameKind()) { case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx); break; case DeclarationName::CXXOperatorName: DNLoc.CXXOperatorName.BeginOpNameLoc = ReadSourceLocation(F, Record, Idx).getRawEncoding(); DNLoc.CXXOperatorName.EndOpNameLoc = ReadSourceLocation(F, Record, Idx).getRawEncoding(); break; case DeclarationName::CXXLiteralOperatorName: DNLoc.CXXLiteralOperatorName.OpNameLoc = ReadSourceLocation(F, Record, Idx).getRawEncoding(); break; case DeclarationName::Identifier: case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: case DeclarationName::CXXUsingDirective: case DeclarationName::CXXDeductionGuideName: break; } } void ASTReader::ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo, const RecordData &Record, unsigned &Idx) { NameInfo.setName(ReadDeclarationName(F, Record, Idx)); NameInfo.setLoc(ReadSourceLocation(F, Record, Idx)); DeclarationNameLoc DNLoc; ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx); NameInfo.setInfo(DNLoc); } void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, const RecordData &Record, unsigned &Idx) { Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx); unsigned NumTPLists = Record[Idx++]; Info.NumTemplParamLists = NumTPLists; if (NumTPLists) { Info.TemplParamLists = new (getContext()) TemplateParameterList *[NumTPLists]; for (unsigned i = 0; i != NumTPLists; ++i) Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx); } } TemplateName ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++]; switch (Kind) { case TemplateName::Template: return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx)); case TemplateName::OverloadedTemplate: { unsigned size = Record[Idx++]; UnresolvedSet<8> Decls; while (size--) Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx)); return Context.getOverloadedTemplateName(Decls.begin(), Decls.end()); } case TemplateName::QualifiedTemplate: { NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx); bool hasTemplKeyword = Record[Idx++]; TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx); return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template); } case TemplateName::DependentTemplate: { NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx); if (Record[Idx++]) // isIdentifier return Context.getDependentTemplateName(NNS, GetIdentifierInfo(F, Record, Idx)); return Context.getDependentTemplateName(NNS, (OverloadedOperatorKind)Record[Idx++]); } case TemplateName::SubstTemplateTemplateParm: { TemplateTemplateParmDecl *param = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx); if (!param) return TemplateName(); TemplateName replacement = ReadTemplateName(F, Record, Idx); return Context.getSubstTemplateTemplateParm(param, replacement); } case TemplateName::SubstTemplateTemplateParmPack: { TemplateTemplateParmDecl *Param = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx); if (!Param) return TemplateName(); TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx); if (ArgPack.getKind() != TemplateArgument::Pack) return TemplateName(); return Context.getSubstTemplateTemplateParmPack(Param, ArgPack); } } llvm_unreachable("Unhandled template name kind!"); } TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F, const RecordData &Record, unsigned &Idx, bool Canonicalize) { ASTContext &Context = getContext(); if (Canonicalize) { // The caller wants a canonical template argument. Sometimes the AST only // wants template arguments in canonical form (particularly as the template // argument lists of template specializations) so ensure we preserve that // canonical form across serialization. TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false); return Context.getCanonicalTemplateArgument(Arg); } TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++]; switch (Kind) { case TemplateArgument::Null: return TemplateArgument(); case TemplateArgument::Type: return TemplateArgument(readType(F, Record, Idx)); case TemplateArgument::Declaration: { ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx); return TemplateArgument(D, readType(F, Record, Idx)); } case TemplateArgument::NullPtr: return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true); case TemplateArgument::Integral: { llvm::APSInt Value = ReadAPSInt(Record, Idx); QualType T = readType(F, Record, Idx); return TemplateArgument(Context, Value, T); } case TemplateArgument::Template: return TemplateArgument(ReadTemplateName(F, Record, Idx)); case TemplateArgument::TemplateExpansion: { TemplateName Name = ReadTemplateName(F, Record, Idx); Optional<unsigned> NumTemplateExpansions; if (unsigned NumExpansions = Record[Idx++]) NumTemplateExpansions = NumExpansions - 1; return TemplateArgument(Name, NumTemplateExpansions); } case TemplateArgument::Expression: return TemplateArgument(ReadExpr(F)); case TemplateArgument::Pack: { unsigned NumArgs = Record[Idx++]; TemplateArgument *Args = new (Context) TemplateArgument[NumArgs]; for (unsigned I = 0; I != NumArgs; ++I) Args[I] = ReadTemplateArgument(F, Record, Idx); return TemplateArgument(llvm::makeArrayRef(Args, NumArgs)); } } llvm_unreachable("Unhandled template argument kind!"); } TemplateParameterList * ASTReader::ReadTemplateParameterList(ModuleFile &F, const RecordData &Record, unsigned &Idx) { SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx); SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx); SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx); unsigned NumParams = Record[Idx++]; SmallVector<NamedDecl *, 16> Params; Params.reserve(NumParams); while (NumParams--) Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx)); // TODO: Concepts TemplateParameterList *TemplateParams = TemplateParameterList::Create( getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr); return TemplateParams; } void ASTReader:: ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs, ModuleFile &F, const RecordData &Record, unsigned &Idx, bool Canonicalize) { unsigned NumTemplateArgs = Record[Idx++]; TemplArgs.reserve(NumTemplateArgs); while (NumTemplateArgs--) TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize)); } /// \brief Read a UnresolvedSet structure. void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set, const RecordData &Record, unsigned &Idx) { unsigned NumDecls = Record[Idx++]; Set.reserve(getContext(), NumDecls); while (NumDecls--) { DeclID ID = ReadDeclID(F, Record, Idx); AccessSpecifier AS = (AccessSpecifier)Record[Idx++]; Set.addLazyDecl(getContext(), ID, AS); } } CXXBaseSpecifier ASTReader::ReadCXXBaseSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx) { bool isVirtual = static_cast<bool>(Record[Idx++]); bool isBaseOfClass = static_cast<bool>(Record[Idx++]); AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]); bool inheritConstructors = static_cast<bool>(Record[Idx++]); TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx); CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, EllipsisLoc); Result.setInheritConstructors(inheritConstructors); return Result; } CXXCtorInitializer ** ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); unsigned NumInitializers = Record[Idx++]; assert(NumInitializers && "wrote ctor initializers but have no inits"); auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; for (unsigned i = 0; i != NumInitializers; ++i) { TypeSourceInfo *TInfo = nullptr; bool IsBaseVirtual = false; FieldDecl *Member = nullptr; IndirectFieldDecl *IndirectMember = nullptr; CtorInitializerType Type = (CtorInitializerType)Record[Idx++]; switch (Type) { case CTOR_INITIALIZER_BASE: TInfo = GetTypeSourceInfo(F, Record, Idx); IsBaseVirtual = Record[Idx++]; break; case CTOR_INITIALIZER_DELEGATING: TInfo = GetTypeSourceInfo(F, Record, Idx); break; case CTOR_INITIALIZER_MEMBER: Member = ReadDeclAs<FieldDecl>(F, Record, Idx); break; case CTOR_INITIALIZER_INDIRECT_MEMBER: IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx); break; } SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx); Expr *Init = ReadExpr(F); SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx); SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx); CXXCtorInitializer *BOMInit; if (Type == CTOR_INITIALIZER_BASE) BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, RParenLoc, MemberOrEllipsisLoc); else if (Type == CTOR_INITIALIZER_DELEGATING) BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); else if (Member) BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc); else BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc); if (/*IsWritten*/Record[Idx++]) { unsigned SourceOrder = Record[Idx++]; BOMInit->setSourceOrder(SourceOrder); } CtorInitializers[i] = BOMInit; } return CtorInitializers; } NestedNameSpecifier * ASTReader::ReadNestedNameSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); unsigned N = Record[Idx++]; NestedNameSpecifier *NNS = nullptr, *Prev = nullptr; for (unsigned I = 0; I != N; ++I) { NestedNameSpecifier::SpecifierKind Kind = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; switch (Kind) { case NestedNameSpecifier::Identifier: { IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx); NNS = NestedNameSpecifier::Create(Context, Prev, II); break; } case NestedNameSpecifier::Namespace: { NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx); NNS = NestedNameSpecifier::Create(Context, Prev, NS); break; } case NestedNameSpecifier::NamespaceAlias: { NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx); NNS = NestedNameSpecifier::Create(Context, Prev, Alias); break; } case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { const Type *T = readType(F, Record, Idx).getTypePtrOrNull(); if (!T) return nullptr; bool Template = Record[Idx++]; NNS = NestedNameSpecifier::Create(Context, Prev, Template, T); break; } case NestedNameSpecifier::Global: { NNS = NestedNameSpecifier::GlobalSpecifier(Context); // No associated value, and there can't be a prefix. break; } case NestedNameSpecifier::Super: { CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx); NNS = NestedNameSpecifier::SuperSpecifier(Context, RD); break; } } Prev = NNS; } return NNS; } NestedNameSpecifierLoc ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx) { ASTContext &Context = getContext(); unsigned N = Record[Idx++]; NestedNameSpecifierLocBuilder Builder; for (unsigned I = 0; I != N; ++I) { NestedNameSpecifier::SpecifierKind Kind = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; switch (Kind) { case NestedNameSpecifier::Identifier: { IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); Builder.Extend(Context, II, Range.getBegin(), Range.getEnd()); break; } case NestedNameSpecifier::Namespace: { NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd()); break; } case NestedNameSpecifier::NamespaceAlias: { NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd()); break; } case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { bool Template = Record[Idx++]; TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx); if (!T) return NestedNameSpecifierLoc(); SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); // FIXME: 'template' keyword location not saved anywhere, so we fake it. Builder.Extend(Context, Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), T->getTypeLoc(), ColonColonLoc); break; } case NestedNameSpecifier::Global: { SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); Builder.MakeGlobal(Context, ColonColonLoc); break; } case NestedNameSpecifier::Super: { CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx); SourceRange Range = ReadSourceRange(F, Record, Idx); Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd()); break; } } } return Builder.getWithLocInContext(Context); } SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx) { SourceLocation beg = ReadSourceLocation(F, Record, Idx); SourceLocation end = ReadSourceLocation(F, Record, Idx); return SourceRange(beg, end); } /// \brief Read an integral value llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) { unsigned BitWidth = Record[Idx++]; unsigned NumWords = llvm::APInt::getNumWords(BitWidth); llvm::APInt Result(BitWidth, NumWords, &Record[Idx]); Idx += NumWords; return Result; } /// \brief Read a signed integral value llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) { bool isUnsigned = Record[Idx++]; return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned); } /// \brief Read a floating-point value llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, const llvm::fltSemantics &Sem, unsigned &Idx) { return llvm::APFloat(Sem, ReadAPInt(Record, Idx)); } // \brief Read a string std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) { unsigned Len = Record[Idx++]; std::string Result(Record.data() + Idx, Record.data() + Idx + Len); Idx += Len; return Result; } std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx) { std::string Filename = ReadString(Record, Idx); ResolveImportedPath(F, Filename); return Filename; } VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, unsigned &Idx) { unsigned Major = Record[Idx++]; unsigned Minor = Record[Idx++]; unsigned Subminor = Record[Idx++]; if (Minor == 0) return VersionTuple(Major); if (Subminor == 0) return VersionTuple(Major, Minor - 1); return VersionTuple(Major, Minor - 1, Subminor - 1); } CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx) { CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); return CXXTemporary::Create(getContext(), Decl); } DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { return Diag(CurrentImportLoc, DiagID); } DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { return Diags.Report(Loc, DiagID); } /// \brief Retrieve the identifier table associated with the /// preprocessor. IdentifierTable &ASTReader::getIdentifierTable() { return PP.getIdentifierTable(); } /// \brief Record that the given ID maps to the given switch-case /// statement. void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { assert((*CurrSwitchCaseStmts)[ID] == nullptr && "Already have a SwitchCase with this ID"); (*CurrSwitchCaseStmts)[ID] = SC; } /// \brief Retrieve the switch-case statement with the given ID. SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID"); return (*CurrSwitchCaseStmts)[ID]; } void ASTReader::ClearSwitchCaseIDs() { CurrSwitchCaseStmts->clear(); } void ASTReader::ReadComments() { ASTContext &Context = getContext(); std::vector<RawComment *> Comments; for (SmallVectorImpl<std::pair<BitstreamCursor, serialization::ModuleFile *> >::iterator I = CommentsCursors.begin(), E = CommentsCursors.end(); I != E; ++I) { Comments.clear(); BitstreamCursor &Cursor = I->first; serialization::ModuleFile &F = *I->second; SavedStreamPosition SavedPosition(Cursor); RecordData Record; while (true) { llvm::BitstreamEntry Entry = Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: // Handled for us already. case llvm::BitstreamEntry::Error: Error("malformed block record in AST file"); return; case llvm::BitstreamEntry::EndBlock: goto NextCursor; case llvm::BitstreamEntry::Record: // The interesting case. break; } // Read a record. Record.clear(); switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) { case COMMENTS_RAW_COMMENT: { unsigned Idx = 0; SourceRange SR = ReadSourceRange(F, Record, Idx); RawComment::CommentKind Kind = (RawComment::CommentKind) Record[Idx++]; bool IsTrailingComment = Record[Idx++]; bool IsAlmostTrailingComment = Record[Idx++]; Comments.push_back(new (Context) RawComment( SR, Kind, IsTrailingComment, IsAlmostTrailingComment, Context.getLangOpts().CommentOpts.ParseAllComments)); break; } } } NextCursor: // De-serialized SourceLocations get negative FileIDs for other modules, // potentially invalidating the original order. Sort it again. std::sort(Comments.begin(), Comments.end(), BeforeThanCompare<RawComment>(SourceMgr)); Context.Comments.addDeserializedComments(Comments); } } void ASTReader::visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref<void(const serialization::InputFile &IF, bool isSystem)> Visitor) { unsigned NumUserInputs = MF.NumUserInputFiles; unsigned NumInputs = MF.InputFilesLoaded.size(); assert(NumUserInputs <= NumInputs); unsigned N = IncludeSystem ? NumInputs : NumUserInputs; for (unsigned I = 0; I < N; ++I) { bool IsSystem = I >= NumUserInputs; InputFile IF = getInputFile(MF, I+1, Complain); Visitor(IF, IsSystem); } } void ASTReader::visitTopLevelModuleMaps( serialization::ModuleFile &MF, llvm::function_ref<void(const FileEntry *FE)> Visitor) { unsigned NumInputs = MF.InputFilesLoaded.size(); for (unsigned I = 0; I < NumInputs; ++I) { InputFileInfo IFI = readInputFileInfo(MF, I + 1); if (IFI.TopLevelModuleMap) // FIXME: This unnecessarily re-reads the InputFileInfo. if (auto *FE = getInputFile(MF, I + 1).getFile()) Visitor(FE); } } std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) { // If we know the owning module, use it. if (Module *M = D->getImportedOwningModule()) return M->getFullModuleName(); // Otherwise, use the name of the top-level module the decl is within. if (ModuleFile *M = getOwningModuleFile(D)) return M->ModuleName; // Not from a module. return ""; } void ASTReader::finishPendingActions() { while (!PendingIdentifierInfos.empty() || !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() || !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty()) { // If any identifiers with corresponding top-level declarations have // been loaded, load those declarations now. typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDeclsMap; TopLevelDeclsMap TopLevelDecls; while (!PendingIdentifierInfos.empty()) { IdentifierInfo *II = PendingIdentifierInfos.back().first; SmallVector<uint32_t, 4> DeclIDs = std::move(PendingIdentifierInfos.back().second); PendingIdentifierInfos.pop_back(); SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]); } // For each decl chain that we wanted to complete while deserializing, mark // it as "still needs to be completed". for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { markIncompleteDeclChain(PendingIncompleteDeclChains[I]); } PendingIncompleteDeclChains.clear(); // Load pending declaration chains. for (unsigned I = 0; I != PendingDeclChains.size(); ++I) loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second); PendingDeclChains.clear(); // Make the most recent of the top-level declarations visible. for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { IdentifierInfo *II = TLD->first; for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II); } } // Load any pending macro definitions. for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { IdentifierInfo *II = PendingMacroIDs.begin()[I].first; SmallVector<PendingMacroInfo, 2> GlobalIDs; GlobalIDs.swap(PendingMacroIDs.begin()[I].second); // Initialize the macro history from chained-PCHs ahead of module imports. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; ++IDIdx) { const PendingMacroInfo &Info = GlobalIDs[IDIdx]; if (!Info.M->isModule()) resolvePendingMacro(II, Info); } // Handle module imports. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; ++IDIdx) { const PendingMacroInfo &Info = GlobalIDs[IDIdx]; if (Info.M->isModule()) resolvePendingMacro(II, Info); } } PendingMacroIDs.clear(); // Wire up the DeclContexts for Decls that we delayed setting until // recursive loading is completed. while (!PendingDeclContextInfos.empty()) { PendingDeclContextInfo Info = PendingDeclContextInfos.front(); PendingDeclContextInfos.pop_front(); DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC)); DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC)); Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext()); } // Perform any pending declaration updates. while (!PendingUpdateRecords.empty()) { auto Update = PendingUpdateRecords.pop_back_val(); ReadingKindTracker ReadingKind(Read_Decl, *this); loadDeclUpdateRecords(Update); } } // At this point, all update records for loaded decls are in place, so any // fake class definitions should have become real. assert(PendingFakeDefinitionData.empty() && "faked up a class definition but never saw the real one"); // If we deserialized any C++ or Objective-C class definitions, any // Objective-C protocol definitions, or any redeclarable templates, make sure // that all redeclarations point to the definitions. Note that this can only // happen now, after the redeclaration chains have been fully wired. for (Decl *D : PendingDefinitions) { if (TagDecl *TD = dyn_cast<TagDecl>(D)) { if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { // Make sure that the TagType points at the definition. const_cast<TagType*>(TagT)->decl = TD; } if (auto RD = dyn_cast<CXXRecordDecl>(D)) { for (auto *R = getMostRecentExistingDecl(RD); R; R = R->getPreviousDecl()) { assert((R == D) == cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && "declaration thinks it's the definition but it isn't"); cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; } } continue; } if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) { // Make sure that the ObjCInterfaceType points at the definition. const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl)) ->Decl = ID; for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) cast<ObjCInterfaceDecl>(R)->Data = ID->Data; continue; } if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) { for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) cast<ObjCProtocolDecl>(R)->Data = PD->Data; continue; } auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl(); for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; } PendingDefinitions.clear(); // Load the bodies of any functions or methods we've encountered. We do // this now (delayed) so that we can be sure that the declaration chains // have been fully wired up (hasBody relies on this). // FIXME: We shouldn't require complete redeclaration chains here. for (PendingBodiesMap::iterator PB = PendingBodies.begin(), PBEnd = PendingBodies.end(); PB != PBEnd; ++PB) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) { // FIXME: Check for =delete/=default? // FIXME: Complain about ODR violations here? const FunctionDecl *Defn = nullptr; if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) { FD->setLazyBody(PB->second); } else mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD); continue; } ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first); if (!getContext().getLangOpts().Modules || !MD->hasBody()) MD->setLazyBody(PB->second); } PendingBodies.clear(); // Do some cleanup. for (auto *ND : PendingMergedDefinitionsToDeduplicate) getContext().deduplicateMergedDefinitonsFor(ND); PendingMergedDefinitionsToDeduplicate.clear(); } void ASTReader::diagnoseOdrViolations() { if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty()) return; // Trigger the import of the full definition of each class that had any // odr-merging problems, so we can produce better diagnostics for them. // These updates may in turn find and diagnose some ODR failures, so take // ownership of the set first. auto OdrMergeFailures = std::move(PendingOdrMergeFailures); PendingOdrMergeFailures.clear(); for (auto &Merge : OdrMergeFailures) { Merge.first->buildLookup(); Merge.first->decls_begin(); Merge.first->bases_begin(); Merge.first->vbases_begin(); for (auto *RD : Merge.second) { RD->decls_begin(); RD->bases_begin(); RD->vbases_begin(); } } // For each declaration from a merged context, check that the canonical // definition of that context also contains a declaration of the same // entity. // // Caution: this loop does things that might invalidate iterators into // PendingOdrMergeChecks. Don't turn this into a range-based for loop! while (!PendingOdrMergeChecks.empty()) { NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); // FIXME: Skip over implicit declarations for now. This matters for things // like implicitly-declared special member functions. This isn't entirely // correct; we can end up with multiple unmerged declarations of the same // implicit entity. if (D->isImplicit()) continue; DeclContext *CanonDef = D->getDeclContext(); bool Found = false; const Decl *DCanon = D->getCanonicalDecl(); for (auto RI : D->redecls()) { if (RI->getLexicalDeclContext() == CanonDef) { Found = true; break; } } if (Found) continue; // Quick check failed, time to do the slow thing. Note, we can't just // look up the name of D in CanonDef here, because the member that is // in CanonDef might not be found by name lookup (it might have been // replaced by a more recent declaration in the lookup table), and we // can't necessarily find it in the redeclaration chain because it might // be merely mergeable, not redeclarable. llvm::SmallVector<const NamedDecl*, 4> Candidates; for (auto *CanonMember : CanonDef->decls()) { if (CanonMember->getCanonicalDecl() == DCanon) { // This can happen if the declaration is merely mergeable and not // actually redeclarable (we looked for redeclarations earlier). // // FIXME: We should be able to detect this more efficiently, without // pulling in all of the members of CanonDef. Found = true; break; } if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) if (ND->getDeclName() == D->getDeclName()) Candidates.push_back(ND); } if (!Found) { // The AST doesn't like TagDecls becoming invalid after they've been // completed. We only really need to mark FieldDecls as invalid here. if (!isa<TagDecl>(D)) D->setInvalidDecl(); // Ensure we don't accidentally recursively enter deserialization while // we're producing our diagnostic. Deserializing RecursionGuard(this); std::string CanonDefModule = getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef)); Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) << D << getOwningModuleNameForDiagnostic(D) << CanonDef << CanonDefModule.empty() << CanonDefModule; if (Candidates.empty()) Diag(cast<Decl>(CanonDef)->getLocation(), diag::note_module_odr_violation_no_possible_decls) << D; else { for (unsigned I = 0, N = Candidates.size(); I != N; ++I) Diag(Candidates[I]->getLocation(), diag::note_module_odr_violation_possible_decl) << Candidates[I]; } DiagnosedOdrMergeFailures.insert(CanonDef); } } if (OdrMergeFailures.empty()) return; // Ensure we don't accidentally recursively enter deserialization while // we're producing our diagnostics. Deserializing RecursionGuard(this); // Issue any pending ODR-failure diagnostics. for (auto &Merge : OdrMergeFailures) { // If we've already pointed out a specific problem with this class, don't // bother issuing a general "something's different" diagnostic. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) continue; bool Diagnosed = false; CXXRecordDecl *FirstRecord = Merge.first; std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord); for (CXXRecordDecl *SecondRecord : Merge.second) { // Multiple different declarations got merged together; tell the user // where they came from. if (FirstRecord == SecondRecord) continue; std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord); using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>; DeclHashes FirstHashes; DeclHashes SecondHashes; ODRHash Hash; auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes, CXXRecordDecl *Record) { for (auto *D : Record->decls()) { // Due to decl merging, the first CXXRecordDecl is the parent of // Decls in both records. if (!ODRHash::isWhitelistedDecl(D, FirstRecord)) continue; Hash.clear(); Hash.AddSubDecl(D); Hashes.emplace_back(D, Hash.CalculateHash()); } }; PopulateHashes(FirstHashes, FirstRecord); PopulateHashes(SecondHashes, SecondRecord); // Used with err_module_odr_violation_mismatch_decl and // note_module_odr_violation_mismatch_decl // This list should be the same Decl's as in ODRHash::isWhiteListedDecl enum { EndOfClass, PublicSpecifer, PrivateSpecifer, ProtectedSpecifer, StaticAssert, Field, CXXMethod, TypeAlias, TypeDef, Var, Friend, Other } FirstDiffType = Other, SecondDiffType = Other; auto DifferenceSelector = [](Decl *D) { assert(D && "valid Decl required"); switch (D->getKind()) { default: return Other; case Decl::AccessSpec: switch (D->getAccess()) { case AS_public: return PublicSpecifer; case AS_private: return PrivateSpecifer; case AS_protected: return ProtectedSpecifer; case AS_none: break; } llvm_unreachable("Invalid access specifier"); case Decl::StaticAssert: return StaticAssert; case Decl::Field: return Field; case Decl::CXXMethod: case Decl::CXXConstructor: case Decl::CXXDestructor: return CXXMethod; case Decl::TypeAlias: return TypeAlias; case Decl::Typedef: return TypeDef; case Decl::Var: return Var; case Decl::Friend: return Friend; } }; Decl *FirstDecl = nullptr; Decl *SecondDecl = nullptr; auto FirstIt = FirstHashes.begin(); auto SecondIt = SecondHashes.begin(); // If there is a diagnoseable difference, FirstDiffType and // SecondDiffType will not be Other and FirstDecl and SecondDecl will be // filled in if not EndOfClass. while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) { if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() && FirstIt->second == SecondIt->second) { ++FirstIt; ++SecondIt; continue; } FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first; SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first; FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass; SecondDiffType = SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass; break; } if (FirstDiffType == Other || SecondDiffType == Other) { // Reaching this point means an unexpected Decl was encountered // or no difference was detected. This causes a generic error // message to be emitted. Diag(FirstRecord->getLocation(), diag::err_module_odr_violation_different_definitions) << FirstRecord << FirstModule.empty() << FirstModule; if (FirstDecl) { Diag(FirstDecl->getLocation(), diag::note_first_module_difference) << FirstRecord << FirstDecl->getSourceRange(); } Diag(SecondRecord->getLocation(), diag::note_module_odr_violation_different_definitions) << SecondModule; if (SecondDecl) { Diag(SecondDecl->getLocation(), diag::note_second_module_difference) << SecondDecl->getSourceRange(); } Diagnosed = true; break; } if (FirstDiffType != SecondDiffType) { SourceLocation FirstLoc; SourceRange FirstRange; if (FirstDiffType == EndOfClass) { FirstLoc = FirstRecord->getBraceRange().getEnd(); } else { FirstLoc = FirstIt->first->getLocation(); FirstRange = FirstIt->first->getSourceRange(); } Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl) << FirstRecord << FirstModule.empty() << FirstModule << FirstRange << FirstDiffType; SourceLocation SecondLoc; SourceRange SecondRange; if (SecondDiffType == EndOfClass) { SecondLoc = SecondRecord->getBraceRange().getEnd(); } else { SecondLoc = SecondDecl->getLocation(); SecondRange = SecondDecl->getSourceRange(); } Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl) << SecondModule << SecondRange << SecondDiffType; Diagnosed = true; break; } assert(FirstDiffType == SecondDiffType); // Used with err_module_odr_violation_mismatch_decl_diff and // note_module_odr_violation_mismatch_decl_diff enum ODRDeclDifference{ StaticAssertCondition, StaticAssertMessage, StaticAssertOnlyMessage, FieldName, FieldTypeName, FieldSingleBitField, FieldDifferentWidthBitField, FieldSingleMutable, FieldSingleInitializer, FieldDifferentInitializers, MethodName, MethodDeleted, MethodVirtual, MethodStatic, MethodVolatile, MethodConst, MethodInline, MethodNumberParameters, MethodParameterType, MethodParameterName, MethodParameterSingleDefaultArgument, MethodParameterDifferentDefaultArgument, TypedefName, TypedefType, VarName, VarType, VarSingleInitializer, VarDifferentInitializer, VarConstexpr, FriendTypeFunction, FriendType, FriendFunction, }; // These lambdas have the common portions of the ODR diagnostics. This // has the same return as Diag(), so addition parameters can be passed // in with operator<< auto ODRDiagError = [FirstRecord, &FirstModule, this]( SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) { return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff) << FirstRecord << FirstModule.empty() << FirstModule << Range << DiffType; }; auto ODRDiagNote = [&SecondModule, this]( SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) { return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff) << SecondModule << Range << DiffType; }; auto ComputeODRHash = [&Hash](const Stmt* S) { assert(S); Hash.clear(); Hash.AddStmt(S); return Hash.CalculateHash(); }; auto ComputeQualTypeODRHash = [&Hash](QualType Ty) { Hash.clear(); Hash.AddQualType(Ty); return Hash.CalculateHash(); }; switch (FirstDiffType) { case Other: case EndOfClass: case PublicSpecifer: case PrivateSpecifer: case ProtectedSpecifer: llvm_unreachable("Invalid diff type"); case StaticAssert: { StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl); StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl); Expr *FirstExpr = FirstSA->getAssertExpr(); Expr *SecondExpr = SecondSA->getAssertExpr(); unsigned FirstODRHash = ComputeODRHash(FirstExpr); unsigned SecondODRHash = ComputeODRHash(SecondExpr); if (FirstODRHash != SecondODRHash) { ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(), StaticAssertCondition); ODRDiagNote(SecondExpr->getLocStart(), SecondExpr->getSourceRange(), StaticAssertCondition); Diagnosed = true; break; } StringLiteral *FirstStr = FirstSA->getMessage(); StringLiteral *SecondStr = SecondSA->getMessage(); assert((FirstStr || SecondStr) && "Both messages cannot be empty"); if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) { SourceLocation FirstLoc, SecondLoc; SourceRange FirstRange, SecondRange; if (FirstStr) { FirstLoc = FirstStr->getLocStart(); FirstRange = FirstStr->getSourceRange(); } else { FirstLoc = FirstSA->getLocStart(); FirstRange = FirstSA->getSourceRange(); } if (SecondStr) { SecondLoc = SecondStr->getLocStart(); SecondRange = SecondStr->getSourceRange(); } else { SecondLoc = SecondSA->getLocStart(); SecondRange = SecondSA->getSourceRange(); } ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage) << (FirstStr == nullptr); ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage) << (SecondStr == nullptr); Diagnosed = true; break; } if (FirstStr && SecondStr && FirstStr->getString() != SecondStr->getString()) { ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(), StaticAssertMessage); ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(), StaticAssertMessage); Diagnosed = true; break; } break; } case Field: { FieldDecl *FirstField = cast<FieldDecl>(FirstDecl); FieldDecl *SecondField = cast<FieldDecl>(SecondDecl); IdentifierInfo *FirstII = FirstField->getIdentifier(); IdentifierInfo *SecondII = SecondField->getIdentifier(); if (FirstII->getName() != SecondII->getName()) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldName) << FirstII; ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldName) << SecondII; Diagnosed = true; break; } assert(getContext().hasSameType(FirstField->getType(), SecondField->getType())); QualType FirstType = FirstField->getType(); QualType SecondType = SecondField->getType(); if (ComputeQualTypeODRHash(FirstType) != ComputeQualTypeODRHash(SecondType)) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldTypeName) << FirstII << FirstType; ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldTypeName) << SecondII << SecondType; Diagnosed = true; break; } const bool IsFirstBitField = FirstField->isBitField(); const bool IsSecondBitField = SecondField->isBitField(); if (IsFirstBitField != IsSecondBitField) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldSingleBitField) << FirstII << IsFirstBitField; ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldSingleBitField) << SecondII << IsSecondBitField; Diagnosed = true; break; } if (IsFirstBitField && IsSecondBitField) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldDifferentWidthBitField) << FirstII << FirstField->getBitWidth()->getSourceRange(); ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldDifferentWidthBitField) << SecondII << SecondField->getBitWidth()->getSourceRange(); Diagnosed = true; break; } const bool IsFirstMutable = FirstField->isMutable(); const bool IsSecondMutable = SecondField->isMutable(); if (IsFirstMutable != IsSecondMutable) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldSingleMutable) << FirstII << IsFirstMutable; ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldSingleMutable) << SecondII << IsSecondMutable; Diagnosed = true; break; } const Expr *FirstInitializer = FirstField->getInClassInitializer(); const Expr *SecondInitializer = SecondField->getInClassInitializer(); if ((!FirstInitializer && SecondInitializer) || (FirstInitializer && !SecondInitializer)) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldSingleInitializer) << FirstII << (FirstInitializer != nullptr); ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldSingleInitializer) << SecondII << (SecondInitializer != nullptr); Diagnosed = true; break; } if (FirstInitializer && SecondInitializer) { unsigned FirstInitHash = ComputeODRHash(FirstInitializer); unsigned SecondInitHash = ComputeODRHash(SecondInitializer); if (FirstInitHash != SecondInitHash) { ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), FieldDifferentInitializers) << FirstII << FirstInitializer->getSourceRange(); ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), FieldDifferentInitializers) << SecondII << SecondInitializer->getSourceRange(); Diagnosed = true; break; } } break; } case CXXMethod: { enum { DiagMethod, DiagConstructor, DiagDestructor, } FirstMethodType, SecondMethodType; auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) { if (isa<CXXConstructorDecl>(D)) return DiagConstructor; if (isa<CXXDestructorDecl>(D)) return DiagDestructor; return DiagMethod; }; const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl); const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl); FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod); SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod); auto FirstName = FirstMethod->getDeclName(); auto SecondName = SecondMethod->getDeclName(); if (FirstMethodType != SecondMethodType || FirstName != SecondName) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodName) << FirstMethodType << FirstName; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodName) << SecondMethodType << SecondName; Diagnosed = true; break; } const bool FirstDeleted = FirstMethod->isDeleted(); const bool SecondDeleted = SecondMethod->isDeleted(); if (FirstDeleted != SecondDeleted) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodDeleted) << FirstMethodType << FirstName << FirstDeleted; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodDeleted) << SecondMethodType << SecondName << SecondDeleted; Diagnosed = true; break; } const bool FirstVirtual = FirstMethod->isVirtualAsWritten(); const bool SecondVirtual = SecondMethod->isVirtualAsWritten(); const bool FirstPure = FirstMethod->isPure(); const bool SecondPure = SecondMethod->isPure(); if ((FirstVirtual || SecondVirtual) && (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodVirtual) << FirstMethodType << FirstName << FirstPure << FirstVirtual; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodVirtual) << SecondMethodType << SecondName << SecondPure << SecondVirtual; Diagnosed = true; break; } // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging, // FirstDecl is the canonical Decl of SecondDecl, so the storage // class needs to be checked instead. const auto FirstStorage = FirstMethod->getStorageClass(); const auto SecondStorage = SecondMethod->getStorageClass(); const bool FirstStatic = FirstStorage == SC_Static; const bool SecondStatic = SecondStorage == SC_Static; if (FirstStatic != SecondStatic) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodStatic) << FirstMethodType << FirstName << FirstStatic; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodStatic) << SecondMethodType << SecondName << SecondStatic; Diagnosed = true; break; } const bool FirstVolatile = FirstMethod->isVolatile(); const bool SecondVolatile = SecondMethod->isVolatile(); if (FirstVolatile != SecondVolatile) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodVolatile) << FirstMethodType << FirstName << FirstVolatile; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodVolatile) << SecondMethodType << SecondName << SecondVolatile; Diagnosed = true; break; } const bool FirstConst = FirstMethod->isConst(); const bool SecondConst = SecondMethod->isConst(); if (FirstConst != SecondConst) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodConst) << FirstMethodType << FirstName << FirstConst; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodConst) << SecondMethodType << SecondName << SecondConst; Diagnosed = true; break; } const bool FirstInline = FirstMethod->isInlineSpecified(); const bool SecondInline = SecondMethod->isInlineSpecified(); if (FirstInline != SecondInline) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodInline) << FirstMethodType << FirstName << FirstInline; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodInline) << SecondMethodType << SecondName << SecondInline; Diagnosed = true; break; } const unsigned FirstNumParameters = FirstMethod->param_size(); const unsigned SecondNumParameters = SecondMethod->param_size(); if (FirstNumParameters != SecondNumParameters) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodNumberParameters) << FirstMethodType << FirstName << FirstNumParameters; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodNumberParameters) << SecondMethodType << SecondName << SecondNumParameters; Diagnosed = true; break; } // Need this status boolean to know when break out of the switch. bool ParameterMismatch = false; for (unsigned I = 0; I < FirstNumParameters; ++I) { const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I); const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I); QualType FirstParamType = FirstParam->getType(); QualType SecondParamType = SecondParam->getType(); if (FirstParamType != SecondParamType && ComputeQualTypeODRHash(FirstParamType) != ComputeQualTypeODRHash(SecondParamType)) { if (const DecayedType *ParamDecayedType = FirstParamType->getAs<DecayedType>()) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterType) << FirstMethodType << FirstName << (I + 1) << FirstParamType << true << ParamDecayedType->getOriginalType(); } else { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterType) << FirstMethodType << FirstName << (I + 1) << FirstParamType << false; } if (const DecayedType *ParamDecayedType = SecondParamType->getAs<DecayedType>()) { ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterType) << SecondMethodType << SecondName << (I + 1) << SecondParamType << true << ParamDecayedType->getOriginalType(); } else { ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterType) << SecondMethodType << SecondName << (I + 1) << SecondParamType << false; } ParameterMismatch = true; break; } DeclarationName FirstParamName = FirstParam->getDeclName(); DeclarationName SecondParamName = SecondParam->getDeclName(); if (FirstParamName != SecondParamName) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterName) << FirstMethodType << FirstName << (I + 1) << FirstParamName; ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterName) << SecondMethodType << SecondName << (I + 1) << SecondParamName; ParameterMismatch = true; break; } const Expr *FirstInit = FirstParam->getInit(); const Expr *SecondInit = SecondParam->getInit(); if ((FirstInit == nullptr) != (SecondInit == nullptr)) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterSingleDefaultArgument) << FirstMethodType << FirstName << (I + 1) << (FirstInit == nullptr) << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterSingleDefaultArgument) << SecondMethodType << SecondName << (I + 1) << (SecondInit == nullptr) << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); ParameterMismatch = true; break; } if (FirstInit && SecondInit && ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { ODRDiagError(FirstMethod->getLocation(), FirstMethod->getSourceRange(), MethodParameterDifferentDefaultArgument) << FirstMethodType << FirstName << (I + 1) << FirstInit->getSourceRange(); ODRDiagNote(SecondMethod->getLocation(), SecondMethod->getSourceRange(), MethodParameterDifferentDefaultArgument) << SecondMethodType << SecondName << (I + 1) << SecondInit->getSourceRange(); ParameterMismatch = true; break; } } if (ParameterMismatch) { Diagnosed = true; break; } break; } case TypeAlias: case TypeDef: { TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl); TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl); auto FirstName = FirstTD->getDeclName(); auto SecondName = SecondTD->getDeclName(); if (FirstName != SecondName) { ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(), TypedefName) << (FirstDiffType == TypeAlias) << FirstName; ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(), TypedefName) << (FirstDiffType == TypeAlias) << SecondName; Diagnosed = true; break; } QualType FirstType = FirstTD->getUnderlyingType(); QualType SecondType = SecondTD->getUnderlyingType(); if (ComputeQualTypeODRHash(FirstType) != ComputeQualTypeODRHash(SecondType)) { ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(), TypedefType) << (FirstDiffType == TypeAlias) << FirstName << FirstType; ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(), TypedefType) << (FirstDiffType == TypeAlias) << SecondName << SecondType; Diagnosed = true; break; } break; } case Var: { VarDecl *FirstVD = cast<VarDecl>(FirstDecl); VarDecl *SecondVD = cast<VarDecl>(SecondDecl); auto FirstName = FirstVD->getDeclName(); auto SecondName = SecondVD->getDeclName(); if (FirstName != SecondName) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarName) << FirstName; ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarName) << SecondName; Diagnosed = true; break; } QualType FirstType = FirstVD->getType(); QualType SecondType = SecondVD->getType(); if (ComputeQualTypeODRHash(FirstType) != ComputeQualTypeODRHash(SecondType)) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarType) << FirstName << FirstType; ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarType) << SecondName << SecondType; Diagnosed = true; break; } const Expr *FirstInit = FirstVD->getInit(); const Expr *SecondInit = SecondVD->getInit(); if ((FirstInit == nullptr) != (SecondInit == nullptr)) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarSingleInitializer) << FirstName << (FirstInit == nullptr) << (FirstInit ? FirstInit->getSourceRange(): SourceRange()); ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarSingleInitializer) << SecondName << (SecondInit == nullptr) << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); Diagnosed = true; break; } if (FirstInit && SecondInit && ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarDifferentInitializer) << FirstName << FirstInit->getSourceRange(); ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarDifferentInitializer) << SecondName << SecondInit->getSourceRange(); Diagnosed = true; break; } const bool FirstIsConstexpr = FirstVD->isConstexpr(); const bool SecondIsConstexpr = SecondVD->isConstexpr(); if (FirstIsConstexpr != SecondIsConstexpr) { ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), VarConstexpr) << FirstName << FirstIsConstexpr; ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), VarConstexpr) << SecondName << SecondIsConstexpr; Diagnosed = true; break; } break; } case Friend: { FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl); FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl); NamedDecl *FirstND = FirstFriend->getFriendDecl(); NamedDecl *SecondND = SecondFriend->getFriendDecl(); TypeSourceInfo *FirstTSI = FirstFriend->getFriendType(); TypeSourceInfo *SecondTSI = SecondFriend->getFriendType(); if (FirstND && SecondND) { ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(), FriendFunction) << FirstND; ODRDiagNote(SecondFriend->getFriendLoc(), SecondFriend->getSourceRange(), FriendFunction) << SecondND; Diagnosed = true; break; } if (FirstTSI && SecondTSI) { QualType FirstFriendType = FirstTSI->getType(); QualType SecondFriendType = SecondTSI->getType(); assert(ComputeQualTypeODRHash(FirstFriendType) != ComputeQualTypeODRHash(SecondFriendType)); ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(), FriendType) << FirstFriendType; ODRDiagNote(SecondFriend->getFriendLoc(), SecondFriend->getSourceRange(), FriendType) << SecondFriendType; Diagnosed = true; break; } ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(), FriendTypeFunction) << (FirstTSI == nullptr); ODRDiagNote(SecondFriend->getFriendLoc(), SecondFriend->getSourceRange(), FriendTypeFunction) << (SecondTSI == nullptr); Diagnosed = true; break; } } if (Diagnosed == true) continue; Diag(FirstDecl->getLocation(), diag::err_module_odr_violation_mismatch_decl_unknown) << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType << FirstDecl->getSourceRange(); Diag(SecondDecl->getLocation(), diag::note_module_odr_violation_mismatch_decl_unknown) << SecondModule << FirstDiffType << SecondDecl->getSourceRange(); Diagnosed = true; } if (!Diagnosed) { // All definitions are updates to the same declaration. This happens if a // module instantiates the declaration of a class template specialization // and two or more other modules instantiate its definition. // // FIXME: Indicate which modules had instantiations of this definition. // FIXME: How can this even happen? Diag(Merge.first->getLocation(), diag::err_module_odr_violation_different_instantiations) << Merge.first; } } } void ASTReader::StartedDeserializing() { if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) ReadTimer->startTimer(); } void ASTReader::FinishedDeserializing() { assert(NumCurrentElementsDeserializing && "FinishedDeserializing not paired with StartedDeserializing"); if (NumCurrentElementsDeserializing == 1) { // We decrease NumCurrentElementsDeserializing only after pending actions // are finished, to avoid recursively re-calling finishPendingActions(). finishPendingActions(); } --NumCurrentElementsDeserializing; if (NumCurrentElementsDeserializing == 0) { // Propagate exception specification updates along redeclaration chains. while (!PendingExceptionSpecUpdates.empty()) { auto Updates = std::move(PendingExceptionSpecUpdates); PendingExceptionSpecUpdates.clear(); for (auto Update : Updates) { ProcessingUpdatesRAIIObj ProcessingUpdates(*this); auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); auto ESI = FPT->getExtProtoInfo().ExceptionSpec; if (auto *Listener = getContext().getASTMutationListener()) Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); for (auto *Redecl : Update.second->redecls()) getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); } } if (ReadTimer) ReadTimer->stopTimer(); diagnoseOdrViolations(); // We are not in recursive loading, so it's safe to pass the "interesting" // decls to the consumer. if (Consumer) PassInterestingDeclsToConsumer(); } } void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { // Remove any fake results before adding any real ones. auto It = PendingFakeLookupResults.find(II); if (It != PendingFakeLookupResults.end()) { for (auto *ND : It->second) SemaObj->IdResolver.RemoveDecl(ND); // FIXME: this works around module+PCH performance issue. // Rather than erase the result from the map, which is O(n), just clear // the vector of NamedDecls. It->second.clear(); } } if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { SemaObj->TUScope->AddDecl(D); } else if (SemaObj->TUScope) { // Adding the decl to IdResolver may have failed because it was already in // (even though it was not added in scope). If it is already in, make sure // it gets in the scope as well. if (std::find(SemaObj->IdResolver.begin(Name), SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end()) SemaObj->TUScope->AddDecl(D); } } ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, StringRef isysroot, bool DisableValidation, bool AllowASTWithCompilerErrors, bool AllowConfigurationMismatch, bool ValidateSystemInputs, bool UseGlobalIndex, std::unique_ptr<llvm::Timer> ReadTimer) : Listener(DisableValidation ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) : cast<ASTReaderListener>(new PCHValidator(PP, *this))), SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), ContextObj(Context), ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr), PCMCache(PP.getPCMCache()), DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot), DisableValidation(DisableValidation), AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), AllowConfigurationMismatch(AllowConfigurationMismatch), ValidateSystemInputs(ValidateSystemInputs), UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { SourceMgr.setExternalSLocEntrySource(this); for (const auto &Ext : Extensions) { auto BlockName = Ext->getExtensionMetadata().BlockName; auto Known = ModuleFileExtensions.find(BlockName); if (Known != ModuleFileExtensions.end()) { Diags.Report(diag::warn_duplicate_module_file_extension) << BlockName; continue; } ModuleFileExtensions.insert({BlockName, Ext}); } } ASTReader::~ASTReader() { if (OwnsDeserializationListener) delete DeserializationListener; for (auto PStr: TokenLiteralDataLoaded) { delete PStr; } } IdentifierResolver &ASTReader::getIdResolver() { return SemaObj ? SemaObj->IdResolver : DummyIdResolver; } unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID) { Idx = 0; Record.clear(); return Cursor.readRecord(AbbrevID, Record); }
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/PrimitiveSet> #include <osg/BufferObject> #include <osg/State> #include <osg/Notify> using namespace osg; //////////////////////////////////////////////////////////////////////////////////////////////////////// // // PrimitiveSet // unsigned int PrimitiveSet::getNumPrimitives() const { switch(_mode) { case(POINTS): return getNumIndices(); case(LINES): return getNumIndices()/2; case(TRIANGLES): return getNumIndices()/3; case(QUADS): return getNumIndices()/4; case(LINE_STRIP): case(LINE_LOOP): case(TRIANGLE_STRIP): case(TRIANGLE_FAN): case(QUAD_STRIP): case(PATCHES): case(POLYGON): return (getNumIndices()>0) ? 1 : 0; } return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawArray // void DrawArrays::draw(State& state, bool) const { #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) GLenum mode = _mode; if (_mode==GL_QUADS) { state.drawQuads(_first, _count, _numInstances); return; } else if (mode==GL_POLYGON) { mode = GL_TRIANGLE_FAN; } else if (mode==GL_QUAD_STRIP) { mode = GL_TRIANGLE_STRIP; } if (_numInstances>=1) state.glDrawArraysInstanced(mode,_first,_count, _numInstances); else glDrawArrays(mode,_first,_count); #else if (_numInstances>=1) state.glDrawArraysInstanced(_mode,_first,_count, _numInstances); else glDrawArrays(_mode,_first,_count); #endif } void DrawArrays::accept(PrimitiveFunctor& functor) const { functor.drawArrays(_mode,_first,_count); } void DrawArrays::accept(PrimitiveIndexFunctor& functor) const { functor.drawArrays(_mode,_first,_count); } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawArrayLengths // unsigned int DrawArrayLengths::getNumPrimitives() const { switch(_mode) { case(POINTS): return getNumIndices(); case(LINES): return getNumIndices()/2; case(TRIANGLES): return getNumIndices()/3; case(QUADS): return getNumIndices()/4; case(LINE_STRIP): case(LINE_LOOP): case(TRIANGLE_STRIP): case(TRIANGLE_FAN): case(QUAD_STRIP): case(PATCHES): case(POLYGON): return size(); } return 0; } void DrawArrayLengths::draw(State& state, bool) const { GLenum mode = _mode; #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) if (_mode==GL_QUADS) { GLint first = _first; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { state.drawQuads(first, *itr, _numInstances); first += *itr; } return; } if (mode==GL_POLYGON) mode = GL_TRIANGLE_FAN; if (mode==GL_QUAD_STRIP) mode = GL_TRIANGLE_STRIP; #endif GLint first = _first; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { glDrawArrays(mode,first,*itr); first += *itr; } } void DrawArrayLengths::accept(PrimitiveFunctor& functor) const { GLint first = _first; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { functor.drawArrays(_mode,first,*itr); first += *itr; } } void DrawArrayLengths::accept(PrimitiveIndexFunctor& functor) const { GLint first = _first; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { functor.drawArrays(_mode,first,*itr); first += *itr; } } unsigned int DrawArrayLengths::getNumIndices() const { unsigned int count = 0; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { count += *itr; } return count; } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawElementsUByte // DrawElementsUByte::~DrawElementsUByte() { releaseGLObjects(); } void DrawElementsUByte::draw(State& state, bool useVertexBufferObjects) const { GLenum mode = _mode; #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) if (mode==GL_POLYGON) mode = GL_TRIANGLE_FAN; if (mode==GL_QUAD_STRIP) mode = GL_TRIANGLE_STRIP; #endif if (useVertexBufferObjects) { GLBufferObject* ebo = getOrCreateGLBufferObject(state.getContextID()); state.bindElementBufferObject(ebo); if (ebo) { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_BYTE, (const GLvoid *)(ebo->getOffset(getBufferIndex())), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_BYTE, (const GLvoid *)(ebo->getOffset(getBufferIndex()))); } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_BYTE, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_BYTE, &front()); } } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_BYTE, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_BYTE, &front()); } } void DrawElementsUByte::accept(PrimitiveFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUByte::accept(PrimitiveIndexFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUByte::offsetIndices(int offset) { for(iterator itr=begin(); itr!=end(); ++itr) { *itr += offset; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawElementsUShort // DrawElementsUShort::~DrawElementsUShort() { releaseGLObjects(); } void DrawElementsUShort::draw(State& state, bool useVertexBufferObjects) const { GLenum mode = _mode; #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) if (mode==GL_POLYGON) mode = GL_TRIANGLE_FAN; if (mode==GL_QUAD_STRIP) mode = GL_TRIANGLE_STRIP; #endif if (useVertexBufferObjects) { GLBufferObject* ebo = getOrCreateGLBufferObject(state.getContextID()); state.bindElementBufferObject(ebo); if (ebo) { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_SHORT, (const GLvoid *)(ebo->getOffset(getBufferIndex())), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_SHORT, (const GLvoid *)(ebo->getOffset(getBufferIndex()))); } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_SHORT, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_SHORT, &front()); } } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_SHORT, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_SHORT, &front()); } } void DrawElementsUShort::accept(PrimitiveFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUShort::accept(PrimitiveIndexFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUShort::offsetIndices(int offset) { for(iterator itr=begin(); itr!=end(); ++itr) { *itr += offset; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawElementsUInt // DrawElementsUInt::~DrawElementsUInt() { releaseGLObjects(); } void DrawElementsUInt::draw(State& state, bool useVertexBufferObjects) const { GLenum mode = _mode; #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) if (mode==GL_POLYGON) mode = GL_TRIANGLE_FAN; if (mode==GL_QUAD_STRIP) mode = GL_TRIANGLE_STRIP; #endif if (useVertexBufferObjects) { GLBufferObject* ebo = getOrCreateGLBufferObject(state.getContextID()); state.bindElementBufferObject(ebo); if (ebo) { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_INT, (const GLvoid *)(ebo->getOffset(getBufferIndex())), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_INT, (const GLvoid *)(ebo->getOffset(getBufferIndex()))); } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_INT, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_INT, &front()); } } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_INT, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_INT, &front()); } } void DrawElementsUInt::accept(PrimitiveFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUInt::accept(PrimitiveIndexFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUInt::offsetIndices(int offset) { for(iterator itr=begin(); itr!=end(); ++itr) { *itr += offset; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // MultiDrawArrays // #ifdef OSG_HAS_MULTIDRAWARRAYS void MultiDrawArrays::draw(osg::State& state, bool) const { // OSG_NOTICE<<"osg::MultiDrawArrays::draw"<<std::endl; GLExtensions* ext = state.get<GLExtensions>(); if (ext->glMultiDrawArrays) { GLsizei primcount = std::min(_firsts.size(), _counts.size()); ext->glMultiDrawArrays(_mode, &_firsts.front(), &_counts.front(), primcount); } } void MultiDrawArrays::accept(PrimitiveFunctor& functor) const { unsigned int primcount = std::min(_firsts.size(), _counts.size()); for(unsigned int i=0; i<primcount; ++i) { functor.drawArrays(_mode, _firsts[i], _counts[i]); } } void MultiDrawArrays::accept(PrimitiveIndexFunctor& functor) const { unsigned int primcount = std::min(_firsts.size(), _counts.size()); for(unsigned int i=0; i<primcount; ++i) { functor.drawArrays(_mode, _firsts[i], _counts[i]); } } unsigned int MultiDrawArrays::getNumIndices() const { unsigned int total=0; for(Counts::const_iterator itr = _counts.begin(); itr!=_counts.end(); ++itr) { total += *itr; } return total; } unsigned int MultiDrawArrays::index(unsigned int pos) const { unsigned int i; for(i=0; i<_counts.size(); ++i) { unsigned int count = _counts[i]; if (pos<count) break; pos -= count; } if (i>=_firsts.size()) return 0; return _firsts[i] + pos; } void MultiDrawArrays::offsetIndices(int offset) { for(Firsts::iterator itr = _firsts.begin(); itr!=_firsts.end(); ++itr) { *itr += offset; } } unsigned int MultiDrawArrays::getNumPrimitives() const { switch(_mode) { case(POINTS): return getNumIndices(); case(LINES): return getNumIndices()/2; case(TRIANGLES): return getNumIndices()/3; case(QUADS): return getNumIndices()/4; case(LINE_STRIP): case(LINE_LOOP): case(TRIANGLE_STRIP): case(TRIANGLE_FAN): case(QUAD_STRIP): case(PATCHES): case(POLYGON): { unsigned int primcount = std::min(_firsts.size(), _counts.size()); return primcount; } } return 0; } void MultiDrawArrays::add(GLint first, GLsizei count) { _firsts.push_back(first); _counts.push_back(count); } #endif Update PrimitiveSet.cpp /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/PrimitiveSet> #include <osg/BufferObject> #include <osg/State> #include <osg/Notify> #include <algorithm> using namespace osg; //////////////////////////////////////////////////////////////////////////////////////////////////////// // // PrimitiveSet // unsigned int PrimitiveSet::getNumPrimitives() const { switch(_mode) { case(POINTS): return getNumIndices(); case(LINES): return getNumIndices()/2; case(TRIANGLES): return getNumIndices()/3; case(QUADS): return getNumIndices()/4; case(LINE_STRIP): case(LINE_LOOP): case(TRIANGLE_STRIP): case(TRIANGLE_FAN): case(QUAD_STRIP): case(PATCHES): case(POLYGON): return (getNumIndices()>0) ? 1 : 0; } return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawArray // void DrawArrays::draw(State& state, bool) const { #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) GLenum mode = _mode; if (_mode==GL_QUADS) { state.drawQuads(_first, _count, _numInstances); return; } else if (mode==GL_POLYGON) { mode = GL_TRIANGLE_FAN; } else if (mode==GL_QUAD_STRIP) { mode = GL_TRIANGLE_STRIP; } if (_numInstances>=1) state.glDrawArraysInstanced(mode,_first,_count, _numInstances); else glDrawArrays(mode,_first,_count); #else if (_numInstances>=1) state.glDrawArraysInstanced(_mode,_first,_count, _numInstances); else glDrawArrays(_mode,_first,_count); #endif } void DrawArrays::accept(PrimitiveFunctor& functor) const { functor.drawArrays(_mode,_first,_count); } void DrawArrays::accept(PrimitiveIndexFunctor& functor) const { functor.drawArrays(_mode,_first,_count); } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawArrayLengths // unsigned int DrawArrayLengths::getNumPrimitives() const { switch(_mode) { case(POINTS): return getNumIndices(); case(LINES): return getNumIndices()/2; case(TRIANGLES): return getNumIndices()/3; case(QUADS): return getNumIndices()/4; case(LINE_STRIP): case(LINE_LOOP): case(TRIANGLE_STRIP): case(TRIANGLE_FAN): case(QUAD_STRIP): case(PATCHES): case(POLYGON): return size(); } return 0; } void DrawArrayLengths::draw(State& state, bool) const { GLenum mode = _mode; #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) if (_mode==GL_QUADS) { GLint first = _first; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { state.drawQuads(first, *itr, _numInstances); first += *itr; } return; } if (mode==GL_POLYGON) mode = GL_TRIANGLE_FAN; if (mode==GL_QUAD_STRIP) mode = GL_TRIANGLE_STRIP; #endif GLint first = _first; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { glDrawArrays(mode,first,*itr); first += *itr; } } void DrawArrayLengths::accept(PrimitiveFunctor& functor) const { GLint first = _first; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { functor.drawArrays(_mode,first,*itr); first += *itr; } } void DrawArrayLengths::accept(PrimitiveIndexFunctor& functor) const { GLint first = _first; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { functor.drawArrays(_mode,first,*itr); first += *itr; } } unsigned int DrawArrayLengths::getNumIndices() const { unsigned int count = 0; for(vector_type::const_iterator itr=begin(); itr!=end(); ++itr) { count += *itr; } return count; } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawElementsUByte // DrawElementsUByte::~DrawElementsUByte() { releaseGLObjects(); } void DrawElementsUByte::draw(State& state, bool useVertexBufferObjects) const { GLenum mode = _mode; #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) if (mode==GL_POLYGON) mode = GL_TRIANGLE_FAN; if (mode==GL_QUAD_STRIP) mode = GL_TRIANGLE_STRIP; #endif if (useVertexBufferObjects) { GLBufferObject* ebo = getOrCreateGLBufferObject(state.getContextID()); state.bindElementBufferObject(ebo); if (ebo) { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_BYTE, (const GLvoid *)(ebo->getOffset(getBufferIndex())), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_BYTE, (const GLvoid *)(ebo->getOffset(getBufferIndex()))); } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_BYTE, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_BYTE, &front()); } } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_BYTE, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_BYTE, &front()); } } void DrawElementsUByte::accept(PrimitiveFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUByte::accept(PrimitiveIndexFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUByte::offsetIndices(int offset) { for(iterator itr=begin(); itr!=end(); ++itr) { *itr += offset; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawElementsUShort // DrawElementsUShort::~DrawElementsUShort() { releaseGLObjects(); } void DrawElementsUShort::draw(State& state, bool useVertexBufferObjects) const { GLenum mode = _mode; #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) if (mode==GL_POLYGON) mode = GL_TRIANGLE_FAN; if (mode==GL_QUAD_STRIP) mode = GL_TRIANGLE_STRIP; #endif if (useVertexBufferObjects) { GLBufferObject* ebo = getOrCreateGLBufferObject(state.getContextID()); state.bindElementBufferObject(ebo); if (ebo) { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_SHORT, (const GLvoid *)(ebo->getOffset(getBufferIndex())), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_SHORT, (const GLvoid *)(ebo->getOffset(getBufferIndex()))); } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_SHORT, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_SHORT, &front()); } } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_SHORT, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_SHORT, &front()); } } void DrawElementsUShort::accept(PrimitiveFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUShort::accept(PrimitiveIndexFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUShort::offsetIndices(int offset) { for(iterator itr=begin(); itr!=end(); ++itr) { *itr += offset; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // DrawElementsUInt // DrawElementsUInt::~DrawElementsUInt() { releaseGLObjects(); } void DrawElementsUInt::draw(State& state, bool useVertexBufferObjects) const { GLenum mode = _mode; #if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) if (mode==GL_POLYGON) mode = GL_TRIANGLE_FAN; if (mode==GL_QUAD_STRIP) mode = GL_TRIANGLE_STRIP; #endif if (useVertexBufferObjects) { GLBufferObject* ebo = getOrCreateGLBufferObject(state.getContextID()); state.bindElementBufferObject(ebo); if (ebo) { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_INT, (const GLvoid *)(ebo->getOffset(getBufferIndex())), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_INT, (const GLvoid *)(ebo->getOffset(getBufferIndex()))); } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_INT, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_INT, &front()); } } else { if (_numInstances>=1) state.glDrawElementsInstanced(mode, size(), GL_UNSIGNED_INT, &front(), _numInstances); else glDrawElements(mode, size(), GL_UNSIGNED_INT, &front()); } } void DrawElementsUInt::accept(PrimitiveFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUInt::accept(PrimitiveIndexFunctor& functor) const { if (!empty()) functor.drawElements(_mode,size(),&front()); } void DrawElementsUInt::offsetIndices(int offset) { for(iterator itr=begin(); itr!=end(); ++itr) { *itr += offset; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // MultiDrawArrays // #ifdef OSG_HAS_MULTIDRAWARRAYS void MultiDrawArrays::draw(osg::State& state, bool) const { // OSG_NOTICE<<"osg::MultiDrawArrays::draw"<<std::endl; GLExtensions* ext = state.get<GLExtensions>(); if (ext->glMultiDrawArrays) { GLsizei primcount = std::min(_firsts.size(), _counts.size()); ext->glMultiDrawArrays(_mode, &_firsts.front(), &_counts.front(), primcount); } } void MultiDrawArrays::accept(PrimitiveFunctor& functor) const { unsigned int primcount = std::min(_firsts.size(), _counts.size()); for(unsigned int i=0; i<primcount; ++i) { functor.drawArrays(_mode, _firsts[i], _counts[i]); } } void MultiDrawArrays::accept(PrimitiveIndexFunctor& functor) const { unsigned int primcount = std::min(_firsts.size(), _counts.size()); for(unsigned int i=0; i<primcount; ++i) { functor.drawArrays(_mode, _firsts[i], _counts[i]); } } unsigned int MultiDrawArrays::getNumIndices() const { unsigned int total=0; for(Counts::const_iterator itr = _counts.begin(); itr!=_counts.end(); ++itr) { total += *itr; } return total; } unsigned int MultiDrawArrays::index(unsigned int pos) const { unsigned int i; for(i=0; i<_counts.size(); ++i) { unsigned int count = _counts[i]; if (pos<count) break; pos -= count; } if (i>=_firsts.size()) return 0; return _firsts[i] + pos; } void MultiDrawArrays::offsetIndices(int offset) { for(Firsts::iterator itr = _firsts.begin(); itr!=_firsts.end(); ++itr) { *itr += offset; } } unsigned int MultiDrawArrays::getNumPrimitives() const { switch(_mode) { case(POINTS): return getNumIndices(); case(LINES): return getNumIndices()/2; case(TRIANGLES): return getNumIndices()/3; case(QUADS): return getNumIndices()/4; case(LINE_STRIP): case(LINE_LOOP): case(TRIANGLE_STRIP): case(TRIANGLE_FAN): case(QUAD_STRIP): case(PATCHES): case(POLYGON): { unsigned int primcount = std::min(_firsts.size(), _counts.size()); return primcount; } } return 0; } void MultiDrawArrays::add(GLint first, GLsizei count) { _firsts.push_back(first); _counts.push_back(count); } #endif
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*++ Module Name: module.c Abstract: Implementation of module related functions in the Win32 API --*/ #include "pal/thread.hpp" #include "pal/malloc.hpp" #include "pal/file.hpp" #include "pal/palinternal.h" #include "pal/dbgmsg.h" #include "pal/module.h" #include "pal/cs.hpp" #include "pal/process.h" #include "pal/file.h" #include "pal/utils.h" #include "pal/init.h" #include "pal/modulename.h" #include "pal/misc.h" #include "pal/virtual.h" #include "pal/map.hpp" #include "pal/stackstring.hpp" #include <sys/param.h> #include <errno.h> #include <string.h> #include <limits.h> #if NEED_DLCOMPAT #include "dlcompat.h" #else // NEED_DLCOMPAT #include <dlfcn.h> #endif // NEED_DLCOMPAT #if HAVE_ALLOCA_H #include <alloca.h> #endif // HAVE_ALLOCA_H #ifdef __APPLE__ #include <mach-o/dyld.h> #include <mach-o/loader.h> #endif // __APPLE__ #include <sys/types.h> #include <sys/mman.h> #if defined(__LINUX__) &&!defined(__ANDROID__) #include <gnu/lib-names.h> #endif using namespace CorUnix; SET_DEFAULT_DEBUG_CHANNEL(LOADER); // In safemath.h, Template SafeInt uses macro _ASSERTE, which need to use variable // defdbgchan defined by SET_DEFAULT_DEBUG_CHANNEL. Therefore, the include statement // should be placed after the SET_DEFAULT_DEBUG_CHANNEL(LOADER) #include <safemath.h> /* macro definitions **********************************************************/ /* get the full name of a module if available, and the short name otherwise*/ #define MODNAME(x) ((x)->lib_name) /* Which path should FindLibrary search? */ #if defined(__APPLE__) #define LIBSEARCHPATH "DYLD_LIBRARY_PATH" #else #define LIBSEARCHPATH "LD_LIBRARY_PATH" #endif #define LIBC_NAME_WITHOUT_EXTENSION "libc" /* static variables ***********************************************************/ /* critical section that regulates access to the module list */ CRITICAL_SECTION module_critsec; /* always the first, in the in-load-order list */ MODSTRUCT exe_module; MODSTRUCT *pal_module = nullptr; char * g_szCoreCLRPath = nullptr; size_t g_cbszCoreCLRPath = MAX_LONGPATH * sizeof(char); int MaxWCharToAcpLength = 3; /* static function declarations ***********************************************/ template<class TChar> static bool LOADVerifyLibraryPath(const TChar *libraryPath); static bool LOADConvertLibraryPathWideStringToMultibyteString( LPCWSTR wideLibraryPath, LPSTR multibyteLibraryPath, INT *multibyteLibraryPathLengthRef); static BOOL LOADValidateModule(MODSTRUCT *module); static LPWSTR LOADGetModuleFileName(MODSTRUCT *module); static MODSTRUCT *LOADAddModule(void *dl_handle, LPCSTR libraryNameOrPath); static void *LOADLoadLibraryDirect(LPCSTR libraryNameOrPath); static BOOL LOADFreeLibrary(MODSTRUCT *module, BOOL fCallDllMain); static HMODULE LOADRegisterLibraryDirect(void *dl_handle, LPCSTR libraryNameOrPath, BOOL fDynamic); static HMODULE LOADLoadLibrary(LPCSTR shortAsciiName, BOOL fDynamic); static BOOL LOADCallDllMainSafe(MODSTRUCT *module, DWORD dwReason, LPVOID lpReserved); /* API function definitions ***************************************************/ /*++ Function: LoadLibraryA See MSDN doc. --*/ HMODULE PALAPI LoadLibraryA( IN LPCSTR lpLibFileName) { return LoadLibraryExA(lpLibFileName, nullptr, 0); } /*++ Function: LoadLibraryW See MSDN doc. --*/ HMODULE PALAPI LoadLibraryW( IN LPCWSTR lpLibFileName) { return LoadLibraryExW(lpLibFileName, nullptr, 0); } /*++ Function: LoadLibraryExA See MSDN doc. --*/ HMODULE PALAPI LoadLibraryExA( IN LPCSTR lpLibFileName, IN /*Reserved*/ HANDLE hFile, IN DWORD dwFlags) { if (dwFlags!= 0) { // UNIXTODO: Implement this! ASSERT("Needs Implementation!!!"); return nullptr; } LPSTR lpstr = nullptr; HMODULE hModule = nullptr; PERF_ENTRY(LoadLibraryA); ENTRY("LoadLibraryExA (lpLibFileName=%p (%s)) \n", (lpLibFileName)? lpLibFileName : "NULL", (lpLibFileName)? lpLibFileName : "NULL"); if (!LOADVerifyLibraryPath(lpLibFileName)) { goto Done; } /* do the Dos/Unix conversion on our own copy of the name */ lpstr = InternalStrdup(lpLibFileName); if (!lpstr) { ERROR("InternalStrdup failure!\n"); SetLastError(ERROR_NOT_ENOUGH_MEMORY); goto Done; } FILEDosToUnixPathA(lpstr); hModule = LOADLoadLibrary(lpstr, TRUE); /* let LOADLoadLibrary call SetLastError */ Done: if (lpstr!= nullptr) { InternalFree(lpstr); } LOGEXIT("LoadLibraryExA returns HMODULE %p\n", hModule); PERF_EXIT(LoadLibraryExA); return hModule; } /*++ Function: LoadLibraryExW See MSDN doc. --*/ HMODULE PALAPI LoadLibraryExW( IN LPCWSTR lpLibFileName, IN /*Reserved*/ HANDLE hFile, IN DWORD dwFlags) { if (dwFlags!= 0) { // UNIXTODO: Implement this! ASSERT("Needs Implementation!!!"); return nullptr; } CHAR * lpstr; INT name_length; PathCharString pathstr; HMODULE hModule = nullptr; PERF_ENTRY(LoadLibraryExW); ENTRY("LoadLibraryExW (lpLibFileName=%p (%S)) \n", lpLibFileName? lpLibFileName : W16_NULLSTRING, lpLibFileName? lpLibFileName : W16_NULLSTRING); if (!LOADVerifyLibraryPath(lpLibFileName)) { goto done; } lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLength); if (nullptr == lpstr) { goto done; } if (!LOADConvertLibraryPathWideStringToMultibyteString(lpLibFileName, lpstr, &name_length)) { goto done; } /* do the Dos/Unix conversion on our own copy of the name */ FILEDosToUnixPathA(lpstr); pathstr.CloseBuffer(name_length); /* let LOADLoadLibrary call SetLastError in case of failure */ hModule = LOADLoadLibrary(lpstr, TRUE); done: LOGEXIT("LoadLibraryExW returns HMODULE %p\n", hModule); PERF_EXIT(LoadLibraryExW); return hModule; } /*++ Function: GetProcAddress See MSDN doc. --*/ FARPROC PALAPI GetProcAddress( IN HMODULE hModule, IN LPCSTR lpProcName) { MODSTRUCT *module; FARPROC ProcAddress = nullptr; LPCSTR symbolName = lpProcName; PERF_ENTRY(GetProcAddress); ENTRY("GetProcAddress (hModule=%p, lpProcName=%p (%s))\n", hModule, lpProcName? lpProcName : "NULL", lpProcName? lpProcName : "NULL"); LockModuleList(); module = (MODSTRUCT *) hModule; /* parameter validation */ if ((lpProcName == nullptr) || (*lpProcName == '\0')) { TRACE("No function name given\n"); SetLastError(ERROR_INVALID_PARAMETER); goto done; } if (!LOADValidateModule(module)) { TRACE("Invalid module handle %p\n", hModule); SetLastError(ERROR_INVALID_HANDLE); goto done; } /* try to assert on attempt to locate symbol by ordinal */ /* this can't be an exact test for HIWORD((DWORD)lpProcName) == 0 because of the address range reserved for ordinals contain can be a valid string address on non-Windows systems */ if ((DWORD_PTR)lpProcName < VIRTUAL_PAGE_SIZE) { ASSERT("Attempt to locate symbol by ordinal?!\n"); } // Get the symbol's address. // If we're looking for a symbol inside the PAL, we try the PAL_ variant // first because otherwise we run the risk of having the non-PAL_ // variant preferred over the PAL's implementation. if (pal_module && module->dl_handle == pal_module->dl_handle) { int iLen = 4 + strlen(lpProcName) + 1; LPSTR lpPALProcName = (LPSTR) alloca(iLen); if (strcpy_s(lpPALProcName, iLen, "PAL_")!= SAFECRT_SUCCESS) { ERROR("strcpy_s failed!\n"); SetLastError(ERROR_INSUFFICIENT_BUFFER); goto done; } if (strcat_s(lpPALProcName, iLen, lpProcName)!= SAFECRT_SUCCESS) { ERROR("strcat_s failed!\n"); SetLastError(ERROR_INSUFFICIENT_BUFFER); goto done; } ProcAddress = (FARPROC) dlsym(module->dl_handle, lpPALProcName); symbolName = lpPALProcName; } // If we aren't looking inside the PAL or we didn't find a PAL_ variant // inside the PAL, fall back to a normal search. if (ProcAddress == nullptr) { ProcAddress = (FARPROC) dlsym(module->dl_handle, lpProcName); } if (ProcAddress) { TRACE("Symbol %s found at address %p in module %p (named %S)\n", lpProcName, ProcAddress, module, MODNAME(module)); /* if we don't know the module's full name yet, this is our chance to obtain it */ if (!module->lib_name && module->dl_handle) { const char* libName = PAL_dladdr((LPVOID)ProcAddress); if (libName) { module->lib_name = UTIL_MBToWC_Alloc(libName, -1); if (nullptr == module->lib_name) { ERROR("MBToWC failure; can't save module's full name\n"); } else { TRACE("Saving full path of module %p as %s\n", module, libName); } } } } else { TRACE("Symbol %s not found in module %p (named %S), dlerror message is \"%s\"\n", lpProcName, module, MODNAME(module), dlerror()); SetLastError(ERROR_PROC_NOT_FOUND); } done: UnlockModuleList(); LOGEXIT("GetProcAddress returns FARPROC %p\n", ProcAddress); PERF_EXIT(GetProcAddress); return ProcAddress; } /*++ Function: FreeLibrary See MSDN doc. --*/ BOOL PALAPI FreeLibrary( IN OUT HMODULE hLibModule) { BOOL retval = FALSE; PERF_ENTRY(FreeLibrary); ENTRY("FreeLibrary (hLibModule=%p)\n", hLibModule); retval = LOADFreeLibrary((MODSTRUCT *)hLibModule, TRUE /* fCallDllMain */); LOGEXIT("FreeLibrary returns BOOL %d\n", retval); PERF_EXIT(FreeLibrary); return retval; } /*++ Function: FreeLibraryAndExitThread See MSDN doc. --*/ PALIMPORT VOID PALAPI FreeLibraryAndExitThread( IN HMODULE hLibModule, IN DWORD dwExitCode) { PERF_ENTRY(FreeLibraryAndExitThread); ENTRY("FreeLibraryAndExitThread()\n"); FreeLibrary(hLibModule); ExitThread(dwExitCode); LOGEXIT("FreeLibraryAndExitThread\n"); PERF_EXIT(FreeLibraryAndExitThread); } /*++ Function: GetModuleFileNameA See MSDN doc. Notes : because of limitations in the dlopen() mechanism, this will only return the full path name if a relative or absolute path was given to LoadLibrary, or if the module was used in a GetProcAddress call. otherwise, this will return the short name as given to LoadLibrary. The exception is if hModule is NULL : in this case, the full path of the executable is always returned. --*/ DWORD PALAPI GetModuleFileNameA( IN HMODULE hModule, OUT LPSTR lpFileName, IN DWORD nSize) { INT name_length; DWORD retval = 0; LPWSTR wide_name = nullptr; PERF_ENTRY(GetModuleFileNameA); ENTRY("GetModuleFileNameA (hModule=%p, lpFileName=%p, nSize=%u)\n", hModule, lpFileName, nSize); LockModuleList(); if (hModule &&!LOADValidateModule((MODSTRUCT *)hModule)) { TRACE("Can't find name for invalid module handle %p\n", hModule); SetLastError(ERROR_INVALID_HANDLE); goto done; } wide_name = LOADGetModuleFileName((MODSTRUCT *)hModule); if (!wide_name) { ASSERT("Can't find name for valid module handle %p\n", hModule); SetLastError(ERROR_INTERNAL_ERROR); goto done; } /* Convert module name to Ascii, place it in the supplied buffer */ name_length = WideCharToMultiByte(CP_ACP, 0, wide_name, -1, lpFileName, nSize, nullptr, nullptr); if (name_length == 0) { TRACE("Buffer too small to copy module's file name.\n"); SetLastError(ERROR_INSUFFICIENT_BUFFER); goto done; } TRACE("File name of module %p is %s\n", hModule, lpFileName); retval = name_length; done: UnlockModuleList(); LOGEXIT("GetModuleFileNameA returns DWORD %d\n", retval); PERF_EXIT(GetModuleFileNameA); return retval; } /*++ Function: GetModuleFileNameW See MSDN doc. Notes : because of limitations in the dlopen() mechanism, this will only return the full path name if a relative or absolute path was given to LoadLibrary, or if the module was used in a GetProcAddress call. otherwise, this will return the short name as given to LoadLibrary. The exception is if hModule is NULL : in this case, the full path of the executable is always returned. --*/ DWORD PALAPI GetModuleFileNameW( IN HMODULE hModule, OUT LPWSTR lpFileName, IN DWORD nSize) { INT name_length; DWORD retval = 0; LPWSTR wide_name = nullptr; PERF_ENTRY(GetModuleFileNameW); ENTRY("GetModuleFileNameW (hModule=%p, lpFileName=%p, nSize=%u)\n", hModule, lpFileName, nSize); LockModuleList(); wcscpy_s(lpFileName, nSize, W("")); if (hModule &&!LOADValidateModule((MODSTRUCT *)hModule)) { TRACE("Can't find name for invalid module handle %p\n", hModule); SetLastError(ERROR_INVALID_HANDLE); goto done; } wide_name = LOADGetModuleFileName((MODSTRUCT *)hModule); if (!wide_name) { TRACE("Can't find name for valid module handle %p\n", hModule); SetLastError(ERROR_INTERNAL_ERROR); goto done; } /* Copy module name into supplied buffer */ name_length = lstrlenW(wide_name); if (name_length >= (INT)nSize) { TRACE("Buffer too small (%u) to copy module's file name (%u).\n", nSize, name_length); SetLastError(ERROR_INSUFFICIENT_BUFFER); goto done; } wcscpy_s(lpFileName, nSize, wide_name); TRACE("file name of module %p is %S\n", hModule, lpFileName); retval = name_length; done: UnlockModuleList(); LOGEXIT("GetModuleFileNameW returns DWORD %u\n", retval); PERF_EXIT(GetModuleFileNameW); return retval; } HMODULE PALAPI GetModuleHandleW( IN OPTIONAL LPCWSTR lpModuleName) { if (lpModuleName) { // UNIXTODO: Implement this! ASSERT("Needs Implementation!!!"); return nullptr; } return (HMODULE)&exe_module; } BOOL PALAPI GetModuleHandleExW( IN DWORD dwFlags, IN OPTIONAL LPCWSTR lpModuleName, OUT HMODULE *phModule) { *phModule = NULL; return FALSE; } /* Function: PAL_LoadLibraryDirect Loads a library using a system call, without registering the library with the module list. Returns the system handle to the loaded library, or nullptr upon failure (error is set via SetLastError()). */ void * PALAPI PAL_LoadLibraryDirect( IN LPCWSTR lpLibFileName) { PathCharString pathstr; CHAR * lpstr = nullptr; INT name_length; void *dl_handle = nullptr; PERF_ENTRY(LoadLibraryDirect); ENTRY("LoadLibraryDirect (lpLibFileName=%p (%S)) \n", lpLibFileName? lpLibFileName : W16_NULLSTRING, lpLibFileName? lpLibFileName : W16_NULLSTRING); if (!LOADVerifyLibraryPath(lpLibFileName)) { goto done; } lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLength); if (nullptr == lpstr) { goto done; } if (!LOADConvertLibraryPathWideStringToMultibyteString(lpLibFileName, lpstr, &name_length)) { goto done; } /* do the Dos/Unix conversion on our own copy of the name */ FILEDosToUnixPathA(lpstr); pathstr.CloseBuffer(name_length); dl_handle = LOADLoadLibraryDirect(lpstr); done: LOGEXIT("LoadLibraryDirect returns HMODULE %p\n", dl_handle); PERF_EXIT(LoadLibraryDirect); return dl_handle; } /* Function: PAL_RegisterLibraryDirect Registers a system handle to a loaded library with the module list. Returns a PAL handle to the loaded library, or nullptr upon failure (error is set via SetLastError()). */ HMODULE PALAPI PAL_RegisterLibraryDirect( IN void *dl_handle, IN LPCWSTR lpLibFileName) { PathCharString pathstr; CHAR * lpstr = nullptr; INT name_length; HMODULE hModule = nullptr; PERF_ENTRY(RegisterLibraryDirect); ENTRY("RegisterLibraryDirect (lpLibFileName=%p (%S)) \n", lpLibFileName? lpLibFileName : W16_NULLSTRING, lpLibFileName? lpLibFileName : W16_NULLSTRING); if (!LOADVerifyLibraryPath(lpLibFileName)) { goto done; } lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLength); if (nullptr == lpstr) { goto done; } if (!LOADConvertLibraryPathWideStringToMultibyteString(lpLibFileName, lpstr, &name_length)) { goto done; } /* do the Dos/Unix conversion on our own copy of the name */ FILEDosToUnixPathA(lpstr); pathstr.CloseBuffer(name_length); /* let LOADRegisterLibraryDirect call SetLastError in case of failure */ LockModuleList(); hModule = LOADRegisterLibraryDirect((void *)dl_handle, lpstr, true /* fDynamic */); UnlockModuleList(); done: LOGEXIT("RegisterLibraryDirect returns HMODULE %p\n", hModule); PERF_EXIT(RegisterLibraryDirect); return hModule; } /*++ Function: PAL_UnregisterModule Used to cleanup the module HINSTANCE from PAL_RegisterModule. --*/ VOID PALAPI PAL_UnregisterModule( IN HINSTANCE hInstance) { PERF_ENTRY(PAL_UnregisterModule); ENTRY("PAL_UnregisterModule(hInstance=%p)\n", hInstance); LOADFreeLibrary((MODSTRUCT *)hInstance, FALSE /* fCallDllMain */); LOGEXIT("PAL_UnregisterModule returns\n"); PERF_EXIT(PAL_UnregisterModule); } /*++ PAL_LOADLoadPEFile Map a PE format file into memory like Windows LoadLibrary() would do. Doesn't apply base relocations if the function is relocated. Parameters: IN hFile - file to map Return value: non-NULL -
Introduce interface file for more isolation import dashboard; import editlist; import ast; string[] getOperatorList(); Dashboard runProgram(string s); EditList buildProgram(AstProgram prog); // vim: syntax=d
/****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; }; struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; }; struct ColourValue { float r; float g; float b; float a; }; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum SceneType { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); exposed new structs, enums, and methods to D2 /****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; }; struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; }; struct ColourValue { float r; float g; float b; float a; }; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum StatFlags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum FrameBuffer { FB_FRONT, FB_BACK, FB_AUTO }; enum SceneType { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE();
/****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* MeshHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); void destroy_light(LightHandle handle); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); exposed new methods and enums to D2 /****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* MeshHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { /// Point light sources give off light equally in all directions, so require only position not direction LT_POINT = 0, /// Directional lights simulate parallel light beams from a distant source, hence have direction but no position LT_DIRECTIONAL = 1, /// Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); void destroy_light(LightHandle handle); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref ColourValue colour); void light_set_specular_colour(LightHandle handle, const ref ColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer);
Added intrinsics. /* * This module holds declarations to LLVM intrinsics. * * See the LLVM language reference for more information: * * - http://llvm.org/docs/LangRef.html#intrinsics * */ module ldc.intrinsics; // Check for the right compiler version(LDC) { // OK } else { static assert(false, "This module is only valid for LDC"); } // // CODE GENERATOR INTRINSICS // // The 'llvm.returnaddress' intrinsic attempts to compute a target-specific // value indicating the return address of the current function or one of its // callers. pragma(intrinsic, "llvm.returnaddress") void* llvm_returnaddress(uint level); // The 'llvm.frameaddress' intrinsic attempts to return the target-specific // frame pointer value for the specified stack frame. pragma(intrinsic, "llvm.frameaddress") void* llvm_frameaddress(uint level); // The 'llvm.stacksave' intrinsic is used to remember the current state of the // function stack, for use with llvm.stackrestore. This is useful for // implementing language features like scoped automatic variable sized arrays // in C99. pragma(intrinsic, "llvm.stacksave") void* llvm_stacksave(); // The 'llvm.stackrestore' intrinsic is used to restore the state of the // function stack to the state it was in when the corresponding llvm.stacksave // intrinsic executed. This is useful for implementing language features like // scoped automatic variable sized arrays in C99. pragma(intrinsic, "llvm.stackrestore") void llvm_stackrestore(void* ptr); // The 'llvm.prefetch' intrinsic is a hint to the code generator to insert a // prefetch instruction if supported; otherwise, it is a noop. Prefetches have // no effect on the behavior of the program but can change its performance // characteristics. pragma(intrinsic, "llvm.prefetch") void llvm_prefetch(void* ptr, uint rw, uint locality); // The 'llvm.pcmarker' intrinsic is a method to export a Program Counter (PC) // in a region of code to simulators and other tools. The method is target // specific, but it is expected that the marker will use exported symbols to // transmit the PC of the marker. The marker makes no guarantees that it will // remain with any specific instruction after optimizations. It is possible // that the presence of a marker will inhibit optimizations. The intended use // is to be inserted after optimizations to allow correlations of simulation // runs. pragma(intrinsic, "llvm.pcmarker") void llvm_pcmarker(uint id); // The 'llvm.readcyclecounter' intrinsic provides access to the cycle counter // register (or similar low latency, high accuracy clocks) on those targets that // support it. On X86, it should map to RDTSC. On Alpha, it should map to RPCC. // As the backing counters overflow quickly (on the order of 9 seconds on // alpha), this should only be used for small timings. pragma(intrinsic, "llvm.readcyclecounter") ulong readcyclecounter(); // // STANDARD C LIBRARY INTRINSICS // // The 'llvm.memcpy.*' intrinsics copy a block of memory from the source // location to the destination location. // Note that, unlike the standard libc function, the llvm.memcpy.* intrinsics do // not return a value, and takes an extra alignment argument. pragma(intrinsic, "llvm.memcpy.i#") void llvm_memcpy(T)(void* dst, void* src, T len, uint alignment); deprecated { alias llvm_memcpy!(uint) llvm_memcpy_i32; alias llvm_memcpy!(ulong) llvm_memcpy_i64; } // The 'llvm.memmove.*' intrinsics move a block of memory from the source // location to the destination location. It is similar to the 'llvm.memcpy' // intrinsic but allows the two memory locations to overlap. // Note that, unlike the standard libc function, the llvm.memmove.* intrinsics // do not return a value, and takes an extra alignment argument. pragma(intrinsic, "llvm.memmove.i#") void llvm_memmove(T)(void* dst, void* src, T len, uint alignment); deprecated { alias llvm_memmove!(uint) llvm_memmove_i32; alias llvm_memmove!(ulong) llvm_memmove_i64; } // The 'llvm.memset.*' intrinsics fill a block of memory with a particular byte // value. // Note that, unlike the standard libc function, the llvm.memset intrinsic does // not return a value, and takes an extra alignment argument. pragma(intrinsic, "llvm.memset.i#") void llvm_memset(T)(void* dst, ubyte val, T len, uint alignment); deprecated { alias llvm_memset!(uint) llvm_memset_i32; alias llvm_memset!(ulong) llvm_memset_i64; } // The 'llvm.sqrt' intrinsics return the sqrt of the specified operand, // returning the same value as the libm 'sqrt' functions would. Unlike sqrt in // libm, however, llvm.sqrt has undefined behavior for negative numbers other // than -0.0 (which allows for better optimization, because there is no need to // worry about errno being set). llvm.sqrt(-0.0) is defined to return -0.0 like // IEEE sqrt. pragma(intrinsic, "llvm.sqrt.f#") T llvm_sqrt(T)(T val); deprecated { alias llvm_sqrt!(float) llvm_sqrt_f32; alias llvm_sqrt!(double) llvm_sqrt_f64; alias llvm_sqrt!(real) llvm_sqrt_f80; // may not actually be .f80 } // The 'llvm.sin.*' intrinsics return the sine of the operand. pragma(intrinsic, "llvm.sin.f#") T llvm_sin(T)(T val); deprecated { alias llvm_sin!(float) llvm_sin_f32; alias llvm_sin!(double) llvm_sin_f64; alias llvm_sin!(real) llvm_sin_f80; // may not actually be .f80 } // The 'llvm.cos.*' intrinsics return the cosine of the operand. pragma(intrinsic, "llvm.cos.f#") T llvm_cos(T)(T val); deprecated { alias llvm_cos!(float) llvm_cos_f32; alias llvm_cos!(double) llvm_cos_f64; alias llvm_cos!(real) llvm_cos_f80; // may not actually be .f80 } // The 'llvm.powi.*' intrinsics return the first operand raised to the specified // (positive or negative) power. The order of evaluation of multiplications is // not defined. When a vector of floating point type is used, the second // argument remains a scalar integer value. pragma(intrinsic, "llvm.powi.f#") T llvm_powi(T)(T val, int power); deprecated { alias llvm_powi!(float) llvm_powi_f32; alias llvm_powi!(double) llvm_powi_f64; alias llvm_powi!(real) llvm_powi_f80; // may not actually be .f80 } // The 'llvm.pow.*' intrinsics return the first operand raised to the specified // (positive or negative) power. pragma(intrinsic, "llvm.pow.f#") T llvm_pow(T)(T val, T power); deprecated { alias llvm_pow!(float) llvm_pow_f32; alias llvm_pow!(double) llvm_pow_f64; alias llvm_pow!(real) llvm_pow_f80; // may not actually be .f80 } // // BIT MANIPULATION INTRINSICS // // The 'llvm.bswap' family of intrinsics is used to byte swap integer values // with an even number of bytes (positive multiple of 16 bits). These are // useful for performing operations on data that is not in the target's native // byte order. pragma(intrinsic, "llvm.bswap.i#.i#") T llvm_bswap(T)(T val); deprecated { alias llvm_bswap!(ushort) llvm_bswap_i16; alias llvm_bswap!(uint) llvm_bswap_i32; alias llvm_bswap!(ulong) llvm_bswap_i64; } // The 'llvm.ctpop' family of intrinsics counts the number of bits set in a // value. pragma(intrinsic, "llvm.ctpop.i#") T llvm_ctpop(T)(T src); deprecated { alias llvm_ctpop!(ubyte) llvm_ctpop_i8; alias llvm_ctpop!(ushort) llvm_ctpop_i16; alias llvm_ctpop!(uint) llvm_ctpop_i32; alias llvm_ctpop!(ulong) llvm_ctpop_i64; } // The 'llvm.ctlz' family of intrinsic functions counts the number of leading // zeros in a variable. pragma(intrinsic, "llvm.ctlz.i#") T llvm_ctlz(T)(T src); deprecated { alias llvm_ctlz!(ubyte) llvm_ctlz_i8; alias llvm_ctlz!(ushort) llvm_ctlz_i16; alias llvm_ctlz!(uint) llvm_ctlz_i32; alias llvm_ctlz!(ulong) llvm_ctlz_i64; } // The 'llvm.cttz' family of intrinsic functions counts the number of trailing // zeros. pragma(intrinsic, "llvm.cttz.i#") T llvm_cttz(T)(T src); deprecated { alias llvm_cttz!(ubyte) llvm_cttz_i8; alias llvm_cttz!(ushort) llvm_cttz_i16; alias llvm_cttz!(uint) llvm_cttz_i32; alias llvm_cttz!(ulong) llvm_cttz_i64; } // The 'llvm.part.select' family of intrinsic functions selects a range of bits // from an integer value and returns them in the same bit width as the original // value. pragma(intrinsic, "llvm.part.select.i#") T llvm_part_select(T)(T val, uint loBit, uint hiBit); deprecated { alias llvm_part_select!(ubyte) llvm_part_select_i; alias llvm_part_select!(ushort) llvm_part_select_i; alias llvm_part_select!(uint) llvm_part_select_i; alias llvm_part_select!(ulong) llvm_part_select_i; } // The 'llvm.part.set' family of intrinsic functions replaces a range of bits // in an integer value with another integer value. It returns the integer with // the replaced bits. // TODO // declare i17 @llvm.part.set.i17.i9 (i17 %val, i9 %repl, i32 %lo, i32 %hi) // declare i29 @llvm.part.set.i29.i9 (i29 %val, i9 %repl, i32 %lo, i32 %hi) // // ATOMIC OPERATIONS AND SYNCHRONIZATION INTRINSICS // // The llvm.memory.barrier intrinsic guarantees ordering between specific // pairs of memory access types. pragma(intrinsic, "llvm.memory.barrier") void llvm_memory_barrier(bool ll, bool ls, bool sl, bool ss, bool device); // This loads a value in memory and compares it to a given value. If they are // equal, it stores a new value into the memory. pragma(intrinsic, "llvm.atomic.cmp.swap.i#.p0i#") T llvm_atomic_cmp_swap(T)(T* ptr, T cmp, T val); // This intrinsic loads the value stored in memory at ptr and yields the value // from memory. It then stores the value in val in the memory at ptr. pragma(intrinsic, "llvm.atomic.swap.i#.p0i#") T llvm_atomic_swap(T)(T* ptr, T val); // This intrinsic adds delta to the value stored in memory at ptr. It yields // the original value at ptr. pragma(intrinsic, "llvm.atomic.load.add.i#.p0i#") T llvm_atomic_load_add(T)(T* ptr, T val); // This intrinsic subtracts delta to the value stored in memory at ptr. It // yields the original value at ptr. pragma(intrinsic, "llvm.atomic.load.sub.i#.p0i#") T llvm_atomic_load_sub(T)(T* ptr, T val); // These intrinsics bitwise the operation (and, nand, or, xor) delta to the // value stored in memory at ptr. It yields the original value at ptr. pragma(intrinsic, "llvm.atomic.load.and.i#.p0i#") T llvm_atomic_load_and(T)(T* ptr, T val); pragma(intrinsic, "llvm.atomic.load.nand.i#.p0i#") T llvm_atomic_load_nand(T)(T* ptr, T val); pragma(intrinsic, "llvm.atomic.load.or.i#.p0i#") T llvm_atomic_load_or(T)(T* ptr, T val); pragma(intrinsic, "llvm.atomic.load.xor.i#.p0i#") T llvm_atomic_load_xor(T)(T* ptr, T val); // These intrinsics takes the signed or unsigned minimum or maximum of delta // and the value stored in memory at ptr. It yields the original value at ptr. pragma(intrinsic, "llvm.atomic.load.max.i#.p0i#") T llvm_atomic_load_max(T)(T* ptr, T val); pragma(intrinsic, "llvm.atomic.load.min.i#.p0i#") T llvm_atomic_load_min(T)(T* ptr, T val); pragma(intrinsic, "llvm.atomic.load.umax.i#.p0i#") T llvm_atomic_load_umax(T)(T* ptr, T val); pragma(intrinsic, "llvm.atomic.load.umin.i#.p0i#") T llvm_atomic_load_umin(T)(T* ptr, T val); // // ARITHMETIC-WITH-OVERFLOW INTRINSICS // struct OverflowRet(T) { static assert(is(T : int), T.stringof ~ " is not an integer type!"); T result; bool overflow; } // Signed and unsigned addition pragma(intrinsic, "llvm.sadd.with.overflow.i#") OverflowRet!(T) llvm_sadd_with_overflow(T)(T lhs, T rhs); pragma(intrinsic, "llvm.uadd.with.overflow.i#") OverflowRet!(T) llvm_uadd_with_overflow(T)(T lhs, T rhs); // Signed and unsigned subtraction pragma(intrinsic, "llvm.ssub.with.overflow.i#") OverflowRet!(T) llvm_ssub_with_overflow(T)(T lhs, T rhs); pragma(intrinsic, "llvm.usub.with.overflow.i#") OverflowRet!(T) llvm_usub_with_overflow(T)(T lhs, T rhs); // Signed and unsigned multiplication pragma(intrinsic, "llvm.smul.with.overflow.i#") OverflowRet!(T) llvm_smul_with_overflow(T)(T lhs, T rhs); /* Note: LLVM documentations says: * Warning: 'llvm.umul.with.overflow' is badly broken. * It is actively being fixed, but it should not currently be used! * * See: http://llvm.org/docs/LangRef.html#int_umul_overflow */ //pragma(intrinsic, "llvm.umul.with.overflow.i#") // OverflowRet!(T) llvm_umul_with_overflow(T)(T lhs, T rhs); // // GENERAL INTRINSICS // // This intrinsics is lowered to the target dependent trap instruction. If the // target does not have a trap instruction, this intrinsic will be lowered to // the call of the abort() function. pragma(intrinsic, "llvm.trap") void llvm_trap();
Initial version of Papyrus DI file <?xml version="1.0" encoding="ASCII"?> <di:SashWindowsMngr xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi"> <pageList> <availablePage> <emfPageIdentifier href="example.notation#/0"/> </availablePage> <availablePage> <emfPageIdentifier href="example.notation#/1"/> </availablePage> </pageList> <sashModel currentSelection="//@sashModel/@windows.0/@children.0"> <windows> <children xsi:type="di:TabFolder"> <children> <emfPageIdentifier href="example.notation#/0"/> </children> <children> <emfPageIdentifier href="example.notation#/1"/> </children> </children> </windows> </sashModel> </di:SashWindowsMngr>
// ====================================== // nanomsg.di : nanomsg bindings for D // // ====================================== const static ulong AF_SP = 1; const static ulong AF_SP_RAW = 2; const static ulong NN_CHUNKREF_MAX = 32; const static ulong NN_DOMAIN = 12; const static ulong NN_DONTWAIT = 1; const static ulong NN_FSM_ACTION = -2; const static ulong NN_FSM_START = -2; const static ulong NN_FSM_STOP = -3; const static ulong NN_HAUSNUMERO = 156384712; const static ulong NN_INPROC = -1; const static ulong NN_IPC = -2; const static ulong NN_IPV4ONLY = 14; const static ulong NN_LINGER = 1; const static ulong NN_PIPEBASE_PARSED = 2; const static ulong NN_PIPEBASE_RELEASE = 1; const static ulong NN_PIPE_IN = 33987; const static ulong NN_PIPE_OUT = 33988; const static ulong NN_PIPE_PARSED = 2; const static ulong NN_PIPE_RELEASE = 1; const static ulong NN_PROTO_BUS = 7; const static ulong NN_PROTOCOL = 13; const static ulong NN_PROTO_PAIR = 1; const static ulong NN_PROTO_PIPELINE = 5; const static ulong NN_PROTO_SUB = 2; const static ulong NN_PROTO_REQREP = 3; const static ulong NN_PROTO_SURVEY = 6; const static ulong NN_RCVBUF = 3; const static ulong NN_RCVFD = 11; const static ulong NN_RCVTIMEO = 5; const static ulong NN_RECONNECT_IVL = 6; const static ulong NN_RECONNECT_IVL_MAX = 7; const static ulong NN_REQ_RESEND_IVL = 1; const static ulong NN_SNDBUF = 2; const static ulong NN_SNDFD = 10; const static ulong NN_SNDPRIO = 8; const static ulong NN_SNDTIMEO = 4; const static ulong NN_SOCKADDR_MAX = 128; const static ulong NN_SOCKBASE_EVENT_IN = 1; const static ulong NN_SOCKBASE_EVENT_OUT = 2; const static ulong NN_SOCKTYPE_FLAG_NORECV = 1; const static ulong NN_SOCKTYPE_FLAG_NOSEND = 2; const static ulong NN_SOL_SOCKET = 0; const static ulong NN_SUB_SUBSCRIBE = 1; const static ulong NN_SUB_UNSUBSCRIBE = 2; const static ulong NN_SURVEYOR_DEADLINE = 1; const static ulong NN_TCP = -3; const static ulong NN_TCP_NODELAY = 1; const static ulong NN_VERSION_AGE = 0; const static ulong NN_VERSION_CURRENT = 0; const static ulong NN_VERSION_REVISION = 0; const static ulong NN_BUS = (NN_PROTO_BUS * 16 + 0); const static ulong NN_MSG = -1; const static ulong NN_PAIR = (NN_PROTO_PAIR * 16 + 0); const static ulong NN_PUSH = (NN_PROTO_PIPELINE * 16 + 0); const static ulong NN_PULL = (NN_PROTO_PIPELINE * 16 + 1); const static ulong NN_ = (NN_PROTO_SUB * 16 + 0); const static ulong NN_SUB = (NN_PROTO_SUB * 16 + 1); const static ulong NN_REQ = (NN_PROTO_REQREP * 16 + 0); const static ulong NN_REP = (NN_PROTO_REQREP * 16 + 1); const static ulong NN_SURVEYOR = (NN_PROTO_SURVEY * 16 + 0); const static ulong NN_RESPONDENT = (NN_PROTO_SURVEY * 16 + 1); const static ulong EACCESS = (NN_HAUSNUMERO + 17); const static ulong ETERM = (NN_HAUSNUMERO + 53); const static ulong EFSM = (NN_HAUSNUMERO + 54); const static ulong NN_QUEUE_NOTINQUEUE = -1; const static ulong NN_LIST_NOTINLIST = -1; struct Struct_nn_iovec { void* iov_base; ulong iov_len; } struct Struct_nn_msghdr { Struct_nn_iovec* msg_iov; ulong msg_iovlen; void* msg_control; ulong msg_controllen; } struct Struct_nn_cmsghdr { ulong cmsg_len; ulong cmsg_level; ulong cmsg_type; } extern(C) { ulong* __errno_location(); ulong nn_errno(); char* nn_strerror(ulong errnum); char* nn_symbol(ulong i, ulong* value); void nn_term(); void* nn_allocmsg(ulong size, ulong _type); ulong nn_freemsg(void* msg); ulong nn_socket(ulong domain, ulong protocol); ulong nn_close(ulong s); ulong nn_setsockopt(ulong s, ulong level, ulong option, void* optval, ulong optvallen); ulong nn_getsockopt(ulong s, ulong level, ulong option, void* optval, ulong* optvallen); ulong nn_bind(ulong s, char* addr); ulong nn_connect(ulong s, char* addr); ulong nn_shutdown(ulong s, ulong how); ulong nn_send(ulong s, void* buf, ulong len, ulong flags); ulong nn_recv(ulong s, void* buf, ulong len, ulong flags); ulong nn_sendmsg(ulong s, Struct_nn_msghdr* msghdr, ulong flags); ulong nn_recvmsg(ulong s, Struct_nn_msghdr* msghdr, ulong flags); ulong nn_device(ulong s1, ulong s2); } include usage instructions for the nanomsg.d d-language bindings // ====================================== // nanomsg.di : nanomsg bindings for D // // to use: put // import nanomsg; // at the top of your D source file. // And at link time, supply: -L-lnanomsg // ====================================== const static ulong AF_SP = 1; const static ulong AF_SP_RAW = 2; const static ulong NN_CHUNKREF_MAX = 32; const static ulong NN_DOMAIN = 12; const static ulong NN_DONTWAIT = 1; const static ulong NN_FSM_ACTION = -2; const static ulong NN_FSM_START = -2; const static ulong NN_FSM_STOP = -3; const static ulong NN_HAUSNUMERO = 156384712; const static ulong NN_INPROC = -1; const static ulong NN_IPC = -2; const static ulong NN_IPV4ONLY = 14; const static ulong NN_LINGER = 1; const static ulong NN_PIPEBASE_PARSED = 2; const static ulong NN_PIPEBASE_RELEASE = 1; const static ulong NN_PIPE_IN = 33987; const static ulong NN_PIPE_OUT = 33988; const static ulong NN_PIPE_PARSED = 2; const static ulong NN_PIPE_RELEASE = 1; const static ulong NN_PROTO_BUS = 7; const static ulong NN_PROTOCOL = 13; const static ulong NN_PROTO_PAIR = 1; const static ulong NN_PROTO_PIPELINE = 5; const static ulong NN_PROTO_SUB = 2; const static ulong NN_PROTO_REQREP = 3; const static ulong NN_PROTO_SURVEY = 6; const static ulong NN_RCVBUF = 3; const static ulong NN_RCVFD = 11; const static ulong NN_RCVTIMEO = 5; const static ulong NN_RECONNECT_IVL = 6; const static ulong NN_RECONNECT_IVL_MAX = 7; const static ulong NN_REQ_RESEND_IVL = 1; const static ulong NN_SNDBUF = 2; const static ulong NN_SNDFD = 10; const static ulong NN_SNDPRIO = 8; const static ulong NN_SNDTIMEO = 4; const static ulong NN_SOCKADDR_MAX = 128; const static ulong NN_SOCKBASE_EVENT_IN = 1; const static ulong NN_SOCKBASE_EVENT_OUT = 2; const static ulong NN_SOCKTYPE_FLAG_NORECV = 1; const static ulong NN_SOCKTYPE_FLAG_NOSEND = 2; const static ulong NN_SOL_SOCKET = 0; const static ulong NN_SUB_SUBSCRIBE = 1; const static ulong NN_SUB_UNSUBSCRIBE = 2; const static ulong NN_SURVEYOR_DEADLINE = 1; const static ulong NN_TCP = -3; const static ulong NN_TCP_NODELAY = 1; const static ulong NN_VERSION_AGE = 0; const static ulong NN_VERSION_CURRENT = 0; const static ulong NN_VERSION_REVISION = 0; const static ulong NN_BUS = (NN_PROTO_BUS * 16 + 0); const static ulong NN_MSG = -1; const static ulong NN_PAIR = (NN_PROTO_PAIR * 16 + 0); const static ulong NN_PUSH = (NN_PROTO_PIPELINE * 16 + 0); const static ulong NN_PULL = (NN_PROTO_PIPELINE * 16 + 1); const static ulong NN_ = (NN_PROTO_SUB * 16 + 0); const static ulong NN_SUB = (NN_PROTO_SUB * 16 + 1); const static ulong NN_REQ = (NN_PROTO_REQREP * 16 + 0); const static ulong NN_REP = (NN_PROTO_REQREP * 16 + 1); const static ulong NN_SURVEYOR = (NN_PROTO_SURVEY * 16 + 0); const static ulong NN_RESPONDENT = (NN_PROTO_SURVEY * 16 + 1); const static ulong EACCESS = (NN_HAUSNUMERO + 17); const static ulong ETERM = (NN_HAUSNUMERO + 53); const static ulong EFSM = (NN_HAUSNUMERO + 54); const static ulong NN_QUEUE_NOTINQUEUE = -1; const static ulong NN_LIST_NOTINLIST = -1; struct Struct_nn_iovec { void* iov_base; ulong iov_len; } struct Struct_nn_msghdr { Struct_nn_iovec* msg_iov; ulong msg_iovlen; void* msg_control; ulong msg_controllen; } struct Struct_nn_cmsghdr { ulong cmsg_len; ulong cmsg_level; ulong cmsg_type; } extern(C) { ulong* __errno_location(); ulong nn_errno(); char* nn_strerror(ulong errnum); char* nn_symbol(ulong i, ulong* value); void nn_term(); void* nn_allocmsg(ulong size, ulong _type); ulong nn_freemsg(void* msg); ulong nn_socket(ulong domain, ulong protocol); ulong nn_close(ulong s); ulong nn_setsockopt(ulong s, ulong level, ulong option, void* optval, ulong optvallen); ulong nn_getsockopt(ulong s, ulong level, ulong option, void* optval, ulong* optvallen); ulong nn_bind(ulong s, char* addr); ulong nn_connect(ulong s, char* addr); ulong nn_shutdown(ulong s, ulong how); ulong nn_send(ulong s, void* buf, ulong len, ulong flags); ulong nn_recv(ulong s, void* buf, ulong len, ulong flags); ulong nn_sendmsg(ulong s, Struct_nn_msghdr* msghdr, ulong flags); ulong nn_recvmsg(ulong s, Struct_nn_msghdr* msghdr, ulong flags); ulong nn_device(ulong s1, ulong s2); }
<?xml version="1.0" encoding="UTF-8"?> <xmi:XMI xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"/> Delete target.di
/****************************************************************************** * ogre_interface.d - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; private import core.stdc.config : c_long, c_ulong; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgreResource.h alias ulong ResourceHandle; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* NodeHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* ManualObjectHandle; alias void* ManualObjectSectionHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* PlaneListHandle; alias void* PlaneBoundedVolumeHandle; alias void* MeshHandle; alias void* TimerHandle; alias void* WindowListenerHandle; alias void* AxisAlignedBoxHandle; alias void* RayHandle; alias void* SphereHandle; alias void* BoneHandle; alias void* TagPointHandle; alias void* SkeletonHandle; alias void* SkeletonInstanceHandle; alias void* SceneQueryHandle; alias void* RaySceneQueryHandle; alias void* RaySceneQueryResultHandle; alias void* SceneQueryListenerHandle; alias void* RaySceneQueryListenerHandle; alias void* SceneQueryResultHandle; alias void* MovableObjectHandle; alias void* RenderOperationHandle; alias void* OverlayHandle; alias void* OverlayManagerHandle; alias void* OverlayElementHandle; alias void* PanelOverlayElementHandle; alias void* TextAreaOverlayElementHandle; alias void* OverlayContainerHandle; alias void* VertexDataHandle; alias void* IndexDataHandle; alias void* coiResourceHandle; alias void* ResourcePtrHandle; alias void* ManualResourceLoaderHandle; alias void* ResourceManagerHandle; alias void* ResourceListenerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; //alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; //Ogre::FrameListener callbacks. alias int function(ref const(FrameEvent) event, void* userdata) FrameStarted; alias int function(ref const(FrameEvent) event, void* userdata) FrameEnded; alias int function(ref const(FrameEvent) event, void* userdata) FrameQueued; alias int function(const ref world_fragment frag, void* userdata) SceneQueryFragmentResult; alias int function(MovableObjectHandle handle, void* userdata) SceneQueryObjectResult; alias int function(const ref world_fragment frag, coiReal distance, void* userdata) RaySceneQueryFragmentResult; alias int function(MovableObjectHandle handle, coiReal distance, void* userdata) RaySceneQueryObjectResult; //Ogre::Resource::Listener callbacks alias void function(coiResourceHandle handle, void* userdata) loadingCompleteCB; alias void function(coiResourceHandle handle, void* userdata) preparingCompleteCB; alias void function(coiResourceHandle handle, void* userdata) unloadingCompleteCB; struct coiQuaternion { coiReal w; coiReal x; coiReal y; coiReal z; } struct coiVector2 { coiReal x; coiReal y; } struct coiVector3 { coiReal x; coiReal y; coiReal z; } struct coiVector4 { coiReal x; coiReal y; coiReal z; coiReal w; } struct coiMatrix3 { coiReal m[3][3]; } struct coiMatrix4 { coiReal m[4][4]; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; } struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ray_pair { int intersects; coiReal distance; } struct coiColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; c_ulong bestFrameTime; c_ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; struct world_fragment { world_fragment_type fragment_type; coiVector3 single_intersection; PlaneListHandle planes; void* geometry; RenderOperationHandle render_op; } struct rayscenequery_result_entry { coiReal distance; MovableObjectHandle movable; world_fragment* fragment; } struct hardware_animation_data { ushort target_buffer_index; coiReal parametric; }; enum logging_level { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum log_message_level { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum orientation_mode { OR_DEGREE_0 = 0, OR_DEGREE_90 = 1, OR_DEGREE_180 = 2, OR_DEGREE_270 = 3, OR_PORTRAIT = OR_DEGREE_0, OR_LANDSCAPERIGHT = OR_DEGREE_90, OR_LANDSCAPELEFT = OR_DEGREE_270 } enum projection_type { PT_ORTHOGRAPHIC, PT_PERSPECTIVE } enum frustum_plane { FRUSTUM_PLANE_NEAR = 0, FRUSTUM_PLANE_FAR = 1, FRUSTUM_PLANE_LEFT = 2, FRUSTUM_PLANE_RIGHT = 3, FRUSTUM_PLANE_TOP = 4, FRUSTUM_PLANE_BOTTOM = 5 } enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF } enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; // OgreResource.h enum loading_state { LOADSTATE_UNLOADED, LOADSTATE_LOADING, LOADSTATE_LOADED, LOADSTATE_UNLOADING, LOADSTATE_PREPARED, LOADSTATE_PREPARING }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { LT_POINT = 0, LT_DIRECTIONAL = 1, LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; enum Extent { EXTENT_NULL, EXTENT_FINITE, EXTENT_INFINITE }; enum CornerEnum { FAR_LEFT_BOTTOM = 0, FAR_LEFT_TOP = 1, FAR_RIGHT_TOP = 2, FAR_RIGHT_BOTTOM = 3, NEAR_RIGHT_BOTTOM = 7, NEAR_LEFT_BOTTOM = 6, NEAR_LEFT_TOP = 5, NEAR_RIGHT_TOP = 4 }; enum plane_side { NO_SIDE, POSITIVE_SIDE, NEGATIVE_SIDE, BOTH_SIDE }; enum world_fragment_type { WFT_NONE, WFT_PLANE_BOUNDED_REGION, WFT_SINGLE_INTERSECTION, WFT_CUSTOM_GEOMETRY, WFT_RENDER_OPERATION }; enum gui_metrics_mode { GMM_RELATIVE, GMM_PIXELS, GMM_RELATIVE_ASPECT_ADJUSTED }; enum gui_horizontal_alignment { GHA_LEFT, GHA_CENTER, GHA_RIGHT }; enum gui_vertical_alignment { GVA_TOP, GVA_CENTER, GVA_BOTTOM }; enum textarea_overlayelement_alignment { Left, Right, Center }; enum skeleton_animation_blend_mode { ANIMBLEND_AVERAGE = 0, ANIMBLEND_CUMULATIVE = 1 }; enum operation_type { OT_POINT_LIST = 1, OT_LINE_LIST = 2, OT_LINE_STRIP = 3, OT_TRIANGLE_LIST = 4, OT_TRIANGLE_STRIP = 5, OT_TRIANGLE_FAN = 6 }; // OgreCommon.h enum compare_function { CMPF_ALWAYS_FAIL, CMPF_ALWAYS_PASS, CMPF_LESS, CMPF_LESS_EQUAL, CMPF_EQUAL, CMPF_NOT_EQUAL, CMPF_GREATER_EQUAL, CMPF_GREATER }; enum texture_filter_options { TFO_NONE, TFO_BILINEAR, TFO_TRILINEAR, TFO_ANISOTROPIC } enum filter_type { FT_MIN, FT_MAG, FT_MIP }; enum filter_options { FO_NONE, FO_POINT, FO_LINEAR, FO_ANISOTROPIC }; enum shade_options { SO_FLAT, SO_GOURAUD, SO_PHONG }; enum fog_mode { FOG_NONE, FOG_EXP, FOG_EXP2, FOG_LINEAR }; enum culling_mode { CULL_NONE = 1, CULL_CLOCKWISE = 2, CULL_ANTICLOCKWISE = 3 }; enum manual_culling_mode { MANUAL_CULL_NONE = 1, MANUAL_CULL_BACK = 2, MANUAL_CULL_FRONT = 3 }; enum waveform_type { WFT_SINE, WFT_TRIANGLE, WFT_SQUARE, WFT_SAWTOOTH, WFT_INVERSE_SAWTOOTH, WFT_PWM }; enum polygon_mode { PM_POINTS = 1, PM_WIREFRAME = 2, PM_SOLID = 3 }; enum shadow_technique { SHADOWTYPE_NONE = 0x00, SHADOWDETAILTYPE_ADDITIVE = 0x01, SHADOWDETAILTYPE_MODULATIVE = 0x02, SHADOWDETAILTYPE_INTEGRATED = 0x04, SHADOWDETAILTYPE_STENCIL = 0x10, SHADOWDETAILTYPE_TEXTURE = 0x20, SHADOWTYPE_STENCIL_MODULATIVE = 0x12, SHADOWTYPE_STENCIL_ADDITIVE = 0x11, SHADOWTYPE_TEXTURE_MODULATIVE = 0x22, SHADOWTYPE_TEXTURE_ADDITIVE = 0x21, SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED = 0x25, SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED = 0x26 }; alias int track_vertex_colour_type; enum track_vertex_colour_enum { TVC_NONE = 0x0, TVC_AMBIENT = 0x1, TVC_DIFFUSE = 0x2, TVC_SPECULAR = 0x4, TVC_EMISSIVE = 0x8 } enum sort_mode { SM_DIRECTION, SM_DISTANCE }; enum frame_buffer_type { FBT_COLOUR = 0x1, FBT_DEPTH = 0x2, FBT_STENCIL = 0x4 }; enum instance_manager_flags { IM_USE16BIT = 0x0001, IM_VTFBESTFIT = 0x0002, IM_VTFBONEMATRIXLOOKUP = 0x0004, IM_USEBONEDUALQUATERNIONS = 0x0008, IM_USEONEWEIGHT = 0x0010, IM_FORCEONEWEIGHT = 0x0020, IM_USEALL = IM_USE16BIT|IM_VTFBESTFIT|IM_USEONEWEIGHT }; enum clip_result { CLIPPED_NONE = 0, CLIPPED_SOME = 1, CLIPPED_ALL = 2 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); TimerHandle root_get_timer(); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, c_ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char* plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); //createManualObject(std::string const&) ManualObjectHandle scenemanager_create_manual_object(SceneManagerHandle handle, const char* name); //createManualObject() ManualObjectHandle scenemanager_create_manual_object_unnamed(SceneManagerHandle handle); //getManualObject(std::string const&) const ManualObjectHandle scenemanager_get_manual_object(const SceneManagerHandle handle, const char* name); //hasManualObject(std::string const&) const int scenemanager_has_manual_object(const SceneManagerHandle handle, const char* name); //destroyManualObject(Ogre::ManualObject*) void scenemanager_destroy_manual_object(SceneManagerHandle handle, ManualObjectHandle obj); //destroyManualObject(std::string const&) void scenemanager_destroy_manual_object_by_name(SceneManagerHandle handle, const char* name); //destroyAllManualObjects() void scenemanager_destroy_all_manual_objects(SceneManagerHandle handle); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); void scenemanager_set_sky_box(SceneManagerHandle handle, int enable, const char* material_name, float distance, int draw_first, const coiQuaternion* orientation, const char* group_name); void scenemanager_set_sky_dome(SceneManagerHandle handle, int enable, const char* material_name, float curvature, float tiling, float distance, int draw_first, const coiQuaternion* orientation, int xsegments, int ysegments, int ysegments_keep, const char* group_name); const(char*) scenemanager_get_name(SceneManagerHandle handle); //void SceneManager::destroyQuery(Ogre::SceneQuery* query); void scenemanager_destroy_scenequery(SceneManagerHandle handle, SceneQueryHandle query); // Ogre::SceneManager::createRayQuery(Ogre::Ray const&, unsigned long) RaySceneQueryHandle scenemanager_create_rayquery(SceneQueryHandle handle, RayHandle ray_handle, c_ulong mask); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Ogre::Node //Ogre::Node::getName() const const(char*) node_get_name(NodeHandle handle); //Ogre::Node::getParent() const //XXX: May be NULL if this is the root node. NodeHandle node_get_parent(NodeHandle handle); //Ogre::Node::getOrientation() const void node_get_orientation(NodeHandle handle, ref coiQuaternion result); //Ogre::Node::setOrientation(Ogre::Quaternion const&) void node_set_orientation(NodeHandle handle, const ref coiQuaternion orientation); //Ogre::Node::setScale(Ogre::Vector3 const&) void node_set_scale(NodeHandle handle, const ref coiVector3 in_scale); //Ogre::Node::setScale(Ogre::Vector3 const&) void node_set_scale_xyz(NodeHandle handle, const float x, const float y, const float z); //Ogre::Node::getScale() const void node_get_scale(NodeHandle handle, ref coiVector3 result); //Ogre::Node::setInheritOrientation(bool) void node_set_inherit_orientation(NodeHandle handle, int inherit); //Ogre::Node::getInheritOrientation() const int node_get_inherit_orientation(NodeHandle handle); //Ogre::Node::resetOrientation() void node_reset_orientation(NodeHandle handle); //Ogre::Node::setInheritScale(bool) void node_set_inherit_scale(NodeHandle handle, int inherit); //Ogre::Node::getInheritScale() const int node_get_inherit_scale(NodeHandle handle); //Ogre::Node::scale(Ogre::Vector3 const&) void node_scale(NodeHandle handle, const ref coiVector3 scale); //Ogre::Node::scale(Ogre::Vector3 const&) void node_scale_xyz(NodeHandle handle, const float x, const float y, const float z); //Ogre::Node::translate(Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate(NodeHandle handle, const ref coiVector3 d, transform_space relative_to); //Ogre::Node::translate(Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate_xyz(NodeHandle handle, const float x, const float y, const float z, transform_space relative_to); //Ogre::Node::translate(Ogre::Matrix3 const&, float, float, float, Ogre::Node::TransformSpace) //Ogre::Node::translate(Ogre::Matrix3 const&, Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate_m(NodeHandle handle, const ref coiMatrix3 axes, const ref coiVector3 move, transform_space relative_to); //Ogre::Node::roll(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_roll(NodeHandle handle, const coiReal angle, transform_space relative_to); //Ogre::Node::pitch(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_pitch(NodeHandle handle, const coiReal angle, transform_space relative_to); // Ogre::Node::yaw(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_yaw(NodeHandle handle, const coiReal angle, transform_space relative_to); //Ogre::Node::rotate(Ogre::Vector3 const&, Ogre::Radian const&, Ogre::Node::TransformSpace) void node_rotate(NodeHandle handle, const ref coiVector3 axis, const coiReal angle, transform_space relative_to); //Ogre::Node::rotate(Ogre::Quaternion const&, Ogre::Node::TransformSpace) void node_rotate_q(NodeHandle handle, const ref coiQuaternion q, transform_space relative_to); //Ogre::Node::getLocalAxes() const void node_get_local_axes(NodeHandle handle, ref coiMatrix3 result); //Ogre::Node::createChild(Ogre::Vector3 const&, Ogre::Quaternion const&) NodeHandle node_create_child(NodeHandle handle, const ref coiVector3 translate, const ref coiQuaternion rotate); //Ogre::Node::createChild(std::string const&, Ogre::Vector3 const&, Ogre::Quaternion const&) NodeHandle node_create_named_child(NodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); //Ogre::Node::addChild(Ogre::Node*) void node_add_child(NodeHandle handle, NodeHandle child); //Ogre::Node::numChildren() const ushort node_num_children(const NodeHandle handle); //Ogre::Node::getChild(unsigned short) const NodeHandle node_get_child_by_index(const NodeHandle handle, ushort index); //Ogre::Node::getChild(std::string const&) const NodeHandle node_get_child_by_name(const NodeHandle handle, const char* name); //Ogre::Node::removeChild(unsigned short) NodeHandle node_remove_child_by_index(NodeHandle handle, ushort index); //Ogre::Node::removeChild(Ogre::Node*) NodeHandle node_remove_child(NodeHandle handle, NodeHandle child); //Ogre::Node::removeChild(std::string const&) NodeHandle node_remove_child_by_name(NodeHandle handle, const char* name); //Ogre::Node::removeAllChildren() void node_remove_all_children(NodeHandle handle); //Ogre::Node::_setDerivedPosition(Ogre::Vector3 const&) void node__set_derived_position(NodeHandle handle, ref const(coiVector3) position); //Ogre::Node::_setDerivedOrientation(Ogre::Quaternion const&) void node__set_derived_orientation(NodeHandle handle, ref const(coiQuaternion) orientation); //Ogre::Node::_getDerivedOrientation() const void node__get_derived_orientation(const NodeHandle handle, ref coiQuaternion orientation); //Ogre::Node::_getDerivedPosition() const void node__get_derived_position(const NodeHandle handle, ref coiVector3 position); //Ogre::Node::_getDerivedScale() const void node__get_derived_scale(const NodeHandle handle, ref coiVector3 scale); // Ogre::Bone //Bone(unsigned short handle, Skeleton* creator); BoneHandle create_bone(ushort handle, SkeletonHandle creator); //Bone(const String& name, unsigned short handle, Skeleton* creator); BoneHandle create_named_bone(const char* name, ushort handle, SkeletonHandle creator); //~Bone(); void destroy_bone(BoneHandle handle); //Bone* createChild(unsigned short handle, const Vector3& translate = Vector3::ZERO, const Quaternion& rotate = Quaternion::IDENTITY); BoneHandle bone_create_child(BoneHandle handle, ushort hnd, ref const(coiVector3) translate, ref const(coiQuaternion) rotate); //unsigned short getHandle(void) const; ushort bone_get_handle(const BoneHandle handle); //void setBindingPose(void); void bone_set_binding_pose(BoneHandle handle); //void reset(void); void bone_reset(BoneHandle handle); //void setManuallyControlled(bool manuallyControlled); void bone_set_manually_controlled(BoneHandle handle, int manually_controlled); //bool isManuallyControlled() const; int bone_is_manually_controlled(const BoneHandle handle); //void _getOffsetTransform(Matrix4& m) const; void bone__get_offset_transform(const BoneHandle handle, ref coiMatrix4 m); //const Vector3& _getBindingPoseInverseScale(void) const; void bone__get_binding_pose_inverse_scale(const BoneHandle handle, ref coiVector3 result); //const Vector3& _getBindingPoseInversePosition(void) const; void bone__get_binding_pose_inverse_position(const BoneHandle handle, ref coiVector3 result); //const Quaternion& _getBindingPoseInverseOrientation(void) const; void bone__get_binding_pose_inverse_orientation(const BoneHandle handle, ref coiQuaternion result); //void needUpdate(bool forceParentUpdate = false); void bone_need_update(BoneHandle handle, int force_parent_update); // Ogre::TagPoint //TagPoint(unsigned short handle, Skeleton* creator); TagPointHandle create_tagpoint(ushort bone_handle, SkeletonHandle creator); //~TagPoint(); void destroy_tagpoint(TagPointHandle handle); //Entity *getParentEntity(void) const; EntityHandle tagpoint_get_parent_entity(const TagPointHandle handle); //MovableObject* getChildObject(void) const; MovableObjectHandle tagpoint_get_child_object(const TagPointHandle handle); //void setParentEntity(Entity *pEntity); void tagpoint_set_parent_entity(TagPointHandle handle, EntityHandle entity); //void setChildObject(MovableObject *pObject); void tagpoint_set_child_object(TagPointHandle handle, MovableObjectHandle obj); //void setInheritParentEntityOrientation(bool inherit); void tagpoint_set_inherit_parent_entity_orientation(TagPointHandle handle, int inherit); //bool getInheritParentEntityOrientation(void) const; int tagpoint_get_inherit_parent_entity_orientation(const TagPointHandle handle); //void setInheritParentEntityScale(bool inherit); void tagpoint_set_inherit_parent_entity_scale(TagPointHandle handle, int inherit); //bool getInheritParentEntityScale(void) const; int tagpoint_get_inherit_parent_entity_scale(const TagPointHandle handle); //const Matrix4& getParentEntityTransform(void) const; void tagpoint_get_parent_entity_transform(const TagPointHandle handle, ref coiMatrix4 result); //const Matrix4& _getFullLocalTransform(void) const; void tagpoint__get_full_local_transform(const TagPointHandle handle, ref coiMatrix4 result); //void needUpdate(bool forceParentUpdate = false); void tagpoint_need_update(TagPointHandle handle, int force_parent_update); //void updateFromParentImpl(void) const; void tagpoint_update_from_parent_impl(const TagPointHandle handle); //TODO: const LightList& getLights(void) const; // Ogre::Skeleton //Skeleton(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual = false, ManualResourceLoader* loader = 0); //~Skeleton(); void destroy_skeleton(SkeletonHandle handle); //Bone* createBone(void); BoneHandle skeleton_create_bone(SkeletonHandle handle); //Bone* createBone(unsigned short handle); BoneHandle skeleton_create_bone_with_handle(SkeletonHandle handle, ushort bone_handle); //Bone* createBone(const String& name); BoneHandle skeleton_create_bone_with_name(SkeletonHandle handle, const char* name); //Bone* createBone(const String& name, unsigned short handle); BoneHandle skeleton_create_bone_with_name_and_handle(SkeletonHandle handle, const char* name, ushort bone_handle); //unsigned short getNumBones(void) const; ushort skeleton_get_num_bones(const SkeletonHandle handle); //Bone* getRootBone(void) const; BoneHandle skeleton_get_root_bone(const SkeletonHandle handle); //typedef vector<Bone*>::type BoneList; //typedef VectorIterator<BoneList> BoneIterator; //TODO: BoneIterator getRootBoneIterator(void); //TODO: BoneIterator getBoneIterator(void); //Bone* getBone(unsigned short handle) const; BoneHandle skeleton_get_bone_by_handle(const SkeletonHandle handle, ushort bone_handle); //Bone* getBone(const String& name) const; BoneHandle skeleton_get_bone_by_name(const SkeletonHandle handle, const char* name); //bool hasBone(const String& name) const; int skeleton_has_bone(const SkeletonHandle handle, const char* name); //void setBindingPose(void); void skeleton_set_binding_pose(SkeletonHandle handle); //void reset(bool resetManualBones = false); void skeleton_reset(SkeletonHandle handle, int reset_manual_bones); //TODO: Animation* createAnimation(const String& name, Real length); //TODO: Animation* getAnimation(const String& name, const LinkedSkeletonAnimationSource** linker) const; //TODO: Animation* getAnimation(const String& name) const; //TODO: Animation* _getAnimationImpl(const String& name, const LinkedSkeletonAnimationSource** linker = 0) const; //bool hasAnimation(const String& name) const; int skeleton_has_animation(const SkeletonHandle handle, const char* name); //void removeAnimation(const String& name); void skeleton_remove_animation(SkeletonHandle handle, const char* name); //TODO: void setAnimationState(const AnimationStateSet& animSet); //TODO: void _initAnimationState(AnimationStateSet* animSet); //TODO: void _refreshAnimationState(AnimationStateSet* animSet); //void _getBoneMatrices(Matrix4* pMatrices); void skeleton__get_bone_matrices(SkeletonHandle handle, ref coiMatrix4[] matrices); //unsigned short getNumAnimations(void) const; ushort skeleton_get_num_animations(const SkeletonHandle handle); //TODO: Animation* getAnimation(unsigned short index) const; //SkeletonAnimationBlendMode getBlendMode() const; skeleton_animation_blend_mode skeleton_get_blend_mode(const SkeletonHandle handle); //void setBlendMode(SkeletonAnimationBlendMode state); void skeleton_set_blend_mode(SkeletonHandle handle, skeleton_animation_blend_mode state); //void _updateTransforms(void); void skeleton__update_transforms(SkeletonHandle handle); //void optimiseAllAnimations(bool preservingIdentityNodeTracks = false); void skeleton_optimise_all_animations(SkeletonHandle handle, int preserving_identity_node_tracks); //void addLinkedSkeletonAnimationSource(const String& skelName, Real scale = 1.0f); void skeleton_add_linked_skeleton_animation_source(SkeletonHandle handle, const char* skel_name, coiReal scale); //void removeAllLinkedSkeletonAnimationSources(void); void skeleton_remove_all_linked_skeleton_animation_sources(SkeletonHandle handle); //typedef vector<LinkedSkeletonAnimationSource>::type LinkedSkeletonAnimSourceList; //typedef ConstVectorIterator<LinkedSkeletonAnimSourceList> LinkedSkeletonAnimSourceIterator; //TODO: LinkedSkeletonAnimSourceIterator getLinkedSkeletonAnimationSourceIterator(void) const; //void _notifyManualBonesDirty(void); void skeleton__notify_manual_bones_dirty(SkeletonHandle handle); //void _notifyManualBoneStateChange(Bone* bone); void skeleton__notify_manual_bone_state_change(SkeletonHandle handle, BoneHandle bone); //bool getManualBonesDirty(void) const; int skeleton_get_manual_bones_dirty(const SkeletonHandle handle); //bool hasManualBones(void) const; int skeleton_has_manual_bones(const SkeletonHandle handle); //typedef vector<ushort>::type BoneHandleMap; //TODO: void _mergeSkeletonAnimations(const Skeleton* source, const BoneHandleMap& boneHandleMap, const StringVector& animations = StringVector()); //TODO: void _buildMapBoneByHandle(const Skeleton* source, BoneHandleMap& boneHandleMap) const; //TODO: void _buildMapBoneByName(const Skeleton* source,BoneHandleMap& boneHandleMap) const; // Ogre::SkeletonInstance //~SkeletonInstance(); void destroy_skeletoninstance(SkeletonInstanceHandle handle); //unsigned short getNumAnimations(void) const; ushort skeletoninstance_get_num_animations(const SkeletonInstanceHandle handle); //TODO: Animation* getAnimation(unsigned short index) const; //TODO: Animation* _getAnimationImpl(const String& name, const LinkedSkeletonAnimationSource** linker = 0) const; //TODO: Animation* createAnimation(const String& name, Real length); //TODO: Animation* getAnimation(const String& name, const LinkedSkeletonAnimationSource** linker = 0) const; //void removeAnimation(const String& name); void skeletoninstance_remove_animation(SkeletonInstanceHandle handle, const char* name); //TagPoint* createTagPointOnBone(Bone* bone, const Quaternion &offsetOrientation = Quaternion::IDENTITY,const Vector3 &offsetPosition = Vector3::ZERO); TagPointHandle skeletoninstance_create_tag_point_on_bone(SkeletonInstanceHandle handle, BoneHandle bone_handle, ref const(coiQuaternion) offset_orientation, ref const(coiVector3) offset_position); //void freeTagPoint(TagPoint* tagPoint); void skeletoninstance_free_tag_point(SkeletonInstanceHandle handle, TagPointHandle tag_point); //void addLinkedSkeletonAnimationSource(const String& skelName, Real scale = 1.0f); void skeletoninstance_add_linked_skeleton_animation_source(SkeletonInstanceHandle handle, const char* skel_name, coiReal scale); //void removeAllLinkedSkeletonAnimationSources(void); void skeletoninstance_remove_all_linked_skeleton_animation_sources(SkeletonInstanceHandle handle); //TODO: LinkedSkeletonAnimSourceIterator getLinkedSkeletonAnimationSourceIterator(void) const; //TODO: void _initAnimationState(AnimationStateSet* animSet); //TODO: void _refreshAnimationState(AnimationStateSet* animSet); //const String& getName(void) const; const(char*) skeletoninstance_get_name(const SkeletonInstanceHandle handle); //TODO: ResourceHandle getHandle(void) const; //const String& getGroup(void); const(char*) skeletoninstance_get_group(SkeletonInstanceHandle handle); // Ogre::SceneNode SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); ushort scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_get_position(SceneNodeHandle handle, ref coiVector3 pos); void scenenode_set_derived_position(SceneNodeHandle handle, const ref coiVector3 pos); void scenenode_get_derived_position(SceneNodeHandle handle, ref coiVector3 pos); //void setFixedYawAxis( bool useFixed, const Vector3& fixedAxis = Vector3::UNIT_Y ); void scenenode_set_fixed_yaw_axis(SceneNodeHandle handle, int use_fixed, const ref coiVector3 fixed_axis); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle, transform_space relative_to); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref coiColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); //Ogre::Viewport::setDimensions(float, float, float, float) void viewport_set_dimensions(ViewportHandle handle, coiReal left, coiReal top, coiReal width, coiReal height); //Ogre::Viewport::getActualDimensions(int&, int&, int&, int&) const void viewport_get_actual_dimensions(ViewportHandle handle, ref int left, ref int top, ref int width, ref int height); //Ogre::Viewport::getBackgroundColour() const void viewport_get_background_colour(ViewportHandle handle, ref coiColourValue cv); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, ref coiVector3 v3); void camera_get_up(CameraHandle handle, ref coiVector3 up); void camera_get_right(CameraHandle handle, ref coiVector3 right); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); void camera_roll(CameraHandle handle, coiReal angle); void camera_yaw(CameraHandle handle, coiReal angle); void camera_pitch(CameraHandle handle, coiReal angle); void camera_rotate(CameraHandle handle, const ref coiVector3 axis, coiReal angle); void camera_rotate_q(CameraHandle handle, const ref coiQuaternion q); //Ogre::Camera::setFixedYawAxis(bool, Ogre::Vector3 const&) void camera_set_fixed_yaw_axis(CameraHandle handle, int on, const ref coiVector3 fixed_axis); //Ogre::Camera::getOrientation() const void camera_get_orientation(CameraHandle handle, ref coiQuaternion orientation); //Ogre::Camera::setOrientation(Ogre::Quaternion const&) void camera_set_orientation(CameraHandle handle, const ref coiQuaternion orientation); //Ogre::Camera::getDerivedOrientation() const void camera_get_derived_orientation(CameraHandle handle, ref coiQuaternion orientation); //Ogre::Camera::getDerivedPosition() const void camera_get_derived_position(CameraHandle handle, ref coiVector3 position); //Ogre::Camera::getDerivedDirection() const void camera_get_derived_direction(CameraHandle handle, ref coiVector3 direction); //Ogre::Camera::getDerivedUp() const void camera_get_derived_up(CameraHandle handle, ref coiVector3 up); //Ogre::Camera::getDerivedRight() const void camera_get_derived_right(CameraHandle handle, ref coiVector3 right); //Ogre::Camera::setAutoTracking(bool, Ogre::SceneNode*, Ogre::Vector3 const&) void camera_set_autotracking(CameraHandle handle, int on, SceneNodeHandle sn_handle, const ref coiVector3 offset); //Ogre::Camera::setLodBias(float) void camera_set_lod_bias(CameraHandle handle, coiReal factor); //Ogre::Camera::getLodBias() const coiReal camera_get_lod_bias(CameraHandle handle); //Ogre::Camera::getCameraToViewportRay(float, float, Ogre::Ray*) const void camera_get_camera_to_viewport_ray(CameraHandle handle, coiReal screenx, coiReal screeny, RayHandle ray); //Ogre::Camera::setWindow(float, float, float, float) void camera_set_window(CameraHandle handle, coiReal left, coiReal top, coiReal right, coiReal bottom); SceneManagerHandle camera_get_scenemanager(CameraHandle handle); // Ogre::MovableObject /* As this is an abstract object, no need for construction. */ ///~MovableObject(); void destroy_movableobject(MovableObjectHandle handle); ///TODO: void _notifyCreator(MovableObjectFactory* fact); ///TODO: MovableObjectFactory* _getCreator(void) const; ///void _notifyManager(SceneManager* man); void movableobject__notify_manager(MovableObjectHandle handle, SceneManagerHandle man); ///SceneManager* _getManager(void) const; SceneManagerHandle movableobject__get_manager(const MovableObjectHandle handle); ///const String& getName(void) const; const(char*) movableobject_get_name(const MovableObjectHandle handle); ///const String& getMovableType(void) const = 0; const(char*) movableobject_get_movable_type(const MovableObjectHandle handle); ///Node* getParentNode(void) const; NodeHandle movableobject_get_parent_node(const MovableObjectHandle handle); ///SceneNode* getParentSceneNode(void) const; SceneNodeHandle movableobject_get_parent_scene_node(const MovableObjectHandle handle); ///bool isParentTagPoint() const; int movableobject_is_parent_tag_point(const MovableObjectHandle handle); ///void _notifyAttached(Node* parent, bool isTagPoint = false); void movableobject__notify_attached(MovableObjectHandle handle, NodeHandle parent, int is_tag_point); ///bool isAttached(void) const; int movableobject_is_attached(const MovableObjectHandle handle); ///void detachFromParent(void); void movableobject_detach_from_parent(MovableObjectHandle handle); ///bool isInScene(void) const; int movableobject_is_in_scene(const MovableObjectHandle handle); ///void _notifyMoved(void); void movableobject__notify_moved(MovableObjectHandle handle); ///void _notifyCurrentCamera(Camera* cam); void movableobject__notify_current_camera(MovableObjectHandle handle, CameraHandle cam); ///const AxisAlignedBox& getBoundingBox(void) const = 0; const(AxisAlignedBoxHandle) movableobject_get_bounding_box(const MovableObjectHandle handle); ///Real getBoundingRadius(void) const = 0; coiReal movableobject_get_bounding_radius(const MovableObjectHandle handle); ///const AxisAlignedBox& getWorldBoundingBox(bool derive = false) const; const(AxisAlignedBoxHandle) movableobject_get_world_bounding_box(const MovableObjectHandle handle, int derive); ///const Sphere& getWorldBoundingSphere(bool derive = false) const; const(SphereHandle) movableobject_get_world_bounding_sphere(const MovableObjectHandle handle, int derive); ///void _updateRenderQueue(RenderQueue* queue) = 0; //TODO:DLL void movableobject__update_render_queue(MovableObjectHandle handle, RenderQueueHandle queue); ///void setVisible(bool visible); void movableobject_set_visible(MovableObjectHandle handle, int visible); ///bool getVisible(void) const; int movableobject_get_visible(const MovableObjectHandle handle); ///bool isVisible(void) const; int movableobject_is_visible(const MovableObjectHandle handle); ///void setRenderingDistance(Real dist); void movableobject_set_rendering_distance(MovableObjectHandle handle, coiReal dist); ///Real getRenderingDistance(void) const; coiReal movableobject_get_rendering_distance(const MovableObjectHandle handle); ///void setRenderingMinPixelSize(Real pixelSize); void movableobject_set_rendering_min_pixel_size(MovableObjectHandle handle, coiReal pixel_size); ///Real getRenderingMinPixelSize() const; coiReal movableobject_get_rendering_min_pixel_size(const MovableObjectHandle handle); //void setUserAny(const Any& anything); XXX: deprecated //const Any& getUserAny(void) const; XXX: deprecated ///UserObjectBindings& getUserObjectBindings(); ///const UserObjectBindings& getUserObjectBindings() const; ///void setRenderQueueGroup(uint8 queueID); void movableobject_set_render_queue_group(MovableObjectHandle handle, ubyte queue_id); ///void setRenderQueueGroupAndPriority(uint8 queueID, ushort priority); void movableobject_set_render_queue_group_and_priority(MovableObjectHandle handle, ubyte queue_id, ushort priority); ///uint8 getRenderQueueGroup(void) const; ubyte movableobject_get_render_queue_group(const MovableObjectHandle handle); ///const Matrix4& _getParentNodeFullTransform(void) const; void movableobject__get_parent_node_full_transform(const MovableObjectHandle handle, ref coiMatrix4 result); ///void setQueryFlags(uint32 flags); void movableobject_set_query_flags(MovableObjectHandle handle, uint flags); ///void addQueryFlags(uint32 flags); void movableobject_add_query_flags(MovableObjectHandle handle, uint flags); ///void removeQueryFlags(uint32 flags); void movableobject_remove_query_flags(MovableObjectHandle handle, uint flags); ///uint32 getQueryFlags(void) const; uint movableobject_get_query_flags(const MovableObjectHandle handle); ///static void setDefaultQueryFlags(uint32 flags); void movableobject_set_default_query_flags(uint flags); ///static uint32 getDefaultQueryFlags(); uint movableobject_get_default_query_flags(); ///void setVisibilityFlags(uint32 flags) void movableobject_set_visibility_flags(MovableObjectHandle handle, uint flags); ///void addVisibilityFlags(uint32 flags); void movableobject_add_visibility_flags(MovableObjectHandle handle, uint flags); ///void removeVisibilityFlags(uint32 flags); void movableobject_remove_visibility_flags(MovableObjectHandle handle, uint flags); ///uint32 getVisibilityFlags(void) const; uint movableobject_get_visibility_flags(const MovableObjectHandle handle); ///static void setDefaultVisibilityFlags(uint32 flags); void movableobject_set_default_visibility_flags(uint flags); ///static uint32 getDefaultVisibilityFlags(); uint movableobject_get_default_visibility_flags(); ///void setListener(Listener* listener); //movableobject_set_listener(MovableObjectHandle handle, ///Listener* getListener(void) const; //movableobject_get_listener(MovableObjectHandle handle, ///const LightList& queryLights(void) const; size_t movableobject_query_lights(const MovableObjectHandle handle, LightHandle result); ///uint32 getLightMask() const; uint movableobject_get_light_mask(const MovableObjectHandle handle); ///void setLightMask(uint32 lightMask); void movableobject_set_light_mask(MovableObjectHandle handle, uint light_mask); ///LightList* _getLightList(); ///EdgeData* getEdgeList(void); ///bool hasEdgeList(void); int movableobject_has_edge_list(MovableObjectHandle handle); ///ShadowRenderableListIterator getShadowVolumeRenderableIterator(ShadowTechnique shadowTechnique, const Light* light, HardwareIndexBufferSharedPtr* indexBuffer, bool extrudeVertices, Real extrusionDist, unsigned long flags = 0); ///const AxisAlignedBox& getLightCapBounds(void) const; const(AxisAlignedBoxHandle) movableobject_get_light_cap_bounds(const MovableObjectHandle handle); ///const AxisAlignedBox& getDarkCapBounds(const Light& light, Real dirLightExtrusionDist) const; const(AxisAlignedBoxHandle) movableobject_get_dark_cap_bounds(const MovableObjectHandle handle, const LightHandle light, coiReal dir_light_extrusion_dist); ///void setCastShadows(bool enabled); void movableobject_set_cast_shadows(MovableObjectHandle handle, int enabled); ///bool getCastShadows(void) const; int movableobject_get_cast_shadows(const MovableObjectHandle handle); ///bool getReceivesShadows(); int movableobject_get_receives_shadows(MovableObjectHandle handle); ///Real getPointExtrusionDistance(const Light* l) const; coiReal movableobject_get_point_extrusion_distance(const MovableObjectHandle handle, const LightHandle l); ///uint32 getTypeFlags(void) const; uint movableobject_get_type_flags(const MovableObjectHandle handle); ///void visitRenderables(Renderable::Visitor* visitor,bool debugRenderables = false) = 0; ///void setDebugDisplayEnabled(bool enabled); void movableobject_set_debug_display_enabled(MovableObjectHandle handle, int enabled); ///bool isDebugDisplayEnabled(void) const; int movableobject_is_debug_display_enabled(const MovableObjectHandle handle); // Ogre::Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); ///Ogre::Entity::getNumSubEntities() const uint entity_get_num_sub_entities(const EntityHandle handle); //Ogre::Entity::clone(std::string const&) const EntityHandle entity_clone(const EntityHandle handle, const char* name); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(const EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); ///Ogre::Entity::setMaterialName(std::string const&, std::string const&) ///Ogre::Entity::setMaterial(Ogre::MaterialPtr const&) void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); ///Ogre::Entity::_notifyCurrentCamera(Ogre::Camera*) void entity__notify_current_camera(EntityHandle handle, CameraHandle cam); ///Ogre::Entity::setRenderQueueGroup(unsigned char) void entity_set_render_queue_group(EntityHandle handle, ubyte queue_id); ///Ogre::Entity::setRenderQueueGroupAndPriority(unsigned char, unsigned short) void entity_set_render_queue_group_and_priority(EntityHandle handle, ubyte queue_id, ushort priority); //Ogre::Entity::getBoundingBox() const const(AxisAlignedBoxHandle) entity_get_bounding_box(const EntityHandle handle); //Ogre::Entity::getBoundingRadius() const coiReal entity_get_bounding_radius(const EntityHandle handle); //Ogre::Entity::setDisplaySkeleton(bool) void entity_set_display_skeleton(EntityHandle handle, int display); //Ogre::Entity::getDisplaySkeleton() const int entity_get_display_skeleton(const EntityHandle handle); // Light LightHandle create_light(const char* light_name); void destroy_light(LightHandle handle); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); //Ogre::Light::getPosition() const void light_get_position(LightHandle handle, ref coiVector3 pos); //Ogre::Light::getPosition() const void light_get_position_xyz(LightHandle handle, ref float x, ref float y, ref float z); //Ogre::Light::getPosition() const void light_get_position_xyz(LightHandle handle, float* x, float* y, float* z); //Ogre::Light::setDirection(float, float, float) void light_set_direction_xyz(LightHandle handle, const float x, const float y, const float z); //Ogre::Light::setDirection(Ogre::Vector3 const&) void light_set_direction(LightHandle handle, const ref coiVector3 direction); //Ogre::Light::getDirection() const void light_get_direction(LightHandle handle, ref coiVector3 direction); //Ogre::Light::setSpotlightRange(Ogre::Radian const&, Ogre::Radian const&, float) void light_set_spotlight_range(LightHandle handle, const coiReal inner_angle, const coiReal outer_angle, coiReal fall_off); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref coiColourValue colour); void light_set_specular_colour(LightHandle handle, const ref coiColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameStarted started_cb, FrameQueued queued_cb, FrameEnded ended_cb, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); WindowListenerHandle add_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerEvent window_event, void* userdata); void remove_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerHandle listener_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(logging_level lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); //Log::logMessage void log_log_message(LogHandle handle, const char* message, log_message_level lml, int maskDebug); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); void render_window_get_custom_attribute(RenderWindowHandle handle, const char* attribute, void* pdata); uint render_window_get_width(RenderWindowHandle handle); uint render_window_get_height(RenderWindowHandle handle); void renderwindow_get_statistics(RenderWindowHandle handle, ref FrameStats stats); void renderwindow_get_statistics_ex(RenderWindowHandle handle, ref float lastFPS, ref float avgFPS, ref float bestFPS, ref float worstFPS); // ColourValue void colourvalue_zero(ref coiColourValue c); void colourvalue_black(ref coiColourValue c); void colourvalue_white(ref coiColourValue c); void colourvalue_red(ref coiColourValue c); void colourvalue_green(ref coiColourValue c); void colourvalue_blue(ref coiColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); void plane_get_normal(PlaneHandle handle, ref coiVector3 normal); void plane_set_normal(PlaneHandle handle, const ref coiVector3 normal); coiReal plane_get_d(PlaneHandle handle); void plane_set_d(PlaneHandle handle, coiReal d); // PlaneList (typedef vector<Plane>::type PlaneList) PlaneListHandle create_planelist(); void destroy_planelist(PlaneListHandle handle); // PlaneBoundedVolume PlaneBoundedVolumeHandle create_planeboundedvolume(plane_side the_outside); void destroy_planeboundedvolume(PlaneBoundedVolumeHandle handle); // bool intersects(const AxisAlignedBox&) const int planeboundedvolume_intersects_axisalignedbox(PlaneBoundedVolumeHandle handle, AxisAlignedBoxHandle query); // bool intersects(const Sphere&) const int planeboundedvolume_intersects_sphere(PlaneBoundedVolumeHandle handle, SphereHandle query); // std::pair<bool, Real> intersects(const Ray&) const void planeboundedvolume_intersects_ray(PlaneBoundedVolumeHandle handle, RayHandle query, ref ray_pair result); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); // Ogre::Timer int timer_set_option(TimerHandle handle, const char* key, void* value); c_ulong timer_get_milliseconds(TimerHandle handle); c_ulong timer_get_microseconds(TimerHandle handle); c_ulong timer_get_milliseconds_cpu(TimerHandle handle); c_ulong timer_get_microseconds_cpu(TimerHandle handle); void timer_reset(TimerHandle handle); // Ogre::AxisAlignedBox AxisAlignedBoxHandle create_axis_aligned_box(); AxisAlignedBoxHandle create_axis_aligned_box_ex(Extent e); AxisAlignedBoxHandle create_axis_aligned_box_v3(const ref coiVector3 min, const ref coiVector3 max); void destroy_axis_aligned_box(AxisAlignedBoxHandle handle); void axisalignedbox_get_size(AxisAlignedBoxHandle handle, ref coiVector3 size); void axisalignedbox_get_minimum(AxisAlignedBoxHandle handle, ref coiVector3 minimum); void axisalignedbox_get_maximum(AxisAlignedBoxHandle handle, ref coiVector3 maximum); void axisalignedbox_set_minimum_x(AxisAlignedBoxHandle handle, coiReal x); void axisalignedbox_set_minimum_y(AxisAlignedBoxHandle handle, coiReal y); void axisalignedbox_set_minimum_z(AxisAlignedBoxHandle handle, coiReal z); void axisalignedbox_set_minimum(AxisAlignedBoxHandle handle, const ref coiVector3 min); void axisalignedbox_set_maximum(AxisAlignedBoxHandle handle, const ref coiVector3 max); void axisalignedbox_set_maximum_x(AxisAlignedBoxHandle handle, coiReal x); void axisalignedbox_set_maximum_y(AxisAlignedBoxHandle handle, coiReal y); void axisalignedbox_set_maximum_z(AxisAlignedBoxHandle handle, coiReal z); void axisalignedbox_set_extents(AxisAlignedBoxHandle handle, const ref coiVector3 min, const ref coiVector3 max); void axisalignedbox_get_corner(AxisAlignedBoxHandle handle, CornerEnum e, ref coiVector3 corner); //Ogre::Ray RayHandle create_ray(const ref coiVector3 origin, const ref coiVector3 direction); void destroy_ray(RayHandle handle); //Ray::setOrigin void ray_set_origin(RayHandle handle, const ref coiVector3 origin); //Ray::getOrigin void ray_get_origin(RayHandle handle, ref coiVector3 origin); //Ray::setDirection void ray_set_direction(RayHandle handle, const ref coiVector3 direction); //Ray::getDirection void ray_get_direction(RayHandle handle, ref coiVector3 direction); //Ray::getPoint void ray_get_point(RayHandle handle, coiReal units, ref coiVector3 point); //Ray::intersects(Plane) void ray_intersects_plane(RayHandle handle, PlaneHandle plane_handle, ref ray_pair result); //Ray::intersects(AxisAlignedBox) void ray_intersects_axisalignedbox(RayHandle handle, AxisAlignedBoxHandle query_handle, ref ray_pair result); //Ray::intersects(Sphere) void ray_intersects_sphere(RayHandle handle, SphereHandle query_handle, ref ray_pair result); // Ogre::Sphere SphereHandle create_sphere(const ref coiVector3 center, coiReal radius); void destroy_sphere(SphereHandle handle); //void setRadius(Real) void sphere_set_radius(SphereHandle handle, coiReal radius); //Real getRadius(void) const coiReal sphere_get_radius(SphereHandle handle); //void setCenter(Vector3) void sphere_set_center(SphereHandle handle, const ref coiVector3 center); //Real getCenter(void) const void sphere_get_center(SphereHandle handle, ref coiVector3 center); // bool intersects(const Sphere&) const int sphere_intersects_sphere(SphereHandle handle, SphereHandle query); // bool intersects(const AxisAlignedBox&) const int sphere_intersects_axisalignedbox(SphereHandle handle, AxisAlignedBoxHandle query); // bool intersects(const Plane&) const int sphere_intersects_plane(SphereHandle handle, PlaneHandle query); // bool intersects(const Vector3&) const int sphere_intersects_vector3(SphereHandle handle, const ref coiVector3 query); // void merge(const Sphere&) void sphere_merge(SphereHandle handle, SphereHandle other_sphere); // Ogre::SceneQuery // SceneQuery::setQueryMask(uint32 mask) void scenequery_set_query_mask(SceneQueryHandle handle, uint32 mask); //uint32 SceneQuery::getQueryMask(void) const uint32 scenequery_get_query_mask(SceneQueryHandle handle); //void SceneQuery::setWorldFragmentType(enum WorldFragmentType wft); void scenequery_set_world_fragment_type(SceneQueryHandle handle, world_fragment_type wft); //WorldFragmentType SceneQuery::getWorldFragmentType(void) const; world_fragment_type scenequery_get_world_fragment_type(SceneQueryHandle handle); // SceneQueryListener SceneQueryListenerHandle create_scenequerylistener(SceneQueryFragmentResult fragment_callback, SceneQueryObjectResult object_callback, void* userdata); void destroy_scenequerylistener(SceneQueryListenerHandle handle); size_t scenequeryresult_movables_count(SceneQueryResultHandle handle); MovableObjectHandle scenequeryresult_movables_at(SceneQueryResultHandle handle, int index); size_t scenequeryresult_worldfragments_count(SceneQueryResultHandle handle, int index); void scenequeryresult_worldfragments_at(SceneQueryResultHandle handle, int index, ref world_fragment result); RaySceneQueryListenerHandle create_rayscenequerylistener(RaySceneQueryFragmentResult fragment_callback, RaySceneQueryObjectResult object_callback, void* userdata); void destroy_rayscenequerylistener(RaySceneQueryListenerHandle handle); //setRay void rayscenequery_set_ray(RaySceneQueryHandle handle, RayHandle ray_handle); //getRay RayHandle rayscenequery_get_ray(RaySceneQueryHandle handle); //void setSortByDistance(bool sort, ushort maxresults = 0); void rayscenequery_set_sort_by_distance(RaySceneQueryHandle handle, int on, ushort maxresults); //bool getSortByDistance(void) const; int rayscenequery_get_sort_by_distance(RaySceneQueryHandle handle); //ushort getMaxResults(void) const; ushort rayscenequery_get_max_results(RaySceneQueryHandle handle); // typedef vector<RaySceneQueryResultEntry>::type RaySceneQueryResult; size_t rayscenequeryresult_count(RaySceneQueryResultHandle handle); void rayscenequeryresult_at(RaySceneQueryResultHandle handle, int index, ref rayscenequery_result_entry result); // Ogre::Overlay //const String& getName(void) const; const(char*) overlay_get_name(OverlayHandle handle); //void setZOrder(ushort zorder); void overlay_set_zorder(OverlayHandle handle, ushort zorder); //ushort getZOrder(void) const; ushort overlay_get_zorder(OverlayHandle handle); //bool isVisible(void) const; int overlay_is_visible(OverlayHandle handle); //bool isInitialised(void) const; int overlay_is_initialised(OverlayHandle handle); //void show(void); void overlay_show(OverlayHandle handle); //void hide(void); void overlay_hide(OverlayHandle handle); //void add2D(OverlayContainer* cont); void overlay_add_2d(OverlayHandle handle, OverlayContainerHandle cont); //void remove2D(OverlayContainer* cont); void overlay_remove_2d(OverlayHandle handle, OverlayContainerHandle cont); //void add3D(SceneNode* node); void overlay_add_3d(OverlayHandle handle, SceneNodeHandle node_handle); //void remove3D(SceneNode* node); void overlay_remove_3d(OverlayHandle handle, SceneNodeHandle node_handle); // void clear(); void overlay_clear(OverlayHandle handle); //void setScroll(Real x, Real y); void overlay_set_scroll(OverlayHandle handle, coiReal x, coiReal y); //Real getScrollX(void) const; coiReal overlay_get_scroll_x(OverlayHandle handle); //Real getScrollY(void) const; coiReal overlay_get_scroll_y(OverlayHandle handle); //void scroll(Real xoff, Real yoff); void overlay_scroll(OverlayHandle handle, coiReal x, coiReal y); //void setRotate(const Radian& angle); void overlay_set_rotate(OverlayHandle handle, coiReal angle); //const Radian &getRotate(void) const; coiReal overlay_get_rotate(OverlayHandle handle); //void rotate(const Radian& angle); void overlay_rotate(OverlayHandle handle, coiReal angle); //void setScale(Real x, Real y); void overlay_set_scale(OverlayHandle handle, coiReal x, coiReal y); //Real getScaleX(void) const; coiReal overlay_get_scale_x(OverlayHandle handle); //Real getScaleY(void) const; coiReal overlay_get_scale_y(OverlayHandle handle); //void _getWorldTransforms(Matrix4* xform) const; void overlay_get_world_transforms(OverlayHandle handle, ref coiMatrix4 xform); //const String& getOrigin(void) const; const(char*) overlay_get_origin(OverlayHandle handle); //void _notifyOrigin(const String& origin); void overlay_notify_origin(OverlayHandle handle, const(char*) origin); //Ogre::OverlayManager //OverlayManager(); OverlayManagerHandle create_overlaymanager(); //~OverlayManager(); void destroy_overlaymanager(OverlayManagerHandle handle); //Real getLoadingOrder(void) const; coiReal overlaymanager_get_loading_order(OverlayManagerHandle handle); //Overlay* create(const String& name); OverlayHandle overlaymanager_create(OverlayManagerHandle handle, const char* name); //Overlay* getByName(const String& name); OverlayHandle overlaymanager_get_by_name(OverlayManagerHandle handle, const char* name); //void destroy(const String& name); void overlaymanager_destroy_by_name(OverlayManagerHandle handle, const char* name); //void destroy(Overlay* overlay); void overlaymanager_destroy(OverlayManagerHandle handle, OverlayHandle overlay_handle); //void destroyAll(void); void overlaymanager_destroy_all(OverlayManagerHandle handle); // XXX: for debugging. //void overlaymanager_list_overlays(OverlayManagerHandle handle); //bool hasViewportChanged(void) const; int overlaymanager_has_viewport_changed(OverlayManagerHandle handle); //int getViewportHeight(void) const; int overlaymanager_get_viewport_height(OverlayManagerHandle handle); //int getViewportWidth(void) const; int overlaymanager_get_viewport_width(OverlayManagerHandle handle); //Real getViewportAspectRatio(void) const; coiReal overlaymanager_get_viewport_aspect_ratio(OverlayManagerHandle handle); //OrientationMode getViewportOrientationMode(void) const; orientation_mode overlaymanager_get_viewport_orientation_mode(OverlayManagerHandle handle); //OverlayElement* createOverlayElement(const String& typeName, const String& instanceName, bool isTemplate = false); OverlayElementHandle overlaymanager_create_overlayelement(OverlayManagerHandle handle, const char* type_name, const char* instance_name, int is_template); //OverlayElement* getOverlayElement(const String& name, bool isTemplate = false); OverlayElementHandle overlaymanager_get_overlayelement(OverlayManagerHandle handle, const char* name, int is_template); //bool hasOverlayElement(const String& name, bool isTemplate = false); int overlaymanager_has_overlay_element(OverlayManagerHandle handle, const char* name, int is_template); //void destroyOverlayElement(const String& instanceName, bool isTemplate = false); void overlaymanager_destroy_overlay_element(OverlayManagerHandle handle, const char* name, int is_template); //void destroyOverlayElement(OverlayElement* pInstance, bool isTemplate = false); void overlaymanager_destroy_overlay_element_instance(OverlayManagerHandle handle, OverlayElementHandle instance, int is_template); //void destroyAllOverlayElements(bool isTemplate = false); void overlaymanager_destroy_all_overlay_elements(OverlayManagerHandle handle); //OverlayElement* createOverlayElementFromTemplate(const String& templateName, const String& typeName, const String& instanceName, bool isTemplate = false); OverlayElementHandle overlaymanager_create_overlayelement_from_template(OverlayManagerHandle handle, const char* template_name, const char* type_name, const char* instance_name, int is_template); //OverlayElement* cloneOverlayElementFromTemplate(const String& templateName, const String& instanceName); OverlayElementHandle overlaymanager_clone_overlayelement_from_template(OverlayManagerHandle handle, const char* template_name, const char* instance_name); //OverlayElement* createOverlayElementFromFactory(const String& typeName, const String& instanceName); OverlayElementHandle overlaymanager_create_overlayelement_from_factory(OverlayManagerHandle handle, const char* type_name, const char* instance_name); //bool isTemplate (String strName) const int overlaymanager_is_template(OverlayManagerHandle handle, const char* name); //static OverlayManager* getSingletonPtr(void); OverlayManagerHandle overlaymanager_get_singleton_ptr(); // Ogre::OverlayElement //~OverlayElement void destroy_overlayelement(OverlayElementHandle handle); //void initialise(void) void overlayelement_initialise(OverlayElementHandle handle); //const String& getName(void) const; const(char*) overlayelement_get_name(OverlayElementHandle handle); //void show(void); void overlayelement_show(OverlayElementHandle handle); //void hide(void); void overlayelement_hide(OverlayElementHandle handle); //bool isVisible(void) const; int overlayelement_is_visible(OverlayElementHandle handle); //bool isEnabled() const; int overlayelement_is_enabled(OverlayElementHandle handle); //void setEnabled(bool b); void overlayelement_set_enabled(OverlayElementHandle handle, int b); //void setDimensions(Real width, Real height); void overlayelement_set_dimensions(OverlayElementHandle handle, coiReal width, coiReal height); //void setPosition(Real left, Real top); void overlayelement_set_position(OverlayElementHandle handle, coiReal left, coiReal top); //void setWidth(Real width); void overlayelement_set_width(OverlayElementHandle handle, coiReal width); //Real getWidth(void) const; coiReal overlayelement_get_width(OverlayElementHandle handle); //void setHeight(Real height); void overlayelement_set_height(OverlayElementHandle handle, coiReal height); //Real getHeight(void) const; coiReal overlayelement_get_height(OverlayElementHandle handle); //void setLeft(Real left); void overlayelement_set_left(OverlayElementHandle handle, coiReal left); //Real getLeft(void) const; coiReal overlayelement_get_left(OverlayElementHandle handle); //void setTop(Real Top); void overlayelement_set_top(OverlayElementHandle handle, coiReal top); //Real getTop(void) const; coiReal overlayelement_get_top(OverlayElementHandle handle); //Real _getLeft(void) const; coiReal overlayelement__get_left(OverlayElementHandle handle); //Real _getTop(void) const; coiReal overlayelement__get_top(OverlayElementHandle handle); //Real _getWidth(void) const; coiReal overlayelement__get_width(OverlayElementHandle handle); //Real _getHeight(void) const; coiReal overlayelement__get_height(OverlayElementHandle handle); //void _setLeft(Real left); void overlayelement__set_left(OverlayElementHandle handle, coiReal left); //void _setTop(Real top); void overlayelement__set_top(OverlayElementHandle handle, coiReal top); //void _setWidth(Real width); void overlayelement__set_width(OverlayElementHandle handle, coiReal width); //void _setHeight(Real height); void overlayelement__set_height(OverlayElementHandle handle, coiReal height); //void _setPosition(Real left, Real top); void overlayelement__set_position(OverlayElementHandle handle, coiReal left, coiReal top); //void _setDimensions(Real width, Real height); void overlayelement__set_dimensions(OverlayElementHandle handle, coiReal width, coiReal height); //const String& getMaterialName(void) const; const(char*) overlayelement_get_material_name(OverlayElementHandle handle); //void setMaterialName(const String& matName); void overlayelement_set_material_name(OverlayElementHandle handle, const char* name); //void getWorldTransforms(Matrix4* xform) const; void overlayelement_get_world_transforms(OverlayElementHandle handle, ref coiMatrix4 xform); //void _positionsOutOfDate(void); void overlayelement__positions_out_of_date(OverlayElementHandle handle); //void _update(void); void overlayelement__update(OverlayElementHandle handle); //void _updateFromParent(void); void overlayelement__update_from_parent(OverlayElementHandle handle); //void _notifyParent(OverlayContainer* parent, Overlay* overlay); void overlayelement__notify_parent(OverlayElementHandle handle, OverlayContainerHandle parent_handle, OverlayHandle overlay_handle); //Real _getDerivedLeft(void); coiReal overlayelement__get_derived_left(OverlayElementHandle handle); //Real _getDerivedTop(void); coiReal overlayelement__get_derived_top(OverlayElementHandle handle); //Real _getRelativeWidth(void); coiReal overlayelement__get_relative_width(OverlayElementHandle handle); //Real _getRelativeHeight(void); coiReal overlayelement__get_relative_height(OverlayElementHandle handle); //ushort _notifyZOrder(ushort newZOrder); ushort overlayelement__notify_zorder(OverlayElementHandle handle, ushort new_zorder); //void _notifyWorldTransforms(const Matrix4& xform); void overlayelement__notify_world_transforms(OverlayElementHandle handle, const ref coiMatrix4 xform); //void _notifyViewport(); void overlayelement__notify_viewport(OverlayElementHandle handle); //const String& getTypeName(void) const; const(char*) overlayelement_get_type_name(OverlayElementHandle handle); //void setCaption(const DisplayString& text); void overlayelement_set_caption(OverlayElementHandle handle, const char* text); //const DisplayString& getCaption(void) const; const(char*) overlayelement_get_caption(OverlayElementHandle handle); //void setColour(const ColourValue& col); void overlayelement_set_colour(OverlayElementHandle handle, const ref coiColourValue col); //const ColourValue& getColour(void) const; void overlayelement_get_colour(OverlayElementHandle handle, ref coiColourValue col); //void setMetricsMode(GuiMetricsMode gmm); void overlayelement_set_metrics_mode(OverlayElementHandle handle, gui_metrics_mode gmm); //GuiMetricsMode getMetricsMode(void) const; gui_metrics_mode overlayelement_get_metrics_mode(OverlayElementHandle handle); //void setHorizontalAlignment(GuiHorizontalAlignment gha); void overlayelement_set_horizontal_alignment(OverlayElementHandle handle, gui_horizontal_alignment gha); //GuiHorizontalAlignment getHorizontalAlignment(void) const; gui_horizontal_alignment overlayelement_get_horizontal_alignment(OverlayElementHandle handle); //void setVerticalAlignment(GuiVerticalAlignment gva); void overlayelement_set_vertical_alignment(OverlayElementHandle handle, gui_vertical_alignment gva); //GuiVerticalAlignment getVerticalAlignment(void) const; gui_vertical_alignment overlayelement_get_vertical_alignment(OverlayElementHandle handle); //bool contains(Real x, Real y) const; int overlayelement_contains(OverlayElementHandle handle, coiReal x, coiReal y); //OverlayElement* findElementAt(Real x, Real y); OverlayElementHandle overlayelement_find_element_at(OverlayElementHandle handle, coiReal x, coiReal y); //bool isContainer() const; int overlayelement_is_container(OverlayElementHandle handle); //bool isKeyEnabled() const; int overlayelement_is_key_enabled(OverlayElementHandle handle); //bool isCloneable() const int overlayelement_is_cloneable(OverlayElementHandle handle); //void setCloneable(bool c); void overlayelement_set_cloneable(OverlayElementHandle handle, int c); //OverlayContainer* getParent(); OverlayContainerHandle overlayelement_get_parent(OverlayElementHandle handle); //void _setParent(OverlayContainer* parent); void overlayelement_set_parent(OverlayElementHandle handle, OverlayContainerHandle parent_handle); //ushort getZOrder() const; ushort overlayelement_get_zorder(OverlayElementHandle handle); //Real getSquaredViewDepth(const Camera* cam) const; coiReal overlayelement_get_squared_view_depth(OverlayElementHandle handle, CameraHandle camera_handle); //void copyFromTemplate(OverlayElement* templateOverlay); void overlayelement_copy_from_template(OverlayElementHandle handle, OverlayElementHandle template_handle); //OverlayElement* clone(const String& instanceName); OverlayElementHandle overlayelement_clone(OverlayElementHandle handle, const char* instance_name); //const OverlayElement* getSourceTemplate () const; const(OverlayElementHandle) overlayelement_get_source_template(OverlayElementHandle handle); // Ogre::OverlayContainer void destroy_overlaycontainer(OverlayContainerHandle handle); //void addChild(OverlayElement* elem); void overlaycontainer_add_child(OverlayContainerHandle handle, OverlayElementHandle child_handle); //void addChildImpl(OverlayElement* elem); void overlaycontainer_add_child_impl(OverlayContainerHandle handle, OverlayElementHandle child_handle); //void addChildImpl(OverlayContainer* cont); void overlaycontainer_add_child_container_impl(OverlayContainerHandle handle, OverlayContainerHandle child_handle); //void removeChild(const String& name); void overlaycontainer_remove_child(OverlayContainerHandle handle, const char* name); //OverlayElement* getChild(const String& name); OverlayElementHandle overlaycontainer_get_child(OverlayContainerHandle handle, const char* name); //void initialise(void); void overlaycontainer_initialise(OverlayContainerHandle handle); //void _addChild(OverlayElement* elem); void overlaycontainer__add_child(OverlayContainerHandle handle, OverlayElementHandle elem); //void _removeChild(OverlayElement* elem); void overlaycontainer__remove_child(OverlayContainerHandle handle, OverlayElementHandle elem); //void _removeChild(const String& name); void overlaycontainer__remove_child_by_name(OverlayContainerHandle handle, const char* name); //void _positionsOutOfDate(void); void overlaycontainer__positions_out_of_date(OverlayContainerHandle handle); //void _update(void); void overlaycontainer__update(OverlayContainerHandle handle); //ushort _notifyZOrder(ushort newZOrder); ushort overlaycontainer__notify_zorder(OverlayContainerHandle handle, ushort new_zorder); //void _notifyViewport(); void overlaycontainer__notify_viewport(OverlayContainerHandle handle); //void _notifyWorldTransforms(const Matrix4& xform); void overlaycontainer__notify_world_transforms(OverlayContainerHandle handle, const ref coiMatrix4 xform); //void _notifyParent(OverlayContainer* parent, Overlay* overlay); void overlaycontainer__notify_parent(OverlayContainerHandle handle, OverlayContainerHandle parent_handle, OverlayHandle overlay_handle); //bool isContainer() const; int overlaycontainer_is_container(OverlayContainerHandle handle); //bool isChildrenProcessEvents() const; int overlaycontainer_is_children_process_events(OverlayContainerHandle handle); //void setChildrenProcessEvents(bool val); void overlaycontainer_set_children_process_events(OverlayContainerHandle handle, int val); //OverlayElement* findElementAt(Real x, Real y); OverlayElementHandle overlaycontainer_find_element_at(OverlayContainerHandle handle, coiReal x, coiReal y); //void copyFromTemplate(OverlayElement* templateOverlay); void overlaycontainer_copy_from_template(OverlayContainerHandle handle, OverlayElementHandle template_overlay); //virtual OverlayElement* clone(const String& instanceName); OverlayElementHandle overlaycontainer_clone(OverlayContainerHandle handle, const char* instance_name); // Ogre::PanelOverlayElement //PanelOverlayElement(const String& name); PanelOverlayElementHandle create_paneloverlayelement(const char* name); //~PanelOverlayElement(); void destroy_paneloverlayelement(PanelOverlayElementHandle handle); //void initialise(void); void paneloverlayelement_initialise(PanelOverlayElementHandle handle); //void setTiling(Real x, Real y, ushort layer = 0); void paneloverlayelement_set_tiling(PanelOverlayElementHandle handle, coiReal x, coiReal y, ushort layer); //Real getTileX(ushort layer = 0) const; coiReal paneloverlayelement_get_tile_x(const PanelOverlayElementHandle handle, ushort layer); //Real getTileY(ushort layer = 0) const; coiReal paneloverlayelement_get_tile_y(const PanelOverlayElementHandle handle, ushort layer); //void setUV(Real u1, Real v1, Real u2, Real v2); void paneloverlayelement_set_uv(PanelOverlayElementHandle handle, coiReal u1, coiReal v1, coiReal u2, coiReal v2); //void getUV(Real& u1, Real& v1, Real& u2, Real& v2) const; void paneloverlayelement_get_uv(const PanelOverlayElementHandle handle, ref coiReal u1, ref coiReal v1, ref coiReal u2, ref coiReal v2); //void setTransparent(bool isTransparent); void paneloverlayelement_set_transparent(PanelOverlayElementHandle handle, int is_transparent); //bool isTransparent(void) const; int paneloverlayelement_is_transparent(const PanelOverlayElementHandle handle); //const String& getTypeName(void) const; const(char*) paneloverlayelement_get_type_name(const PanelOverlayElementHandle handle); //void getRenderOperation(RenderOperation& op); void paneloverlayelement_get_renderoperation(PanelOverlayElementHandle handle, RenderOperationHandle renderOp); //void setMaterialName(const String& matName); void paneloverlayelement_set_material_name(PanelOverlayElementHandle handle, const char* mat_name); //TODO: void _updateRenderQueue(RenderQueue* queue); // Ogre::TextAreaOverlayElement //TextAreaOverlayElement(const String& name); TextAreaOverlayElementHandle create_textareaoverlayelement(const char* name); //~TextAreaOverlayElement(); void destroy_textareaoverlayelement(TextAreaOverlayElementHandle handle); //void initialise(void); void textareaoverlayelement_initialise(TextAreaOverlayElementHandle handle); //void setCaption(const DisplayString& text); void textareaoverlayelement_set_caption(TextAreaOverlayElementHandle handle, const char* text); //void setCharHeight( Real height ); void textareaoverlayelement_set_char_height(TextAreaOverlayElementHandle handle, coiReal height); //Real getCharHeight() const; coiReal textareaoverlayelement_get_char_height(const TextAreaOverlayElementHandle handle); //void setSpaceWidth( Real width ); void textareaoverlayelement_set_space_width(TextAreaOverlayElementHandle handle, coiReal width); //Real getSpaceWidth() const; coiReal textareaoverlayelement_get_space_width(const TextAreaOverlayElementHandle handle); //void setFontName( const String& font ); void textareaoverlayelement_set_font_name(TextAreaOverlayElementHandle handle, const char* font); //const String& getFontName() const; const(char*) textareaoverlayelement_get_font_name(const TextAreaOverlayElementHandle handle); //const String& getTypeName(void) const; const(char*) textareaoverlayelement_get_type_name(const TextAreaOverlayElementHandle handle); //TODO: const MaterialPtr& getMaterial(void) const; //TODO: void getRenderOperation(RenderOperation& op); //void setMaterialName(const String& matName); void textareaoverlayelement_set_material_name(TextAreaOverlayElementHandle handle, const char* mat_name); //void setColour(const ColourValue& col); void textareaoverlayelement_set_colour(TextAreaOverlayElementHandle handle, ref const(coiColourValue) col); //const ColourValue& getColour(void) const; void textareaoverlayelement_get_colour(const TextAreaOverlayElementHandle handle, ref coiColourValue result); //void setColourBottom(const ColourValue& col); void textareaoverlayelement_set_colour_bottom(TextAreaOverlayElementHandle handle, ref const(coiColourValue) col); //const ColourValue& getColourBottom(void) const; void textareaoverlayelement_get_colour_bottom(const TextAreaOverlayElementHandle handle, ref coiColourValue result); //void setColourTop(const ColourValue& col); void textareaoverlayelement_set_colour_top(TextAreaOverlayElementHandle handle, ref const(coiColourValue) col); //const ColourValue& getColourTop(void) const; void textareaoverlayelement_get_colour_top(const TextAreaOverlayElementHandle handle, ref coiColourValue result); //void setAlignment( Alignment a ); void textareaoverlayelement_set_alignment(TextAreaOverlayElementHandle handle, textarea_overlayelement_alignment a); //Alignment getAlignment() const textarea_overlayelement_alignment textareaoverlayelement_get_alignment(const TextAreaOverlayElementHandle handle); //void setMetricsMode(GuiMetricsMode gmm); void textareaoverlayelement_set_metrics_mode(TextAreaOverlayElementHandle handle, gui_metrics_mode gmm); //void _update(void); void textareaoverlayelement__update(TextAreaOverlayElementHandle handle); // Ogre::VertexData //TODO: VertexData(HardwareBufferManagerBase* mgr = 0); //TODO: VertexData(VertexDeclaration* dcl, VertexBufferBinding* bind); //~VertexData(); void destroy_vertexdata(VertexDataHandle handle); //(see OgreHardwareVertexBuffer.h): VertexDeclaration* vertexDeclaration; //(see OgreHardwareVertexBuffer.h) VertexBufferBinding* vertexBufferBinding; //size_t vertexStart; size_t vertexdata_vertex_start(VertexDataHandle handle); // getter //size_t vertexCount; size_t vertexdata_vertex_count(VertexDataHandle handle); // getter //typedef vector<HardwareAnimationData>::type HardwareAnimationDataList; //HardwareAnimationDataList hwAnimationDataList; //size_t hwAnimDataItemsUsed; size_t vertexdata_hw_anim_data_items_used(VertexDataHandle handle); //VertexData* clone(bool copyData = true, HardwareBufferManagerBase* mgr = 0) const; VertexDataHandle vertexdata_clone(const VertexDataHandle handle, int copy_data); //void prepareForShadowVolume(void); void vertexdata_prepare_for_shadow_volume(VertexDataHandle handle); //HardwareVertexBufferSharedPtr hardwareShadowVolWBuffer; //TODO: void reorganiseBuffers(VertexDeclaration* newDeclaration, const BufferUsageList& bufferUsage, HardwareBufferManagerBase* mgr = 0); //TODO: void reorganiseBuffers(VertexDeclaration* newDeclaration, HardwareBufferManagerBase* mgr = 0); //void closeGapsInBindings(void); void vertexdata_close_gaps_in_bindings(VertexDataHandle handle); //void removeUnusedBuffers(void); void vertexdata_remove_unused_buffers(VertexDataHandle handle); //TODO:void convertPackedColour(VertexElementType srcType, VertexElementType destType); //ushort allocateHardwareAnimationElements(ushort count, bool animateNormals); ushort vertexdata_allocate_hardware_animation_elements(VertexDataHandle handle, ushort count, int animate_normals); // Ogre::IndexData //IndexData(); IndexDataHandle create_indexdata(); //~IndexData(); void destroy_indexdata(IndexDataHandle handle); //HardwareIndexBufferSharedPtr indexBuffer; //size_t indexStart; size_t indexdata_index_start(IndexDataHandle handle); //size_t indexCount; size_t indexdata_index_count(IndexDataHandle handle); //IndexData* clone(bool copyData = true, HardwareBufferManagerBase* mgr = 0) const; IndexDataHandle indexdata_clone(const IndexDataHandle handle, int copy_data); //void optimiseVertexCacheTriList(void); void indexdata_optimise_vertex_cache_tri_list(IndexDataHandle handle); // Ogre::RenderOperation RenderOperationHandle create_renderoperation(); void destroy_renderoperation(RenderOperationHandle handle); //VertexData *vertexData; VertexDataHandle renderoperation_get_vertex_data(RenderOperationHandle handle); void renderoperation_set_vertex_data(RenderOperationHandle handle, VertexDataHandle vertex_data); //OperationType operationType; operation_type renderoperation_get_operation_type(RenderOperationHandle handle); void renderoperation_set_operation_type(RenderOperationHandle handle, operation_type op_type); //bool useIndexes; int renderoperation_get_use_indexes(RenderOperationHandle handle); void renderoperation_set_use_indexes(RenderOperationHandle, bool use_indexes); //IndexData *indexData; IndexDataHandle renderoperation_get_index_data(RenderOperationHandle handle); void renderoperation_set_index_data(RenderOperationHandle handle, IndexDataHandle index_data); //TODO: const Renderable* srcRenderable; //size_t numberOfInstances; size_t renderoperation_get_number_of_instances(RenderOperationHandle handle); void renderoperation_set_number_of_instances(RenderOperationHandle handle, size_t num); //bool useGlobalInstancingVertexBufferIsAvailable; int renderoperation_get_use_global_instancing_vertex_buffer_is_available(RenderOperationHandle handle); void renderoperation_set_use_global_instancing_vertex_buffer_is_available(RenderOperationHandle handle, int use); // Ogre::ManualObject //ManualObject(const String& name); ManualObjectHandle create_manualobject(const char* name); //~ManualObject(); void destroy_manualobject(ManualObjectHandle handle); //void clear(void); void manualobject_clear(ManualObjectHandle handle); //void estimateVertexCount(size_t vcount); void manualobject_estimate_vertex_count(ManualObjectHandle handle, size_t vcount); //void estimateIndexCount(size_t icount); void manualobject_estimate_index_count(ManualObjectHandle handle, size_t icount); //void begin(const String& materialName, RenderOperation::OperationType opType = RenderOperation::OT_TRIANGLE_LIST, const String & groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); void manualobject_begin(ManualObjectHandle handle, const char* material_name, operation_type op_type, const char* group_name); //void setDynamic(bool dyn) void manualobject_set_dynamic(ManualObjectHandle handle, int dyn); //bool getDynamic() const int manualobject_get_dynamic(const ManualObjectHandle handle); //void beginUpdate(size_t sectionIndex); void manualobject_begin_update(ManualObjectHandle handle, size_t section_index); //void position(const Vector3& pos); //void position(Real x, Real y, Real z); void manualobject_position(ManualObjectHandle handle, ref const(coiVector3) pos); //void normal(const Vector3& norm); //void normal(Real x, Real y, Real z); void manualobject_normal(ManualObjectHandle handle, ref const(coiVector3) norm); //void tangent(const Vector3& tan); //void tangent(Real x, Real y, Real z); void manualobject_tangent(ManualObjectHandle handle, ref const(coiVector3) tan); //void textureCoord(Real u); void manualobject_texture_coord_u(ManualObjectHandle handle, coiReal u); //void textureCoord(Real u, Real v); //void textureCoord(Real u, Real v, Real w); //void textureCoord(Real x, Real y, Real z, Real w); //void textureCoord(const Vector2& uv); void manualobject_texture_coord_uv(ManualObjectHandle handle, ref const(coiVector2) uv); //void textureCoord(const Vector3& uvw); void manualobject_texture_coord_uvw(ManualObjectHandle handle, ref const(coiVector3) uvw); //void textureCoord(const Vector4& xyzw); void manualobject_texture_coord_xyxw(ManualObjectHandle handle, ref const(coiVector4) xyzw); //void colour(const ColourValue& col); void manualobject_colour(ManualObjectHandle handle, ref const(coiColourValue) col); //void colour(Real r, Real g, Real b, Real a = 1.0f); //void index(uint32 idx); void manualobject_index(ManualObjectHandle handle, uint32 idx); //void triangle(uint32 i1, uint32 i2, uint32 i3); void manualobject_triangle(ManualObjectHandle handle, uint32 i1, uint32 i2, uint32 i3); //void quad(uint32 i1, uint32 i2, uint32 i3, uint32 i4); void manualobject_quad(ManualObjectHandle handle, uint32 i1, uint32 i2, uint32 i3, uint32 i4); //size_t getCurrentVertexCount() const; size_t manualobject_get_current_vertex_count(const ManualObjectHandle handle); //size_t getCurrentIndexCount() const; size_t manualobject_get_current_index_count(const ManualObjectHandle handle); //ManualObjectSection* end(void); ManualObjectSectionHandle manualobject_end(ManualObjectHandle handle); //void setMaterialName(size_t subIndex, const String& name, const String & group = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); void manualobject_set_material_name(ManualObjectHandle handle, size_t sub_index, const char* name, const char* group); //MeshPtr convertToMesh(const String& meshName, const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); MeshHandle manualobject_convert_to_mesh(ManualObjectHandle handle, const char* mesh_name, const char* group_name); //void setUseIdentityProjection(bool useIdentityProjection); void manualobject_set_use_identity_projection(ManualObjectHandle handle, bool use_identity_projection); //bool getUseIdentityProjection(void) const; int manualobject_get_use_identity_projection(const ManualObjectHandle handle); //void setUseIdentityView(bool useIdentityView); void manualobject_set_use_identity_view(ManualObjectHandle handle, int use_identity_view); //bool getUseIdentityView(void) const; int manualobject_get_use_identity_view(const ManualObjectHandle handle); //void setBoundingBox(const AxisAlignedBox& box); void manualobject_set_bounding_box(ManualObjectHandle handle, const AxisAlignedBoxHandle box); //ManualObjectSection* getSection(unsigned int index) const; ManualObjectSectionHandle manualobject_get_section(const ManualObjectHandle handle, uint index); //unsigned int getNumSections(void) const; uint manualobject_get_num_sections(const ManualObjectHandle handle); //void setKeepDeclarationOrder(bool keepOrder); void manualobject_set_keep_declaration_order(ManualObjectHandle handle, int keep_order); //bool getKeepDeclarationOrder() const; int manualobject_get_keep_declaration_order(const ManualObjectHandle handle); //const String& getMovableType(void) const; const(char*) manualobject_get_movable_type(const ManualObjectHandle handle); //const AxisAlignedBox& getBoundingBox(void) const; const(AxisAlignedBoxHandle) manualobject_get_bounding_box(const ManualObjectHandle handle); //Real getBoundingRadius(void) const; coiReal manualobject_get_bounding_radius(const ManualObjectHandle handle); //TODO: void _updateRenderQueue(RenderQueue* queue); //TODO: EdgeData* getEdgeList(void); //bool hasEdgeList(void); int manualobject_has_edge_list(ManualObjectHandle handle); //TODO: ShadowRenderableListIterator getShadowVolumeRenderableIterator(ShadowTechnique shadowTechnique, const Light* light, HardwareIndexBufferSharedPtr* indexBuffer, bool extrudeVertices, Real extrusionDist, unsigned long flags = 0); // Ogre::ManualObject::ManualObjectSection //ManualObjectSection(ManualObject* parent, const String& materialName, RenderOperation::OperationType opType, const String & groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); ManualObjectSectionHandle create_manualobjectsection(ManualObjectHandle parent, const char* material_name, operation_type op_type, const char* group_name); //~ManualObjectSection(); void destroy_manualobjectsection(ManualObjectSectionHandle handle); //RenderOperation* getRenderOperation(void); RenderOperationHandle manualobjectsection_get_render_operation(ManualObjectSectionHandle handle); //const String& getMaterialName(void) const const(char*) manualobjectsection_get_material_name(const ManualObjectSectionHandle handle); //const String& getMaterialGroup(void) const const(char*) manualobjectsection_get_material_group(const ManualObjectSectionHandle handle); //void setMaterialName(const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ) void manualobjectsection_set_material_name(ManualObjectSectionHandle handle, const char* name, const char* group_name); //void set32BitIndices(bool n32) void manualobjectsection_set_32_bit_indices(ManualObjectSectionHandle handle, int n32); //bool get32BitIndices() const int manualobjectsection_get_32_bit_indices(const ManualObjectSectionHandle handle); //TODO:const MaterialPtr& getMaterial(void) const //void getRenderOperation(RenderOperation& op) void manualobjectsection_renderable_get_render_operation(ManualObjectSectionHandle handle, RenderOperationHandle renderOp); //void getWorldTransforms(Matrix4* xform) const void manualobjectsection_get_world_transforms(const ManualObjectSectionHandle handle, ref coiMatrix4 xform); //Real getSquaredViewDepth(const Ogre::Camera *) const coiReal manualobjectsection_get_squared_view_depth(const ManualObjectSectionHandle handle, const CameraHandle cam); //TODO: const LightList &getLights(void) const //Ogre::Resource::Listener ResourceListenerHandle create_resourcelistener(loadingCompleteCB loading_cb, preparingCompleteCB preparing_cb, unloadingCompleteCB unloading_cb, void* userdata); void destroy_resourcelistener(ResourceListenerHandle handle); // Ogre::Resource void destroy_resource(coiResourceHandle handle); //void prepare(bool backgroundThread = false) void resource_prepare(coiResourceHandle handle, int background_thread); //void load(bool backgroundThread = false) void resource_load(coiResourceHandle handle, int background_thread); //void reload() void resource_reload(coiResourceHandle handle); //bool isReloadable(void) const int resource_is_reloadable(const coiResourceHandle handle); //bool isManuallyLoaded(void) const int resource_is_manually_loaded(const coiResourceHandle handle); //void unload(void) void resource_unload(coiResourceHandle handle); //size_t getSize(void) const size_t resource_get_size(const coiResourceHandle handle); //void touch(void) void resource_touch(coiResourceHandle handle); //const String& getName(void) const const(char*) resource_get_name(const coiResourceHandle handle); //ResourceHandle getHandle(void) const ResourceHandle resource_get_handle(const coiResourceHandle handle); //bool isPrepared(void) const int resource_is_prepared(const coiResourceHandle handle); //bool isLoaded(void) const int resource_is_loaded(const coiResourceHandle handle); //bool isLoading() const int resource_is_loading(const coiResourceHandle handle); //LoadingState getLoadingState() const loading_state resource_get_loading_state(const coiResourceHandle handle); //bool isBackgroundLoaded(void) const int resource_is_background_loaded(const coiResourceHandle handle); //void setBackgroundLoaded(bool bl) void resource_set_background_loaded(coiResourceHandle handle, int bl); //void escalateLoading() void resource_escalate_loading(coiResourceHandle handle); //void addListener(Listener* lis) void resource_add_listener(coiResourceHandle handle, ResourceListenerHandle listener); //void removeListener(Listener* lis) void resource_remove_listener(coiResourceHandle handle, ResourceListenerHandle listener); //const String& getGroup(void) const const(char*) resource_get_group(const coiResourceHandle handle); //void changeGroupOwnership(const String& newGroup) void resource_change_group_ownership(coiResourceHandle handle, const char* new_group); //ResourceManager* getCreator(void) ResourceManagerHandle resource_get_creator(coiResourceHandle handle); //const String& getOrigin(void) const const(char*) resource_get_origin(const coiResourceHandle handle); //void _notifyOrigin(const String& origin) void resource__notify_origin(coiResourceHandle handle, const char* origin); //size_t getStateCount() const size_t resource_get_state_count(const coiResourceHandle handle); //void _dirtyState() void resource__dirty_state(coiResourceHandle handle); //void _fireLoadingComplete(bool wasBackgroundLoaded) void resource__fire_loading_complete(coiResourceHandle handle, int was_background_loaded); //void _firePreparingComplete(bool wasBackgroundLoaded) void resource__fire_preparing_complete(coiResourceHandle handle, int was_background_loaded); //void _fireUnloadingComplete(void) void resource__fire_unloading_complete(coiResourceHandle handle); //typedef SharedPtr<Resource> ResourcePtr //Ogre::ManualResourceLoader //~ManualResourceLoader() void destroy_manualresourceloader(ManualResourceLoaderHandle handle); //void prepareResource(Resource* resource) void manualresourceloader_prepare_resource(ManualResourceLoaderHandle handle, coiResourceHandle resource); //void loadResource(Resource* resource) void manualresourceloader_load_resource(ManualResourceLoaderHandle handle, coiResourceHandle resource); //Ogre::ResourceManager //~ResourceManager(); void destroy_resourcemanager(ResourceManagerHandle handle); //ResourcePtr create(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* createParams = 0) ResourcePtrHandle resourcemanager_create(ResourceManagerHandle handle, const char* name, const char* group, int is_manual, ManualResourceLoaderHandle l, const NameValuePairListHandle nvp) //typedef std::pair<ResourcePtr, bool> ResourceCreateOrRetrieveResult //TODO: ResourceCreateOrRetrieveResult createOrRetrieve(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* createParams = 0) //void setMemoryBudget( size_t bytes) void resourcemanager_set_memory_budget(ResourceManagerHandle handle, size_t bytes); //size_t getMemoryBudget(void) const size_t resourcemanager_get_memory_budget(const ResourceManagerHandle handle); //size_t getMemoryUsage(void) const size_t resourcemanager_get_memory_usage(const ResourceManagerHandle handle); //void unload(const String& name) void resourcemanager_unload_by_name(ResourceManagerHandle handle, const char* name); //void unload(ResourceHandle handle) void resourcemanager_unload_by_handle(ResourceManagerHandle handle, ResourceHandle res_handle); //void unloadAll(bool reloadableOnly = true) void resourcemanager_unload_all(ResourceManagerHandle handle, int reloadable_only); //void reloadAll(bool reloadableOnly = true) void resourcemanager_reload_all(ResourceManagerHandle handle, int reloadable_only); //void unloadUnreferencedResources(bool reloadableOnly = true) void resourcemanager_unload_unreferenced_resources(ResourceManagerHandle handle, int reloadable_only); //void reloadUnreferencedResources(bool reloadableOnly = true) void resourcemanager_reload_unreferenced_resources(ResourceManagerHandle handle, int reloadable_only); //void remove(ResourcePtr& r) void resourcemanager_remove_by_ptr(ResourceManagerHandle handle, ResourcePtrHandle resource_ptr); //void remove(const String& name) void resourcemanager_remove_by_name(ResourceManagerHandle handle, const char* name); //void remove(ResourceHandle handle) void resourcemanager_remove_by_handle(ResourceManagerHandle handle, ResourceHandle res_handle); //void removeAll(void) void resourcemanager_remove_all(ResourceManagerHandle handle); //void removeUnreferencedResources(bool reloadableOnly = true) void resourcemanager_remove_unreferenced_resources(ResourceManagerHandle handle, int reloadable_only); //ResourcePtr getByName(const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) ResourcePtrHandle resourcemanager_get_by_name(ResourceManagerHandle handle, const char* name, const char* group_name); //ResourcePtr getByHandle(ResourceHandle handle) ResourcePtrHandle resourcemanager_get_by_handle(ResourceManagerHandle handle, ResourceHandle res_handle); //bool resourceExists(const String& name) bool resourcemanager_exists_by_name(ResourceManagerHandle handle, const char* name); //bool resourceExists(ResourceHandle handle) bool resourcemanager_exists_by_handle(ResourceManagerHandle handle, ResourceHandle res_handle); //void _notifyResourceTouched(Resource* res) void resourcemanager__notify_resource_touched(ResourceManagerHandle handle, coiResourceHandle res); //void _notifyResourceLoaded(Resource* res) void resourcemanager__notify_resource_loaded(ResourceManagerHandle handle, coiResourceHandle res); //void _notifyResourceUnloaded(Resource* res) void resourcemanager__notify_resource_unloaded(ResourceManagerHandle handle, coiResourceHandle res); //ResourcePtr prepare(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0, bool backgroundThread = false) ResourcePtrHandle resourcemanager_prepare(ResourceManagerHandle handle, const char* name, const char* group, int is_manual, ManualResourceLoaderHandle loader, NameValuePairListHandle load_params, int background_thread); //ResourcePtr load(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0, bool backgroundThread = false) ResourcePtrHandle resourcemanager_load(ResourceManagerHandle handle, const char* name, const char* group, int is_manual, ManualResourceLoaderHandle loader, NameValuePairListHandle load_params, int background_thread); //TODO:const StringVector& getScriptPatterns(void) const //TODO: void parseScript(DataStreamPtr& stream, const String& groupName) //Real getLoadingOrder(void) const coiReal resourcemanager_get_loading_order(const ResourceManagerHandle handle); //const String& getResourceType(void) const const(char*) resourcemanager_get_resource_type(const ResourceManagerHandle handle); //void setVerbose(bool v) void resourcemanager_set_verbose(ResourceManagerHandle handle, int v); //bool getVerbose(void) bool resourcemanager_get_verbose(ResourceManagerHandle handle); ditto /****************************************************************************** * ogre_interface.d - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; private import core.stdc.config : c_long, c_ulong; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgreResource.h alias ulong ResourceHandle; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* NodeHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* ManualObjectHandle; alias void* ManualObjectSectionHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* PlaneListHandle; alias void* PlaneBoundedVolumeHandle; alias void* MeshHandle; alias void* TimerHandle; alias void* WindowListenerHandle; alias void* AxisAlignedBoxHandle; alias void* RayHandle; alias void* SphereHandle; alias void* BoneHandle; alias void* TagPointHandle; alias void* SkeletonHandle; alias void* SkeletonInstanceHandle; alias void* SceneQueryHandle; alias void* RaySceneQueryHandle; alias void* RaySceneQueryResultHandle; alias void* SceneQueryListenerHandle; alias void* RaySceneQueryListenerHandle; alias void* SceneQueryResultHandle; alias void* MovableObjectHandle; alias void* RenderOperationHandle; alias void* OverlayHandle; alias void* OverlayManagerHandle; alias void* OverlayElementHandle; alias void* PanelOverlayElementHandle; alias void* TextAreaOverlayElementHandle; alias void* OverlayContainerHandle; alias void* VertexDataHandle; alias void* IndexDataHandle; alias void* coiResourceHandle; alias void* ResourcePtrHandle; alias void* ManualResourceLoaderHandle; alias void* ResourceManagerHandle; alias void* ResourceListenerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; //alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; //Ogre::FrameListener callbacks. alias int function(ref const(FrameEvent) event, void* userdata) FrameStarted; alias int function(ref const(FrameEvent) event, void* userdata) FrameEnded; alias int function(ref const(FrameEvent) event, void* userdata) FrameQueued; alias int function(const ref world_fragment frag, void* userdata) SceneQueryFragmentResult; alias int function(MovableObjectHandle handle, void* userdata) SceneQueryObjectResult; alias int function(const ref world_fragment frag, coiReal distance, void* userdata) RaySceneQueryFragmentResult; alias int function(MovableObjectHandle handle, coiReal distance, void* userdata) RaySceneQueryObjectResult; //Ogre::Resource::Listener callbacks alias void function(coiResourceHandle handle, void* userdata) loadingCompleteCB; alias void function(coiResourceHandle handle, void* userdata) preparingCompleteCB; alias void function(coiResourceHandle handle, void* userdata) unloadingCompleteCB; struct coiQuaternion { coiReal w; coiReal x; coiReal y; coiReal z; } struct coiVector2 { coiReal x; coiReal y; } struct coiVector3 { coiReal x; coiReal y; coiReal z; } struct coiVector4 { coiReal x; coiReal y; coiReal z; coiReal w; } struct coiMatrix3 { coiReal m[3][3]; } struct coiMatrix4 { coiReal m[4][4]; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; } struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ray_pair { int intersects; coiReal distance; } struct coiColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; c_ulong bestFrameTime; c_ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; struct world_fragment { world_fragment_type fragment_type; coiVector3 single_intersection; PlaneListHandle planes; void* geometry; RenderOperationHandle render_op; } struct rayscenequery_result_entry { coiReal distance; MovableObjectHandle movable; world_fragment* fragment; } struct hardware_animation_data { ushort target_buffer_index; coiReal parametric; }; enum logging_level { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum log_message_level { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum orientation_mode { OR_DEGREE_0 = 0, OR_DEGREE_90 = 1, OR_DEGREE_180 = 2, OR_DEGREE_270 = 3, OR_PORTRAIT = OR_DEGREE_0, OR_LANDSCAPERIGHT = OR_DEGREE_90, OR_LANDSCAPELEFT = OR_DEGREE_270 } enum projection_type { PT_ORTHOGRAPHIC, PT_PERSPECTIVE } enum frustum_plane { FRUSTUM_PLANE_NEAR = 0, FRUSTUM_PLANE_FAR = 1, FRUSTUM_PLANE_LEFT = 2, FRUSTUM_PLANE_RIGHT = 3, FRUSTUM_PLANE_TOP = 4, FRUSTUM_PLANE_BOTTOM = 5 } enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF } enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; // OgreResource.h enum loading_state { LOADSTATE_UNLOADED, LOADSTATE_LOADING, LOADSTATE_LOADED, LOADSTATE_UNLOADING, LOADSTATE_PREPARED, LOADSTATE_PREPARING }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { LT_POINT = 0, LT_DIRECTIONAL = 1, LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; enum Extent { EXTENT_NULL, EXTENT_FINITE, EXTENT_INFINITE }; enum CornerEnum { FAR_LEFT_BOTTOM = 0, FAR_LEFT_TOP = 1, FAR_RIGHT_TOP = 2, FAR_RIGHT_BOTTOM = 3, NEAR_RIGHT_BOTTOM = 7, NEAR_LEFT_BOTTOM = 6, NEAR_LEFT_TOP = 5, NEAR_RIGHT_TOP = 4 }; enum plane_side { NO_SIDE, POSITIVE_SIDE, NEGATIVE_SIDE, BOTH_SIDE }; enum world_fragment_type { WFT_NONE, WFT_PLANE_BOUNDED_REGION, WFT_SINGLE_INTERSECTION, WFT_CUSTOM_GEOMETRY, WFT_RENDER_OPERATION }; enum gui_metrics_mode { GMM_RELATIVE, GMM_PIXELS, GMM_RELATIVE_ASPECT_ADJUSTED }; enum gui_horizontal_alignment { GHA_LEFT, GHA_CENTER, GHA_RIGHT }; enum gui_vertical_alignment { GVA_TOP, GVA_CENTER, GVA_BOTTOM }; enum textarea_overlayelement_alignment { Left, Right, Center }; enum skeleton_animation_blend_mode { ANIMBLEND_AVERAGE = 0, ANIMBLEND_CUMULATIVE = 1 }; enum operation_type { OT_POINT_LIST = 1, OT_LINE_LIST = 2, OT_LINE_STRIP = 3, OT_TRIANGLE_LIST = 4, OT_TRIANGLE_STRIP = 5, OT_TRIANGLE_FAN = 6 }; // OgreCommon.h enum compare_function { CMPF_ALWAYS_FAIL, CMPF_ALWAYS_PASS, CMPF_LESS, CMPF_LESS_EQUAL, CMPF_EQUAL, CMPF_NOT_EQUAL, CMPF_GREATER_EQUAL, CMPF_GREATER }; enum texture_filter_options { TFO_NONE, TFO_BILINEAR, TFO_TRILINEAR, TFO_ANISOTROPIC } enum filter_type { FT_MIN, FT_MAG, FT_MIP }; enum filter_options { FO_NONE, FO_POINT, FO_LINEAR, FO_ANISOTROPIC }; enum shade_options { SO_FLAT, SO_GOURAUD, SO_PHONG }; enum fog_mode { FOG_NONE, FOG_EXP, FOG_EXP2, FOG_LINEAR }; enum culling_mode { CULL_NONE = 1, CULL_CLOCKWISE = 2, CULL_ANTICLOCKWISE = 3 }; enum manual_culling_mode { MANUAL_CULL_NONE = 1, MANUAL_CULL_BACK = 2, MANUAL_CULL_FRONT = 3 }; enum waveform_type { WFT_SINE, WFT_TRIANGLE, WFT_SQUARE, WFT_SAWTOOTH, WFT_INVERSE_SAWTOOTH, WFT_PWM }; enum polygon_mode { PM_POINTS = 1, PM_WIREFRAME = 2, PM_SOLID = 3 }; enum shadow_technique { SHADOWTYPE_NONE = 0x00, SHADOWDETAILTYPE_ADDITIVE = 0x01, SHADOWDETAILTYPE_MODULATIVE = 0x02, SHADOWDETAILTYPE_INTEGRATED = 0x04, SHADOWDETAILTYPE_STENCIL = 0x10, SHADOWDETAILTYPE_TEXTURE = 0x20, SHADOWTYPE_STENCIL_MODULATIVE = 0x12, SHADOWTYPE_STENCIL_ADDITIVE = 0x11, SHADOWTYPE_TEXTURE_MODULATIVE = 0x22, SHADOWTYPE_TEXTURE_ADDITIVE = 0x21, SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED = 0x25, SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED = 0x26 }; alias int track_vertex_colour_type; enum track_vertex_colour_enum { TVC_NONE = 0x0, TVC_AMBIENT = 0x1, TVC_DIFFUSE = 0x2, TVC_SPECULAR = 0x4, TVC_EMISSIVE = 0x8 } enum sort_mode { SM_DIRECTION, SM_DISTANCE }; enum frame_buffer_type { FBT_COLOUR = 0x1, FBT_DEPTH = 0x2, FBT_STENCIL = 0x4 }; enum instance_manager_flags { IM_USE16BIT = 0x0001, IM_VTFBESTFIT = 0x0002, IM_VTFBONEMATRIXLOOKUP = 0x0004, IM_USEBONEDUALQUATERNIONS = 0x0008, IM_USEONEWEIGHT = 0x0010, IM_FORCEONEWEIGHT = 0x0020, IM_USEALL = IM_USE16BIT|IM_VTFBESTFIT|IM_USEONEWEIGHT }; enum clip_result { CLIPPED_NONE = 0, CLIPPED_SOME = 1, CLIPPED_ALL = 2 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); TimerHandle root_get_timer(); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, c_ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char* plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); //createManualObject(std::string const&) ManualObjectHandle scenemanager_create_manual_object(SceneManagerHandle handle, const char* name); //createManualObject() ManualObjectHandle scenemanager_create_manual_object_unnamed(SceneManagerHandle handle); //getManualObject(std::string const&) const ManualObjectHandle scenemanager_get_manual_object(const SceneManagerHandle handle, const char* name); //hasManualObject(std::string const&) const int scenemanager_has_manual_object(const SceneManagerHandle handle, const char* name); //destroyManualObject(Ogre::ManualObject*) void scenemanager_destroy_manual_object(SceneManagerHandle handle, ManualObjectHandle obj); //destroyManualObject(std::string const&) void scenemanager_destroy_manual_object_by_name(SceneManagerHandle handle, const char* name); //destroyAllManualObjects() void scenemanager_destroy_all_manual_objects(SceneManagerHandle handle); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); void scenemanager_set_sky_box(SceneManagerHandle handle, int enable, const char* material_name, float distance, int draw_first, const coiQuaternion* orientation, const char* group_name); void scenemanager_set_sky_dome(SceneManagerHandle handle, int enable, const char* material_name, float curvature, float tiling, float distance, int draw_first, const coiQuaternion* orientation, int xsegments, int ysegments, int ysegments_keep, const char* group_name); const(char*) scenemanager_get_name(SceneManagerHandle handle); //void SceneManager::destroyQuery(Ogre::SceneQuery* query); void scenemanager_destroy_scenequery(SceneManagerHandle handle, SceneQueryHandle query); // Ogre::SceneManager::createRayQuery(Ogre::Ray const&, unsigned long) RaySceneQueryHandle scenemanager_create_rayquery(SceneQueryHandle handle, RayHandle ray_handle, c_ulong mask); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Ogre::Node //Ogre::Node::getName() const const(char*) node_get_name(NodeHandle handle); //Ogre::Node::getParent() const //XXX: May be NULL if this is the root node. NodeHandle node_get_parent(NodeHandle handle); //Ogre::Node::getOrientation() const void node_get_orientation(NodeHandle handle, ref coiQuaternion result); //Ogre::Node::setOrientation(Ogre::Quaternion const&) void node_set_orientation(NodeHandle handle, const ref coiQuaternion orientation); //Ogre::Node::setScale(Ogre::Vector3 const&) void node_set_scale(NodeHandle handle, const ref coiVector3 in_scale); //Ogre::Node::setScale(Ogre::Vector3 const&) void node_set_scale_xyz(NodeHandle handle, const float x, const float y, const float z); //Ogre::Node::getScale() const void node_get_scale(NodeHandle handle, ref coiVector3 result); //Ogre::Node::setInheritOrientation(bool) void node_set_inherit_orientation(NodeHandle handle, int inherit); //Ogre::Node::getInheritOrientation() const int node_get_inherit_orientation(NodeHandle handle); //Ogre::Node::resetOrientation() void node_reset_orientation(NodeHandle handle); //Ogre::Node::setInheritScale(bool) void node_set_inherit_scale(NodeHandle handle, int inherit); //Ogre::Node::getInheritScale() const int node_get_inherit_scale(NodeHandle handle); //Ogre::Node::scale(Ogre::Vector3 const&) void node_scale(NodeHandle handle, const ref coiVector3 scale); //Ogre::Node::scale(Ogre::Vector3 const&) void node_scale_xyz(NodeHandle handle, const float x, const float y, const float z); //Ogre::Node::translate(Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate(NodeHandle handle, const ref coiVector3 d, transform_space relative_to); //Ogre::Node::translate(Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate_xyz(NodeHandle handle, const float x, const float y, const float z, transform_space relative_to); //Ogre::Node::translate(Ogre::Matrix3 const&, float, float, float, Ogre::Node::TransformSpace) //Ogre::Node::translate(Ogre::Matrix3 const&, Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate_m(NodeHandle handle, const ref coiMatrix3 axes, const ref coiVector3 move, transform_space relative_to); //Ogre::Node::roll(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_roll(NodeHandle handle, const coiReal angle, transform_space relative_to); //Ogre::Node::pitch(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_pitch(NodeHandle handle, const coiReal angle, transform_space relative_to); // Ogre::Node::yaw(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_yaw(NodeHandle handle, const coiReal angle, transform_space relative_to); //Ogre::Node::rotate(Ogre::Vector3 const&, Ogre::Radian const&, Ogre::Node::TransformSpace) void node_rotate(NodeHandle handle, const ref coiVector3 axis, const coiReal angle, transform_space relative_to); //Ogre::Node::rotate(Ogre::Quaternion const&, Ogre::Node::TransformSpace) void node_rotate_q(NodeHandle handle, const ref coiQuaternion q, transform_space relative_to); //Ogre::Node::getLocalAxes() const void node_get_local_axes(NodeHandle handle, ref coiMatrix3 result); //Ogre::Node::createChild(Ogre::Vector3 const&, Ogre::Quaternion const&) NodeHandle node_create_child(NodeHandle handle, const ref coiVector3 translate, const ref coiQuaternion rotate); //Ogre::Node::createChild(std::string const&, Ogre::Vector3 const&, Ogre::Quaternion const&) NodeHandle node_create_named_child(NodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); //Ogre::Node::addChild(Ogre::Node*) void node_add_child(NodeHandle handle, NodeHandle child); //Ogre::Node::numChildren() const ushort node_num_children(const NodeHandle handle); //Ogre::Node::getChild(unsigned short) const NodeHandle node_get_child_by_index(const NodeHandle handle, ushort index); //Ogre::Node::getChild(std::string const&) const NodeHandle node_get_child_by_name(const NodeHandle handle, const char* name); //Ogre::Node::removeChild(unsigned short) NodeHandle node_remove_child_by_index(NodeHandle handle, ushort index); //Ogre::Node::removeChild(Ogre::Node*) NodeHandle node_remove_child(NodeHandle handle, NodeHandle child); //Ogre::Node::removeChild(std::string const&) NodeHandle node_remove_child_by_name(NodeHandle handle, const char* name); //Ogre::Node::removeAllChildren() void node_remove_all_children(NodeHandle handle); //Ogre::Node::_setDerivedPosition(Ogre::Vector3 const&) void node__set_derived_position(NodeHandle handle, ref const(coiVector3) position); //Ogre::Node::_setDerivedOrientation(Ogre::Quaternion const&) void node__set_derived_orientation(NodeHandle handle, ref const(coiQuaternion) orientation); //Ogre::Node::_getDerivedOrientation() const void node__get_derived_orientation(const NodeHandle handle, ref coiQuaternion orientation); //Ogre::Node::_getDerivedPosition() const void node__get_derived_position(const NodeHandle handle, ref coiVector3 position); //Ogre::Node::_getDerivedScale() const void node__get_derived_scale(const NodeHandle handle, ref coiVector3 scale); // Ogre::Bone //Bone(unsigned short handle, Skeleton* creator); BoneHandle create_bone(ushort handle, SkeletonHandle creator); //Bone(const String& name, unsigned short handle, Skeleton* creator); BoneHandle create_named_bone(const char* name, ushort handle, SkeletonHandle creator); //~Bone(); void destroy_bone(BoneHandle handle); //Bone* createChild(unsigned short handle, const Vector3& translate = Vector3::ZERO, const Quaternion& rotate = Quaternion::IDENTITY); BoneHandle bone_create_child(BoneHandle handle, ushort hnd, ref const(coiVector3) translate, ref const(coiQuaternion) rotate); //unsigned short getHandle(void) const; ushort bone_get_handle(const BoneHandle handle); //void setBindingPose(void); void bone_set_binding_pose(BoneHandle handle); //void reset(void); void bone_reset(BoneHandle handle); //void setManuallyControlled(bool manuallyControlled); void bone_set_manually_controlled(BoneHandle handle, int manually_controlled); //bool isManuallyControlled() const; int bone_is_manually_controlled(const BoneHandle handle); //void _getOffsetTransform(Matrix4& m) const; void bone__get_offset_transform(const BoneHandle handle, ref coiMatrix4 m); //const Vector3& _getBindingPoseInverseScale(void) const; void bone__get_binding_pose_inverse_scale(const BoneHandle handle, ref coiVector3 result); //const Vector3& _getBindingPoseInversePosition(void) const; void bone__get_binding_pose_inverse_position(const BoneHandle handle, ref coiVector3 result); //const Quaternion& _getBindingPoseInverseOrientation(void) const; void bone__get_binding_pose_inverse_orientation(const BoneHandle handle, ref coiQuaternion result); //void needUpdate(bool forceParentUpdate = false); void bone_need_update(BoneHandle handle, int force_parent_update); // Ogre::TagPoint //TagPoint(unsigned short handle, Skeleton* creator); TagPointHandle create_tagpoint(ushort bone_handle, SkeletonHandle creator); //~TagPoint(); void destroy_tagpoint(TagPointHandle handle); //Entity *getParentEntity(void) const; EntityHandle tagpoint_get_parent_entity(const TagPointHandle handle); //MovableObject* getChildObject(void) const; MovableObjectHandle tagpoint_get_child_object(const TagPointHandle handle); //void setParentEntity(Entity *pEntity); void tagpoint_set_parent_entity(TagPointHandle handle, EntityHandle entity); //void setChildObject(MovableObject *pObject); void tagpoint_set_child_object(TagPointHandle handle, MovableObjectHandle obj); //void setInheritParentEntityOrientation(bool inherit); void tagpoint_set_inherit_parent_entity_orientation(TagPointHandle handle, int inherit); //bool getInheritParentEntityOrientation(void) const; int tagpoint_get_inherit_parent_entity_orientation(const TagPointHandle handle); //void setInheritParentEntityScale(bool inherit); void tagpoint_set_inherit_parent_entity_scale(TagPointHandle handle, int inherit); //bool getInheritParentEntityScale(void) const; int tagpoint_get_inherit_parent_entity_scale(const TagPointHandle handle); //const Matrix4& getParentEntityTransform(void) const; void tagpoint_get_parent_entity_transform(const TagPointHandle handle, ref coiMatrix4 result); //const Matrix4& _getFullLocalTransform(void) const; void tagpoint__get_full_local_transform(const TagPointHandle handle, ref coiMatrix4 result); //void needUpdate(bool forceParentUpdate = false); void tagpoint_need_update(TagPointHandle handle, int force_parent_update); //void updateFromParentImpl(void) const; void tagpoint_update_from_parent_impl(const TagPointHandle handle); //TODO: const LightList& getLights(void) const; // Ogre::Skeleton //Skeleton(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual = false, ManualResourceLoader* loader = 0); //~Skeleton(); void destroy_skeleton(SkeletonHandle handle); //Bone* createBone(void); BoneHandle skeleton_create_bone(SkeletonHandle handle); //Bone* createBone(unsigned short handle); BoneHandle skeleton_create_bone_with_handle(SkeletonHandle handle, ushort bone_handle); //Bone* createBone(const String& name); BoneHandle skeleton_create_bone_with_name(SkeletonHandle handle, const char* name); //Bone* createBone(const String& name, unsigned short handle); BoneHandle skeleton_create_bone_with_name_and_handle(SkeletonHandle handle, const char* name, ushort bone_handle); //unsigned short getNumBones(void) const; ushort skeleton_get_num_bones(const SkeletonHandle handle); //Bone* getRootBone(void) const; BoneHandle skeleton_get_root_bone(const SkeletonHandle handle); //typedef vector<Bone*>::type BoneList; //typedef VectorIterator<BoneList> BoneIterator; //TODO: BoneIterator getRootBoneIterator(void); //TODO: BoneIterator getBoneIterator(void); //Bone* getBone(unsigned short handle) const; BoneHandle skeleton_get_bone_by_handle(const SkeletonHandle handle, ushort bone_handle); //Bone* getBone(const String& name) const; BoneHandle skeleton_get_bone_by_name(const SkeletonHandle handle, const char* name); //bool hasBone(const String& name) const; int skeleton_has_bone(const SkeletonHandle handle, const char* name); //void setBindingPose(void); void skeleton_set_binding_pose(SkeletonHandle handle); //void reset(bool resetManualBones = false); void skeleton_reset(SkeletonHandle handle, int reset_manual_bones); //TODO: Animation* createAnimation(const String& name, Real length); //TODO: Animation* getAnimation(const String& name, const LinkedSkeletonAnimationSource** linker) const; //TODO: Animation* getAnimation(const String& name) const; //TODO: Animation* _getAnimationImpl(const String& name, const LinkedSkeletonAnimationSource** linker = 0) const; //bool hasAnimation(const String& name) const; int skeleton_has_animation(const SkeletonHandle handle, const char* name); //void removeAnimation(const String& name); void skeleton_remove_animation(SkeletonHandle handle, const char* name); //TODO: void setAnimationState(const AnimationStateSet& animSet); //TODO: void _initAnimationState(AnimationStateSet* animSet); //TODO: void _refreshAnimationState(AnimationStateSet* animSet); //void _getBoneMatrices(Matrix4* pMatrices); void skeleton__get_bone_matrices(SkeletonHandle handle, ref coiMatrix4[] matrices); //unsigned short getNumAnimations(void) const; ushort skeleton_get_num_animations(const SkeletonHandle handle); //TODO: Animation* getAnimation(unsigned short index) const; //SkeletonAnimationBlendMode getBlendMode() const; skeleton_animation_blend_mode skeleton_get_blend_mode(const SkeletonHandle handle); //void setBlendMode(SkeletonAnimationBlendMode state); void skeleton_set_blend_mode(SkeletonHandle handle, skeleton_animation_blend_mode state); //void _updateTransforms(void); void skeleton__update_transforms(SkeletonHandle handle); //void optimiseAllAnimations(bool preservingIdentityNodeTracks = false); void skeleton_optimise_all_animations(SkeletonHandle handle, int preserving_identity_node_tracks); //void addLinkedSkeletonAnimationSource(const String& skelName, Real scale = 1.0f); void skeleton_add_linked_skeleton_animation_source(SkeletonHandle handle, const char* skel_name, coiReal scale); //void removeAllLinkedSkeletonAnimationSources(void); void skeleton_remove_all_linked_skeleton_animation_sources(SkeletonHandle handle); //typedef vector<LinkedSkeletonAnimationSource>::type LinkedSkeletonAnimSourceList; //typedef ConstVectorIterator<LinkedSkeletonAnimSourceList> LinkedSkeletonAnimSourceIterator; //TODO: LinkedSkeletonAnimSourceIterator getLinkedSkeletonAnimationSourceIterator(void) const; //void _notifyManualBonesDirty(void); void skeleton__notify_manual_bones_dirty(SkeletonHandle handle); //void _notifyManualBoneStateChange(Bone* bone); void skeleton__notify_manual_bone_state_change(SkeletonHandle handle, BoneHandle bone); //bool getManualBonesDirty(void) const; int skeleton_get_manual_bones_dirty(const SkeletonHandle handle); //bool hasManualBones(void) const; int skeleton_has_manual_bones(const SkeletonHandle handle); //typedef vector<ushort>::type BoneHandleMap; //TODO: void _mergeSkeletonAnimations(const Skeleton* source, const BoneHandleMap& boneHandleMap, const StringVector& animations = StringVector()); //TODO: void _buildMapBoneByHandle(const Skeleton* source, BoneHandleMap& boneHandleMap) const; //TODO: void _buildMapBoneByName(const Skeleton* source,BoneHandleMap& boneHandleMap) const; // Ogre::SkeletonInstance //~SkeletonInstance(); void destroy_skeletoninstance(SkeletonInstanceHandle handle); //unsigned short getNumAnimations(void) const; ushort skeletoninstance_get_num_animations(const SkeletonInstanceHandle handle); //TODO: Animation* getAnimation(unsigned short index) const; //TODO: Animation* _getAnimationImpl(const String& name, const LinkedSkeletonAnimationSource** linker = 0) const; //TODO: Animation* createAnimation(const String& name, Real length); //TODO: Animation* getAnimation(const String& name, const LinkedSkeletonAnimationSource** linker = 0) const; //void removeAnimation(const String& name); void skeletoninstance_remove_animation(SkeletonInstanceHandle handle, const char* name); //TagPoint* createTagPointOnBone(Bone* bone, const Quaternion &offsetOrientation = Quaternion::IDENTITY,const Vector3 &offsetPosition = Vector3::ZERO); TagPointHandle skeletoninstance_create_tag_point_on_bone(SkeletonInstanceHandle handle, BoneHandle bone_handle, ref const(coiQuaternion) offset_orientation, ref const(coiVector3) offset_position); //void freeTagPoint(TagPoint* tagPoint); void skeletoninstance_free_tag_point(SkeletonInstanceHandle handle, TagPointHandle tag_point); //void addLinkedSkeletonAnimationSource(const String& skelName, Real scale = 1.0f); void skeletoninstance_add_linked_skeleton_animation_source(SkeletonInstanceHandle handle, const char* skel_name, coiReal scale); //void removeAllLinkedSkeletonAnimationSources(void); void skeletoninstance_remove_all_linked_skeleton_animation_sources(SkeletonInstanceHandle handle); //TODO: LinkedSkeletonAnimSourceIterator getLinkedSkeletonAnimationSourceIterator(void) const; //TODO: void _initAnimationState(AnimationStateSet* animSet); //TODO: void _refreshAnimationState(AnimationStateSet* animSet); //const String& getName(void) const; const(char*) skeletoninstance_get_name(const SkeletonInstanceHandle handle); //TODO: ResourceHandle getHandle(void) const; //const String& getGroup(void); const(char*) skeletoninstance_get_group(SkeletonInstanceHandle handle); // Ogre::SceneNode SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); ushort scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_get_position(SceneNodeHandle handle, ref coiVector3 pos); void scenenode_set_derived_position(SceneNodeHandle handle, const ref coiVector3 pos); void scenenode_get_derived_position(SceneNodeHandle handle, ref coiVector3 pos); //void setFixedYawAxis( bool useFixed, const Vector3& fixedAxis = Vector3::UNIT_Y ); void scenenode_set_fixed_yaw_axis(SceneNodeHandle handle, int use_fixed, const ref coiVector3 fixed_axis); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle, transform_space relative_to); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref coiColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); //Ogre::Viewport::setDimensions(float, float, float, float) void viewport_set_dimensions(ViewportHandle handle, coiReal left, coiReal top, coiReal width, coiReal height); //Ogre::Viewport::getActualDimensions(int&, int&, int&, int&) const void viewport_get_actual_dimensions(ViewportHandle handle, ref int left, ref int top, ref int width, ref int height); //Ogre::Viewport::getBackgroundColour() const void viewport_get_background_colour(ViewportHandle handle, ref coiColourValue cv); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, ref coiVector3 v3); void camera_get_up(CameraHandle handle, ref coiVector3 up); void camera_get_right(CameraHandle handle, ref coiVector3 right); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); void camera_roll(CameraHandle handle, coiReal angle); void camera_yaw(CameraHandle handle, coiReal angle); void camera_pitch(CameraHandle handle, coiReal angle); void camera_rotate(CameraHandle handle, const ref coiVector3 axis, coiReal angle); void camera_rotate_q(CameraHandle handle, const ref coiQuaternion q); //Ogre::Camera::setFixedYawAxis(bool, Ogre::Vector3 const&) void camera_set_fixed_yaw_axis(CameraHandle handle, int on, const ref coiVector3 fixed_axis); //Ogre::Camera::getOrientation() const void camera_get_orientation(CameraHandle handle, ref coiQuaternion orientation); //Ogre::Camera::setOrientation(Ogre::Quaternion const&) void camera_set_orientation(CameraHandle handle, const ref coiQuaternion orientation); //Ogre::Camera::getDerivedOrientation() const void camera_get_derived_orientation(CameraHandle handle, ref coiQuaternion orientation); //Ogre::Camera::getDerivedPosition() const void camera_get_derived_position(CameraHandle handle, ref coiVector3 position); //Ogre::Camera::getDerivedDirection() const void camera_get_derived_direction(CameraHandle handle, ref coiVector3 direction); //Ogre::Camera::getDerivedUp() const void camera_get_derived_up(CameraHandle handle, ref coiVector3 up); //Ogre::Camera::getDerivedRight() const void camera_get_derived_right(CameraHandle handle, ref coiVector3 right); //Ogre::Camera::setAutoTracking(bool, Ogre::SceneNode*, Ogre::Vector3 const&) void camera_set_autotracking(CameraHandle handle, int on, SceneNodeHandle sn_handle, const ref coiVector3 offset); //Ogre::Camera::setLodBias(float) void camera_set_lod_bias(CameraHandle handle, coiReal factor); //Ogre::Camera::getLodBias() const coiReal camera_get_lod_bias(CameraHandle handle); //Ogre::Camera::getCameraToViewportRay(float, float, Ogre::Ray*) const void camera_get_camera_to_viewport_ray(CameraHandle handle, coiReal screenx, coiReal screeny, RayHandle ray); //Ogre::Camera::setWindow(float, float, float, float) void camera_set_window(CameraHandle handle, coiReal left, coiReal top, coiReal right, coiReal bottom); SceneManagerHandle camera_get_scenemanager(CameraHandle handle); // Ogre::MovableObject /* As this is an abstract object, no need for construction. */ ///~MovableObject(); void destroy_movableobject(MovableObjectHandle handle); ///TODO: void _notifyCreator(MovableObjectFactory* fact); ///TODO: MovableObjectFactory* _getCreator(void) const; ///void _notifyManager(SceneManager* man); void movableobject__notify_manager(MovableObjectHandle handle, SceneManagerHandle man); ///SceneManager* _getManager(void) const; SceneManagerHandle movableobject__get_manager(const MovableObjectHandle handle); ///const String& getName(void) const; const(char*) movableobject_get_name(const MovableObjectHandle handle); ///const String& getMovableType(void) const = 0; const(char*) movableobject_get_movable_type(const MovableObjectHandle handle); ///Node* getParentNode(void) const; NodeHandle movableobject_get_parent_node(const MovableObjectHandle handle); ///SceneNode* getParentSceneNode(void) const; SceneNodeHandle movableobject_get_parent_scene_node(const MovableObjectHandle handle); ///bool isParentTagPoint() const; int movableobject_is_parent_tag_point(const MovableObjectHandle handle); ///void _notifyAttached(Node* parent, bool isTagPoint = false); void movableobject__notify_attached(MovableObjectHandle handle, NodeHandle parent, int is_tag_point); ///bool isAttached(void) const; int movableobject_is_attached(const MovableObjectHandle handle); ///void detachFromParent(void); void movableobject_detach_from_parent(MovableObjectHandle handle); ///bool isInScene(void) const; int movableobject_is_in_scene(const MovableObjectHandle handle); ///void _notifyMoved(void); void movableobject__notify_moved(MovableObjectHandle handle); ///void _notifyCurrentCamera(Camera* cam); void movableobject__notify_current_camera(MovableObjectHandle handle, CameraHandle cam); ///const AxisAlignedBox& getBoundingBox(void) const = 0; const(AxisAlignedBoxHandle) movableobject_get_bounding_box(const MovableObjectHandle handle); ///Real getBoundingRadius(void) const = 0; coiReal movableobject_get_bounding_radius(const MovableObjectHandle handle); ///const AxisAlignedBox& getWorldBoundingBox(bool derive = false) const; const(AxisAlignedBoxHandle) movableobject_get_world_bounding_box(const MovableObjectHandle handle, int derive); ///const Sphere& getWorldBoundingSphere(bool derive = false) const; const(SphereHandle) movableobject_get_world_bounding_sphere(const MovableObjectHandle handle, int derive); ///void _updateRenderQueue(RenderQueue* queue) = 0; //TODO:DLL void movableobject__update_render_queue(MovableObjectHandle handle, RenderQueueHandle queue); ///void setVisible(bool visible); void movableobject_set_visible(MovableObjectHandle handle, int visible); ///bool getVisible(void) const; int movableobject_get_visible(const MovableObjectHandle handle); ///bool isVisible(void) const; int movableobject_is_visible(const MovableObjectHandle handle); ///void setRenderingDistance(Real dist); void movableobject_set_rendering_distance(MovableObjectHandle handle, coiReal dist); ///Real getRenderingDistance(void) const; coiReal movableobject_get_rendering_distance(const MovableObjectHandle handle); ///void setRenderingMinPixelSize(Real pixelSize); void movableobject_set_rendering_min_pixel_size(MovableObjectHandle handle, coiReal pixel_size); ///Real getRenderingMinPixelSize() const; coiReal movableobject_get_rendering_min_pixel_size(const MovableObjectHandle handle); //void setUserAny(const Any& anything); XXX: deprecated //const Any& getUserAny(void) const; XXX: deprecated ///UserObjectBindings& getUserObjectBindings(); ///const UserObjectBindings& getUserObjectBindings() const; ///void setRenderQueueGroup(uint8 queueID); void movableobject_set_render_queue_group(MovableObjectHandle handle, ubyte queue_id); ///void setRenderQueueGroupAndPriority(uint8 queueID, ushort priority); void movableobject_set_render_queue_group_and_priority(MovableObjectHandle handle, ubyte queue_id, ushort priority); ///uint8 getRenderQueueGroup(void) const; ubyte movableobject_get_render_queue_group(const MovableObjectHandle handle); ///const Matrix4& _getParentNodeFullTransform(void) const; void movableobject__get_parent_node_full_transform(const MovableObjectHandle handle, ref coiMatrix4 result); ///void setQueryFlags(uint32 flags); void movableobject_set_query_flags(MovableObjectHandle handle, uint flags); ///void addQueryFlags(uint32 flags); void movableobject_add_query_flags(MovableObjectHandle handle, uint flags); ///void removeQueryFlags(uint32 flags); void movableobject_remove_query_flags(MovableObjectHandle handle, uint flags); ///uint32 getQueryFlags(void) const; uint movableobject_get_query_flags(const MovableObjectHandle handle); ///static void setDefaultQueryFlags(uint32 flags); void movableobject_set_default_query_flags(uint flags); ///static uint32 getDefaultQueryFlags(); uint movableobject_get_default_query_flags(); ///void setVisibilityFlags(uint32 flags) void movableobject_set_visibility_flags(MovableObjectHandle handle, uint flags); ///void addVisibilityFlags(uint32 flags); void movableobject_add_visibility_flags(MovableObjectHandle handle, uint flags); ///void removeVisibilityFlags(uint32 flags); void movableobject_remove_visibility_flags(MovableObjectHandle handle, uint flags); ///uint32 getVisibilityFlags(void) const; uint movableobject_get_visibility_flags(const MovableObjectHandle handle); ///static void setDefaultVisibilityFlags(uint32 flags); void movableobject_set_default_visibility_flags(uint flags); ///static uint32 getDefaultVisibilityFlags(); uint movableobject_get_default_visibility_flags(); ///void setListener(Listener* listener); //movableobject_set_listener(MovableObjectHandle handle, ///Listener* getListener(void) const; //movableobject_get_listener(MovableObjectHandle handle, ///const LightList& queryLights(void) const; size_t movableobject_query_lights(const MovableObjectHandle handle, LightHandle result); ///uint32 getLightMask() const; uint movableobject_get_light_mask(const MovableObjectHandle handle); ///void setLightMask(uint32 lightMask); void movableobject_set_light_mask(MovableObjectHandle handle, uint light_mask); ///LightList* _getLightList(); ///EdgeData* getEdgeList(void); ///bool hasEdgeList(void); int movableobject_has_edge_list(MovableObjectHandle handle); ///ShadowRenderableListIterator getShadowVolumeRenderableIterator(ShadowTechnique shadowTechnique, const Light* light, HardwareIndexBufferSharedPtr* indexBuffer, bool extrudeVertices, Real extrusionDist, unsigned long flags = 0); ///const AxisAlignedBox& getLightCapBounds(void) const; const(AxisAlignedBoxHandle) movableobject_get_light_cap_bounds(const MovableObjectHandle handle); ///const AxisAlignedBox& getDarkCapBounds(const Light& light, Real dirLightExtrusionDist) const; const(AxisAlignedBoxHandle) movableobject_get_dark_cap_bounds(const MovableObjectHandle handle, const LightHandle light, coiReal dir_light_extrusion_dist); ///void setCastShadows(bool enabled); void movableobject_set_cast_shadows(MovableObjectHandle handle, int enabled); ///bool getCastShadows(void) const; int movableobject_get_cast_shadows(const MovableObjectHandle handle); ///bool getReceivesShadows(); int movableobject_get_receives_shadows(MovableObjectHandle handle); ///Real getPointExtrusionDistance(const Light* l) const; coiReal movableobject_get_point_extrusion_distance(const MovableObjectHandle handle, const LightHandle l); ///uint32 getTypeFlags(void) const; uint movableobject_get_type_flags(const MovableObjectHandle handle); ///void visitRenderables(Renderable::Visitor* visitor,bool debugRenderables = false) = 0; ///void setDebugDisplayEnabled(bool enabled); void movableobject_set_debug_display_enabled(MovableObjectHandle handle, int enabled); ///bool isDebugDisplayEnabled(void) const; int movableobject_is_debug_display_enabled(const MovableObjectHandle handle); // Ogre::Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); ///Ogre::Entity::getNumSubEntities() const uint entity_get_num_sub_entities(const EntityHandle handle); //Ogre::Entity::clone(std::string const&) const EntityHandle entity_clone(const EntityHandle handle, const char* name); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(const EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); ///Ogre::Entity::setMaterialName(std::string const&, std::string const&) ///Ogre::Entity::setMaterial(Ogre::MaterialPtr const&) void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); ///Ogre::Entity::_notifyCurrentCamera(Ogre::Camera*) void entity__notify_current_camera(EntityHandle handle, CameraHandle cam); ///Ogre::Entity::setRenderQueueGroup(unsigned char) void entity_set_render_queue_group(EntityHandle handle, ubyte queue_id); ///Ogre::Entity::setRenderQueueGroupAndPriority(unsigned char, unsigned short) void entity_set_render_queue_group_and_priority(EntityHandle handle, ubyte queue_id, ushort priority); //Ogre::Entity::getBoundingBox() const const(AxisAlignedBoxHandle) entity_get_bounding_box(const EntityHandle handle); //Ogre::Entity::getBoundingRadius() const coiReal entity_get_bounding_radius(const EntityHandle handle); //Ogre::Entity::setDisplaySkeleton(bool) void entity_set_display_skeleton(EntityHandle handle, int display); //Ogre::Entity::getDisplaySkeleton() const int entity_get_display_skeleton(const EntityHandle handle); // Light LightHandle create_light(const char* light_name); void destroy_light(LightHandle handle); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); //Ogre::Light::getPosition() const void light_get_position(LightHandle handle, ref coiVector3 pos); //Ogre::Light::getPosition() const void light_get_position_xyz(LightHandle handle, ref float x, ref float y, ref float z); //Ogre::Light::getPosition() const void light_get_position_xyz(LightHandle handle, float* x, float* y, float* z); //Ogre::Light::setDirection(float, float, float) void light_set_direction_xyz(LightHandle handle, const float x, const float y, const float z); //Ogre::Light::setDirection(Ogre::Vector3 const&) void light_set_direction(LightHandle handle, const ref coiVector3 direction); //Ogre::Light::getDirection() const void light_get_direction(LightHandle handle, ref coiVector3 direction); //Ogre::Light::setSpotlightRange(Ogre::Radian const&, Ogre::Radian const&, float) void light_set_spotlight_range(LightHandle handle, const coiReal inner_angle, const coiReal outer_angle, coiReal fall_off); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref coiColourValue colour); void light_set_specular_colour(LightHandle handle, const ref coiColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameStarted started_cb, FrameQueued queued_cb, FrameEnded ended_cb, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); WindowListenerHandle add_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerEvent window_event, void* userdata); void remove_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerHandle listener_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(logging_level lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); //Log::logMessage void log_log_message(LogHandle handle, const char* message, log_message_level lml, int maskDebug); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); void render_window_get_custom_attribute(RenderWindowHandle handle, const char* attribute, void* pdata); uint render_window_get_width(RenderWindowHandle handle); uint render_window_get_height(RenderWindowHandle handle); void renderwindow_get_statistics(RenderWindowHandle handle, ref FrameStats stats); void renderwindow_get_statistics_ex(RenderWindowHandle handle, ref float lastFPS, ref float avgFPS, ref float bestFPS, ref float worstFPS); // ColourValue void colourvalue_zero(ref coiColourValue c); void colourvalue_black(ref coiColourValue c); void colourvalue_white(ref coiColourValue c); void colourvalue_red(ref coiColourValue c); void colourvalue_green(ref coiColourValue c); void colourvalue_blue(ref coiColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); void plane_get_normal(PlaneHandle handle, ref coiVector3 normal); void plane_set_normal(PlaneHandle handle, const ref coiVector3 normal); coiReal plane_get_d(PlaneHandle handle); void plane_set_d(PlaneHandle handle, coiReal d); // PlaneList (typedef vector<Plane>::type PlaneList) PlaneListHandle create_planelist(); void destroy_planelist(PlaneListHandle handle); // PlaneBoundedVolume PlaneBoundedVolumeHandle create_planeboundedvolume(plane_side the_outside); void destroy_planeboundedvolume(PlaneBoundedVolumeHandle handle); // bool intersects(const AxisAlignedBox&) const int planeboundedvolume_intersects_axisalignedbox(PlaneBoundedVolumeHandle handle, AxisAlignedBoxHandle query); // bool intersects(const Sphere&) const int planeboundedvolume_intersects_sphere(PlaneBoundedVolumeHandle handle, SphereHandle query); // std::pair<bool, Real> intersects(const Ray&) const void planeboundedvolume_intersects_ray(PlaneBoundedVolumeHandle handle, RayHandle query, ref ray_pair result); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); // Ogre::Timer int timer_set_option(TimerHandle handle, const char* key, void* value); c_ulong timer_get_milliseconds(TimerHandle handle); c_ulong timer_get_microseconds(TimerHandle handle); c_ulong timer_get_milliseconds_cpu(TimerHandle handle); c_ulong timer_get_microseconds_cpu(TimerHandle handle); void timer_reset(TimerHandle handle); // Ogre::AxisAlignedBox AxisAlignedBoxHandle create_axis_aligned_box(); AxisAlignedBoxHandle create_axis_aligned_box_ex(Extent e); AxisAlignedBoxHandle create_axis_aligned_box_v3(const ref coiVector3 min, const ref coiVector3 max); void destroy_axis_aligned_box(AxisAlignedBoxHandle handle); void axisalignedbox_get_size(AxisAlignedBoxHandle handle, ref coiVector3 size); void axisalignedbox_get_minimum(AxisAlignedBoxHandle handle, ref coiVector3 minimum); void axisalignedbox_get_maximum(AxisAlignedBoxHandle handle, ref coiVector3 maximum); void axisalignedbox_set_minimum_x(AxisAlignedBoxHandle handle, coiReal x); void axisalignedbox_set_minimum_y(AxisAlignedBoxHandle handle, coiReal y); void axisalignedbox_set_minimum_z(AxisAlignedBoxHandle handle, coiReal z); void axisalignedbox_set_minimum(AxisAlignedBoxHandle handle, const ref coiVector3 min); void axisalignedbox_set_maximum(AxisAlignedBoxHandle handle, const ref coiVector3 max); void axisalignedbox_set_maximum_x(AxisAlignedBoxHandle handle, coiReal x); void axisalignedbox_set_maximum_y(AxisAlignedBoxHandle handle, coiReal y); void axisalignedbox_set_maximum_z(AxisAlignedBoxHandle handle, coiReal z); void axisalignedbox_set_extents(AxisAlignedBoxHandle handle, const ref coiVector3 min, const ref coiVector3 max); void axisalignedbox_get_corner(AxisAlignedBoxHandle handle, CornerEnum e, ref coiVector3 corner); //Ogre::Ray RayHandle create_ray(const ref coiVector3 origin, const ref coiVector3 direction); void destroy_ray(RayHandle handle); //Ray::setOrigin void ray_set_origin(RayHandle handle, const ref coiVector3 origin); //Ray::getOrigin void ray_get_origin(RayHandle handle, ref coiVector3 origin); //Ray::setDirection void ray_set_direction(RayHandle handle, const ref coiVector3 direction); //Ray::getDirection void ray_get_direction(RayHandle handle, ref coiVector3 direction); //Ray::getPoint void ray_get_point(RayHandle handle, coiReal units, ref coiVector3 point); //Ray::intersects(Plane) void ray_intersects_plane(RayHandle handle, PlaneHandle plane_handle, ref ray_pair result); //Ray::intersects(AxisAlignedBox) void ray_intersects_axisalignedbox(RayHandle handle, AxisAlignedBoxHandle query_handle, ref ray_pair result); //Ray::intersects(Sphere) void ray_intersects_sphere(RayHandle handle, SphereHandle query_handle, ref ray_pair result); // Ogre::Sphere SphereHandle create_sphere(const ref coiVector3 center, coiReal radius); void destroy_sphere(SphereHandle handle); //void setRadius(Real) void sphere_set_radius(SphereHandle handle, coiReal radius); //Real getRadius(void) const coiReal sphere_get_radius(SphereHandle handle); //void setCenter(Vector3) void sphere_set_center(SphereHandle handle, const ref coiVector3 center); //Real getCenter(void) const void sphere_get_center(SphereHandle handle, ref coiVector3 center); // bool intersects(const Sphere&) const int sphere_intersects_sphere(SphereHandle handle, SphereHandle query); // bool intersects(const AxisAlignedBox&) const int sphere_intersects_axisalignedbox(SphereHandle handle, AxisAlignedBoxHandle query); // bool intersects(const Plane&) const int sphere_intersects_plane(SphereHandle handle, PlaneHandle query); // bool intersects(const Vector3&) const int sphere_intersects_vector3(SphereHandle handle, const ref coiVector3 query); // void merge(const Sphere&) void sphere_merge(SphereHandle handle, SphereHandle other_sphere); // Ogre::SceneQuery // SceneQuery::setQueryMask(uint32 mask) void scenequery_set_query_mask(SceneQueryHandle handle, uint32 mask); //uint32 SceneQuery::getQueryMask(void) const uint32 scenequery_get_query_mask(SceneQueryHandle handle); //void SceneQuery::setWorldFragmentType(enum WorldFragmentType wft); void scenequery_set_world_fragment_type(SceneQueryHandle handle, world_fragment_type wft); //WorldFragmentType SceneQuery::getWorldFragmentType(void) const; world_fragment_type scenequery_get_world_fragment_type(SceneQueryHandle handle); // SceneQueryListener SceneQueryListenerHandle create_scenequerylistener(SceneQueryFragmentResult fragment_callback, SceneQueryObjectResult object_callback, void* userdata); void destroy_scenequerylistener(SceneQueryListenerHandle handle); size_t scenequeryresult_movables_count(SceneQueryResultHandle handle); MovableObjectHandle scenequeryresult_movables_at(SceneQueryResultHandle handle, int index); size_t scenequeryresult_worldfragments_count(SceneQueryResultHandle handle, int index); void scenequeryresult_worldfragments_at(SceneQueryResultHandle handle, int index, ref world_fragment result); RaySceneQueryListenerHandle create_rayscenequerylistener(RaySceneQueryFragmentResult fragment_callback, RaySceneQueryObjectResult object_callback, void* userdata); void destroy_rayscenequerylistener(RaySceneQueryListenerHandle handle); //setRay void rayscenequery_set_ray(RaySceneQueryHandle handle, RayHandle ray_handle); //getRay RayHandle rayscenequery_get_ray(RaySceneQueryHandle handle); //void setSortByDistance(bool sort, ushort maxresults = 0); void rayscenequery_set_sort_by_distance(RaySceneQueryHandle handle, int on, ushort maxresults); //bool getSortByDistance(void) const; int rayscenequery_get_sort_by_distance(RaySceneQueryHandle handle); //ushort getMaxResults(void) const; ushort rayscenequery_get_max_results(RaySceneQueryHandle handle); // typedef vector<RaySceneQueryResultEntry>::type RaySceneQueryResult; size_t rayscenequeryresult_count(RaySceneQueryResultHandle handle); void rayscenequeryresult_at(RaySceneQueryResultHandle handle, int index, ref rayscenequery_result_entry result); // Ogre::Overlay //const String& getName(void) const; const(char*) overlay_get_name(OverlayHandle handle); //void setZOrder(ushort zorder); void overlay_set_zorder(OverlayHandle handle, ushort zorder); //ushort getZOrder(void) const; ushort overlay_get_zorder(OverlayHandle handle); //bool isVisible(void) const; int overlay_is_visible(OverlayHandle handle); //bool isInitialised(void) const; int overlay_is_initialised(OverlayHandle handle); //void show(void); void overlay_show(OverlayHandle handle); //void hide(void); void overlay_hide(OverlayHandle handle); //void add2D(OverlayContainer* cont); void overlay_add_2d(OverlayHandle handle, OverlayContainerHandle cont); //void remove2D(OverlayContainer* cont); void overlay_remove_2d(OverlayHandle handle, OverlayContainerHandle cont); //void add3D(SceneNode* node); void overlay_add_3d(OverlayHandle handle, SceneNodeHandle node_handle); //void remove3D(SceneNode* node); void overlay_remove_3d(OverlayHandle handle, SceneNodeHandle node_handle); // void clear(); void overlay_clear(OverlayHandle handle); //void setScroll(Real x, Real y); void overlay_set_scroll(OverlayHandle handle, coiReal x, coiReal y); //Real getScrollX(void) const; coiReal overlay_get_scroll_x(OverlayHandle handle); //Real getScrollY(void) const; coiReal overlay_get_scroll_y(OverlayHandle handle); //void scroll(Real xoff, Real yoff); void overlay_scroll(OverlayHandle handle, coiReal x, coiReal y); //void setRotate(const Radian& angle); void overlay_set_rotate(OverlayHandle handle, coiReal angle); //const Radian &getRotate(void) const; coiReal overlay_get_rotate(OverlayHandle handle); //void rotate(const Radian& angle); void overlay_rotate(OverlayHandle handle, coiReal angle); //void setScale(Real x, Real y); void overlay_set_scale(OverlayHandle handle, coiReal x, coiReal y); //Real getScaleX(void) const; coiReal overlay_get_scale_x(OverlayHandle handle); //Real getScaleY(void) const; coiReal overlay_get_scale_y(OverlayHandle handle); //void _getWorldTransforms(Matrix4* xform) const; void overlay_get_world_transforms(OverlayHandle handle, ref coiMatrix4 xform); //const String& getOrigin(void) const; const(char*) overlay_get_origin(OverlayHandle handle); //void _notifyOrigin(const String& origin); void overlay_notify_origin(OverlayHandle handle, const(char*) origin); //Ogre::OverlayManager //OverlayManager(); OverlayManagerHandle create_overlaymanager(); //~OverlayManager(); void destroy_overlaymanager(OverlayManagerHandle handle); //Real getLoadingOrder(void) const; coiReal overlaymanager_get_loading_order(OverlayManagerHandle handle); //Overlay* create(const String& name); OverlayHandle overlaymanager_create(OverlayManagerHandle handle, const char* name); //Overlay* getByName(const String& name); OverlayHandle overlaymanager_get_by_name(OverlayManagerHandle handle, const char* name); //void destroy(const String& name); void overlaymanager_destroy_by_name(OverlayManagerHandle handle, const char* name); //void destroy(Overlay* overlay); void overlaymanager_destroy(OverlayManagerHandle handle, OverlayHandle overlay_handle); //void destroyAll(void); void overlaymanager_destroy_all(OverlayManagerHandle handle); // XXX: for debugging. //void overlaymanager_list_overlays(OverlayManagerHandle handle); //bool hasViewportChanged(void) const; int overlaymanager_has_viewport_changed(OverlayManagerHandle handle); //int getViewportHeight(void) const; int overlaymanager_get_viewport_height(OverlayManagerHandle handle); //int getViewportWidth(void) const; int overlaymanager_get_viewport_width(OverlayManagerHandle handle); //Real getViewportAspectRatio(void) const; coiReal overlaymanager_get_viewport_aspect_ratio(OverlayManagerHandle handle); //OrientationMode getViewportOrientationMode(void) const; orientation_mode overlaymanager_get_viewport_orientation_mode(OverlayManagerHandle handle); //OverlayElement* createOverlayElement(const String& typeName, const String& instanceName, bool isTemplate = false); OverlayElementHandle overlaymanager_create_overlayelement(OverlayManagerHandle handle, const char* type_name, const char* instance_name, int is_template); //OverlayElement* getOverlayElement(const String& name, bool isTemplate = false); OverlayElementHandle overlaymanager_get_overlayelement(OverlayManagerHandle handle, const char* name, int is_template); //bool hasOverlayElement(const String& name, bool isTemplate = false); int overlaymanager_has_overlay_element(OverlayManagerHandle handle, const char* name, int is_template); //void destroyOverlayElement(const String& instanceName, bool isTemplate = false); void overlaymanager_destroy_overlay_element(OverlayManagerHandle handle, const char* name, int is_template); //void destroyOverlayElement(OverlayElement* pInstance, bool isTemplate = false); void overlaymanager_destroy_overlay_element_instance(OverlayManagerHandle handle, OverlayElementHandle instance, int is_template); //void destroyAllOverlayElements(bool isTemplate = false); void overlaymanager_destroy_all_overlay_elements(OverlayManagerHandle handle); //OverlayElement* createOverlayElementFromTemplate(const String& templateName, const String& typeName, const String& instanceName, bool isTemplate = false); OverlayElementHandle overlaymanager_create_overlayelement_from_template(OverlayManagerHandle handle, const char* template_name, const char* type_name, const char* instance_name, int is_template); //OverlayElement* cloneOverlayElementFromTemplate(const String& templateName, const String& instanceName); OverlayElementHandle overlaymanager_clone_overlayelement_from_template(OverlayManagerHandle handle, const char* template_name, const char* instance_name); //OverlayElement* createOverlayElementFromFactory(const String& typeName, const String& instanceName); OverlayElementHandle overlaymanager_create_overlayelement_from_factory(OverlayManagerHandle handle, const char* type_name, const char* instance_name); //bool isTemplate (String strName) const int overlaymanager_is_template(OverlayManagerHandle handle, const char* name); //static OverlayManager* getSingletonPtr(void); OverlayManagerHandle overlaymanager_get_singleton_ptr(); // Ogre::OverlayElement //~OverlayElement void destroy_overlayelement(OverlayElementHandle handle); //void initialise(void) void overlayelement_initialise(OverlayElementHandle handle); //const String& getName(void) const; const(char*) overlayelement_get_name(OverlayElementHandle handle); //void show(void); void overlayelement_show(OverlayElementHandle handle); //void hide(void); void overlayelement_hide(OverlayElementHandle handle); //bool isVisible(void) const; int overlayelement_is_visible(OverlayElementHandle handle); //bool isEnabled() const; int overlayelement_is_enabled(OverlayElementHandle handle); //void setEnabled(bool b); void overlayelement_set_enabled(OverlayElementHandle handle, int b); //void setDimensions(Real width, Real height); void overlayelement_set_dimensions(OverlayElementHandle handle, coiReal width, coiReal height); //void setPosition(Real left, Real top); void overlayelement_set_position(OverlayElementHandle handle, coiReal left, coiReal top); //void setWidth(Real width); void overlayelement_set_width(OverlayElementHandle handle, coiReal width); //Real getWidth(void) const; coiReal overlayelement_get_width(OverlayElementHandle handle); //void setHeight(Real height); void overlayelement_set_height(OverlayElementHandle handle, coiReal height); //Real getHeight(void) const; coiReal overlayelement_get_height(OverlayElementHandle handle); //void setLeft(Real left); void overlayelement_set_left(OverlayElementHandle handle, coiReal left); //Real getLeft(void) const; coiReal overlayelement_get_left(OverlayElementHandle handle); //void setTop(Real Top); void overlayelement_set_top(OverlayElementHandle handle, coiReal top); //Real getTop(void) const; coiReal overlayelement_get_top(OverlayElementHandle handle); //Real _getLeft(void) const; coiReal overlayelement__get_left(OverlayElementHandle handle); //Real _getTop(void) const; coiReal overlayelement__get_top(OverlayElementHandle handle); //Real _getWidth(void) const; coiReal overlayelement__get_width(OverlayElementHandle handle); //Real _getHeight(void) const; coiReal overlayelement__get_height(OverlayElementHandle handle); //void _setLeft(Real left); void overlayelement__set_left(OverlayElementHandle handle, coiReal left); //void _setTop(Real top); void overlayelement__set_top(OverlayElementHandle handle, coiReal top); //void _setWidth(Real width); void overlayelement__set_width(OverlayElementHandle handle, coiReal width); //void _setHeight(Real height); void overlayelement__set_height(OverlayElementHandle handle, coiReal height); //void _setPosition(Real left, Real top); void overlayelement__set_position(OverlayElementHandle handle, coiReal left, coiReal top); //void _setDimensions(Real width, Real height); void overlayelement__set_dimensions(OverlayElementHandle handle, coiReal width, coiReal height); //const String& getMaterialName(void) const; const(char*) overlayelement_get_material_name(OverlayElementHandle handle); //void setMaterialName(const String& matName); void overlayelement_set_material_name(OverlayElementHandle handle, const char* name); //void getWorldTransforms(Matrix4* xform) const; void overlayelement_get_world_transforms(OverlayElementHandle handle, ref coiMatrix4 xform); //void _positionsOutOfDate(void); void overlayelement__positions_out_of_date(OverlayElementHandle handle); //void _update(void); void overlayelement__update(OverlayElementHandle handle); //void _updateFromParent(void); void overlayelement__update_from_parent(OverlayElementHandle handle); //void _notifyParent(OverlayContainer* parent, Overlay* overlay); void overlayelement__notify_parent(OverlayElementHandle handle, OverlayContainerHandle parent_handle, OverlayHandle overlay_handle); //Real _getDerivedLeft(void); coiReal overlayelement__get_derived_left(OverlayElementHandle handle); //Real _getDerivedTop(void); coiReal overlayelement__get_derived_top(OverlayElementHandle handle); //Real _getRelativeWidth(void); coiReal overlayelement__get_relative_width(OverlayElementHandle handle); //Real _getRelativeHeight(void); coiReal overlayelement__get_relative_height(OverlayElementHandle handle); //ushort _notifyZOrder(ushort newZOrder); ushort overlayelement__notify_zorder(OverlayElementHandle handle, ushort new_zorder); //void _notifyWorldTransforms(const Matrix4& xform); void overlayelement__notify_world_transforms(OverlayElementHandle handle, const ref coiMatrix4 xform); //void _notifyViewport(); void overlayelement__notify_viewport(OverlayElementHandle handle); //const String& getTypeName(void) const; const(char*) overlayelement_get_type_name(OverlayElementHandle handle); //void setCaption(const DisplayString& text); void overlayelement_set_caption(OverlayElementHandle handle, const char* text); //const DisplayString& getCaption(void) const; const(char*) overlayelement_get_caption(OverlayElementHandle handle); //void setColour(const ColourValue& col); void overlayelement_set_colour(OverlayElementHandle handle, const ref coiColourValue col); //const ColourValue& getColour(void) const; void overlayelement_get_colour(OverlayElementHandle handle, ref coiColourValue col); //void setMetricsMode(GuiMetricsMode gmm); void overlayelement_set_metrics_mode(OverlayElementHandle handle, gui_metrics_mode gmm); //GuiMetricsMode getMetricsMode(void) const; gui_metrics_mode overlayelement_get_metrics_mode(OverlayElementHandle handle); //void setHorizontalAlignment(GuiHorizontalAlignment gha); void overlayelement_set_horizontal_alignment(OverlayElementHandle handle, gui_horizontal_alignment gha); //GuiHorizontalAlignment getHorizontalAlignment(void) const; gui_horizontal_alignment overlayelement_get_horizontal_alignment(OverlayElementHandle handle); //void setVerticalAlignment(GuiVerticalAlignment gva); void overlayelement_set_vertical_alignment(OverlayElementHandle handle, gui_vertical_alignment gva); //GuiVerticalAlignment getVerticalAlignment(void) const; gui_vertical_alignment overlayelement_get_vertical_alignment(OverlayElementHandle handle); //bool contains(Real x, Real y) const; int overlayelement_contains(OverlayElementHandle handle, coiReal x, coiReal y); //OverlayElement* findElementAt(Real x, Real y); OverlayElementHandle overlayelement_find_element_at(OverlayElementHandle handle, coiReal x, coiReal y); //bool isContainer() const; int overlayelement_is_container(OverlayElementHandle handle); //bool isKeyEnabled() const; int overlayelement_is_key_enabled(OverlayElementHandle handle); //bool isCloneable() const int overlayelement_is_cloneable(OverlayElementHandle handle); //void setCloneable(bool c); void overlayelement_set_cloneable(OverlayElementHandle handle, int c); //OverlayContainer* getParent(); OverlayContainerHandle overlayelement_get_parent(OverlayElementHandle handle); //void _setParent(OverlayContainer* parent); void overlayelement_set_parent(OverlayElementHandle handle, OverlayContainerHandle parent_handle); //ushort getZOrder() const; ushort overlayelement_get_zorder(OverlayElementHandle handle); //Real getSquaredViewDepth(const Camera* cam) const; coiReal overlayelement_get_squared_view_depth(OverlayElementHandle handle, CameraHandle camera_handle); //void copyFromTemplate(OverlayElement* templateOverlay); void overlayelement_copy_from_template(OverlayElementHandle handle, OverlayElementHandle template_handle); //OverlayElement* clone(const String& instanceName); OverlayElementHandle overlayelement_clone(OverlayElementHandle handle, const char* instance_name); //const OverlayElement* getSourceTemplate () const; const(OverlayElementHandle) overlayelement_get_source_template(OverlayElementHandle handle); // Ogre::OverlayContainer void destroy_overlaycontainer(OverlayContainerHandle handle); //void addChild(OverlayElement* elem); void overlaycontainer_add_child(OverlayContainerHandle handle, OverlayElementHandle child_handle); //void addChildImpl(OverlayElement* elem); void overlaycontainer_add_child_impl(OverlayContainerHandle handle, OverlayElementHandle child_handle); //void addChildImpl(OverlayContainer* cont); void overlaycontainer_add_child_container_impl(OverlayContainerHandle handle, OverlayContainerHandle child_handle); //void removeChild(const String& name); void overlaycontainer_remove_child(OverlayContainerHandle handle, const char* name); //OverlayElement* getChild(const String& name); OverlayElementHandle overlaycontainer_get_child(OverlayContainerHandle handle, const char* name); //void initialise(void); void overlaycontainer_initialise(OverlayContainerHandle handle); //void _addChild(OverlayElement* elem); void overlaycontainer__add_child(OverlayContainerHandle handle, OverlayElementHandle elem); //void _removeChild(OverlayElement* elem); void overlaycontainer__remove_child(OverlayContainerHandle handle, OverlayElementHandle elem); //void _removeChild(const String& name); void overlaycontainer__remove_child_by_name(OverlayContainerHandle handle, const char* name); //void _positionsOutOfDate(void); void overlaycontainer__positions_out_of_date(OverlayContainerHandle handle); //void _update(void); void overlaycontainer__update(OverlayContainerHandle handle); //ushort _notifyZOrder(ushort newZOrder); ushort overlaycontainer__notify_zorder(OverlayContainerHandle handle, ushort new_zorder); //void _notifyViewport(); void overlaycontainer__notify_viewport(OverlayContainerHandle handle); //void _notifyWorldTransforms(const Matrix4& xform); void overlaycontainer__notify_world_transforms(OverlayContainerHandle handle, const ref coiMatrix4 xform); //void _notifyParent(OverlayContainer* parent, Overlay* overlay); void overlaycontainer__notify_parent(OverlayContainerHandle handle, OverlayContainerHandle parent_handle, OverlayHandle overlay_handle); //bool isContainer() const; int overlaycontainer_is_container(OverlayContainerHandle handle); //bool isChildrenProcessEvents() const; int overlaycontainer_is_children_process_events(OverlayContainerHandle handle); //void setChildrenProcessEvents(bool val); void overlaycontainer_set_children_process_events(OverlayContainerHandle handle, int val); //OverlayElement* findElementAt(Real x, Real y); OverlayElementHandle overlaycontainer_find_element_at(OverlayContainerHandle handle, coiReal x, coiReal y); //void copyFromTemplate(OverlayElement* templateOverlay); void overlaycontainer_copy_from_template(OverlayContainerHandle handle, OverlayElementHandle template_overlay); //virtual OverlayElement* clone(const String& instanceName); OverlayElementHandle overlaycontainer_clone(OverlayContainerHandle handle, const char* instance_name); // Ogre::PanelOverlayElement //PanelOverlayElement(const String& name); PanelOverlayElementHandle create_paneloverlayelement(const char* name); //~PanelOverlayElement(); void destroy_paneloverlayelement(PanelOverlayElementHandle handle); //void initialise(void); void paneloverlayelement_initialise(PanelOverlayElementHandle handle); //void setTiling(Real x, Real y, ushort layer = 0); void paneloverlayelement_set_tiling(PanelOverlayElementHandle handle, coiReal x, coiReal y, ushort layer); //Real getTileX(ushort layer = 0) const; coiReal paneloverlayelement_get_tile_x(const PanelOverlayElementHandle handle, ushort layer); //Real getTileY(ushort layer = 0) const; coiReal paneloverlayelement_get_tile_y(const PanelOverlayElementHandle handle, ushort layer); //void setUV(Real u1, Real v1, Real u2, Real v2); void paneloverlayelement_set_uv(PanelOverlayElementHandle handle, coiReal u1, coiReal v1, coiReal u2, coiReal v2); //void getUV(Real& u1, Real& v1, Real& u2, Real& v2) const; void paneloverlayelement_get_uv(const PanelOverlayElementHandle handle, ref coiReal u1, ref coiReal v1, ref coiReal u2, ref coiReal v2); //void setTransparent(bool isTransparent); void paneloverlayelement_set_transparent(PanelOverlayElementHandle handle, int is_transparent); //bool isTransparent(void) const; int paneloverlayelement_is_transparent(const PanelOverlayElementHandle handle); //const String& getTypeName(void) const; const(char*) paneloverlayelement_get_type_name(const PanelOverlayElementHandle handle); //void getRenderOperation(RenderOperation& op); void paneloverlayelement_get_renderoperation(PanelOverlayElementHandle handle, RenderOperationHandle renderOp); //void setMaterialName(const String& matName); void paneloverlayelement_set_material_name(PanelOverlayElementHandle handle, const char* mat_name); //TODO: void _updateRenderQueue(RenderQueue* queue); // Ogre::TextAreaOverlayElement //TextAreaOverlayElement(const String& name); TextAreaOverlayElementHandle create_textareaoverlayelement(const char* name); //~TextAreaOverlayElement(); void destroy_textareaoverlayelement(TextAreaOverlayElementHandle handle); //void initialise(void); void textareaoverlayelement_initialise(TextAreaOverlayElementHandle handle); //void setCaption(const DisplayString& text); void textareaoverlayelement_set_caption(TextAreaOverlayElementHandle handle, const char* text); //void setCharHeight( Real height ); void textareaoverlayelement_set_char_height(TextAreaOverlayElementHandle handle, coiReal height); //Real getCharHeight() const; coiReal textareaoverlayelement_get_char_height(const TextAreaOverlayElementHandle handle); //void setSpaceWidth( Real width ); void textareaoverlayelement_set_space_width(TextAreaOverlayElementHandle handle, coiReal width); //Real getSpaceWidth() const; coiReal textareaoverlayelement_get_space_width(const TextAreaOverlayElementHandle handle); //void setFontName( const String& font ); void textareaoverlayelement_set_font_name(TextAreaOverlayElementHandle handle, const char* font); //const String& getFontName() const; const(char*) textareaoverlayelement_get_font_name(const TextAreaOverlayElementHandle handle); //const String& getTypeName(void) const; const(char*) textareaoverlayelement_get_type_name(const TextAreaOverlayElementHandle handle); //TODO: const MaterialPtr& getMaterial(void) const; //TODO: void getRenderOperation(RenderOperation& op); //void setMaterialName(const String& matName); void textareaoverlayelement_set_material_name(TextAreaOverlayElementHandle handle, const char* mat_name); //void setColour(const ColourValue& col); void textareaoverlayelement_set_colour(TextAreaOverlayElementHandle handle, ref const(coiColourValue) col); //const ColourValue& getColour(void) const; void textareaoverlayelement_get_colour(const TextAreaOverlayElementHandle handle, ref coiColourValue result); //void setColourBottom(const ColourValue& col); void textareaoverlayelement_set_colour_bottom(TextAreaOverlayElementHandle handle, ref const(coiColourValue) col); //const ColourValue& getColourBottom(void) const; void textareaoverlayelement_get_colour_bottom(const TextAreaOverlayElementHandle handle, ref coiColourValue result); //void setColourTop(const ColourValue& col); void textareaoverlayelement_set_colour_top(TextAreaOverlayElementHandle handle, ref const(coiColourValue) col); //const ColourValue& getColourTop(void) const; void textareaoverlayelement_get_colour_top(const TextAreaOverlayElementHandle handle, ref coiColourValue result); //void setAlignment( Alignment a ); void textareaoverlayelement_set_alignment(TextAreaOverlayElementHandle handle, textarea_overlayelement_alignment a); //Alignment getAlignment() const textarea_overlayelement_alignment textareaoverlayelement_get_alignment(const TextAreaOverlayElementHandle handle); //void setMetricsMode(GuiMetricsMode gmm); void textareaoverlayelement_set_metrics_mode(TextAreaOverlayElementHandle handle, gui_metrics_mode gmm); //void _update(void); void textareaoverlayelement__update(TextAreaOverlayElementHandle handle); // Ogre::VertexData //TODO: VertexData(HardwareBufferManagerBase* mgr = 0); //TODO: VertexData(VertexDeclaration* dcl, VertexBufferBinding* bind); //~VertexData(); void destroy_vertexdata(VertexDataHandle handle); //(see OgreHardwareVertexBuffer.h): VertexDeclaration* vertexDeclaration; //(see OgreHardwareVertexBuffer.h) VertexBufferBinding* vertexBufferBinding; //size_t vertexStart; size_t vertexdata_vertex_start(VertexDataHandle handle); // getter //size_t vertexCount; size_t vertexdata_vertex_count(VertexDataHandle handle); // getter //typedef vector<HardwareAnimationData>::type HardwareAnimationDataList; //HardwareAnimationDataList hwAnimationDataList; //size_t hwAnimDataItemsUsed; size_t vertexdata_hw_anim_data_items_used(VertexDataHandle handle); //VertexData* clone(bool copyData = true, HardwareBufferManagerBase* mgr = 0) const; VertexDataHandle vertexdata_clone(const VertexDataHandle handle, int copy_data); //void prepareForShadowVolume(void); void vertexdata_prepare_for_shadow_volume(VertexDataHandle handle); //HardwareVertexBufferSharedPtr hardwareShadowVolWBuffer; //TODO: void reorganiseBuffers(VertexDeclaration* newDeclaration, const BufferUsageList& bufferUsage, HardwareBufferManagerBase* mgr = 0); //TODO: void reorganiseBuffers(VertexDeclaration* newDeclaration, HardwareBufferManagerBase* mgr = 0); //void closeGapsInBindings(void); void vertexdata_close_gaps_in_bindings(VertexDataHandle handle); //void removeUnusedBuffers(void); void vertexdata_remove_unused_buffers(VertexDataHandle handle); //TODO:void convertPackedColour(VertexElementType srcType, VertexElementType destType); //ushort allocateHardwareAnimationElements(ushort count, bool animateNormals); ushort vertexdata_allocate_hardware_animation_elements(VertexDataHandle handle, ushort count, int animate_normals); // Ogre::IndexData //IndexData(); IndexDataHandle create_indexdata(); //~IndexData(); void destroy_indexdata(IndexDataHandle handle); //HardwareIndexBufferSharedPtr indexBuffer; //size_t indexStart; size_t indexdata_index_start(IndexDataHandle handle); //size_t indexCount; size_t indexdata_index_count(IndexDataHandle handle); //IndexData* clone(bool copyData = true, HardwareBufferManagerBase* mgr = 0) const; IndexDataHandle indexdata_clone(const IndexDataHandle handle, int copy_data); //void optimiseVertexCacheTriList(void); void indexdata_optimise_vertex_cache_tri_list(IndexDataHandle handle); // Ogre::RenderOperation RenderOperationHandle create_renderoperation(); void destroy_renderoperation(RenderOperationHandle handle); //VertexData *vertexData; VertexDataHandle renderoperation_get_vertex_data(RenderOperationHandle handle); void renderoperation_set_vertex_data(RenderOperationHandle handle, VertexDataHandle vertex_data); //OperationType operationType; operation_type renderoperation_get_operation_type(RenderOperationHandle handle); void renderoperation_set_operation_type(RenderOperationHandle handle, operation_type op_type); //bool useIndexes; int renderoperation_get_use_indexes(RenderOperationHandle handle); void renderoperation_set_use_indexes(RenderOperationHandle, bool use_indexes); //IndexData *indexData; IndexDataHandle renderoperation_get_index_data(RenderOperationHandle handle); void renderoperation_set_index_data(RenderOperationHandle handle, IndexDataHandle index_data); //TODO: const Renderable* srcRenderable; //size_t numberOfInstances; size_t renderoperation_get_number_of_instances(RenderOperationHandle handle); void renderoperation_set_number_of_instances(RenderOperationHandle handle, size_t num); //bool useGlobalInstancingVertexBufferIsAvailable; int renderoperation_get_use_global_instancing_vertex_buffer_is_available(RenderOperationHandle handle); void renderoperation_set_use_global_instancing_vertex_buffer_is_available(RenderOperationHandle handle, int use); // Ogre::ManualObject //ManualObject(const String& name); ManualObjectHandle create_manualobject(const char* name); //~ManualObject(); void destroy_manualobject(ManualObjectHandle handle); //void clear(void); void manualobject_clear(ManualObjectHandle handle); //void estimateVertexCount(size_t vcount); void manualobject_estimate_vertex_count(ManualObjectHandle handle, size_t vcount); //void estimateIndexCount(size_t icount); void manualobject_estimate_index_count(ManualObjectHandle handle, size_t icount); //void begin(const String& materialName, RenderOperation::OperationType opType = RenderOperation::OT_TRIANGLE_LIST, const String & groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); void manualobject_begin(ManualObjectHandle handle, const char* material_name, operation_type op_type, const char* group_name); //void setDynamic(bool dyn) void manualobject_set_dynamic(ManualObjectHandle handle, int dyn); //bool getDynamic() const int manualobject_get_dynamic(const ManualObjectHandle handle); //void beginUpdate(size_t sectionIndex); void manualobject_begin_update(ManualObjectHandle handle, size_t section_index); //void position(const Vector3& pos); //void position(Real x, Real y, Real z); void manualobject_position(ManualObjectHandle handle, ref const(coiVector3) pos); //void normal(const Vector3& norm); //void normal(Real x, Real y, Real z); void manualobject_normal(ManualObjectHandle handle, ref const(coiVector3) norm); //void tangent(const Vector3& tan); //void tangent(Real x, Real y, Real z); void manualobject_tangent(ManualObjectHandle handle, ref const(coiVector3) tan); //void textureCoord(Real u); void manualobject_texture_coord_u(ManualObjectHandle handle, coiReal u); //void textureCoord(Real u, Real v); //void textureCoord(Real u, Real v, Real w); //void textureCoord(Real x, Real y, Real z, Real w); //void textureCoord(const Vector2& uv); void manualobject_texture_coord_uv(ManualObjectHandle handle, ref const(coiVector2) uv); //void textureCoord(const Vector3& uvw); void manualobject_texture_coord_uvw(ManualObjectHandle handle, ref const(coiVector3) uvw); //void textureCoord(const Vector4& xyzw); void manualobject_texture_coord_xyxw(ManualObjectHandle handle, ref const(coiVector4) xyzw); //void colour(const ColourValue& col); void manualobject_colour(ManualObjectHandle handle, ref const(coiColourValue) col); //void colour(Real r, Real g, Real b, Real a = 1.0f); //void index(uint32 idx); void manualobject_index(ManualObjectHandle handle, uint32 idx); //void triangle(uint32 i1, uint32 i2, uint32 i3); void manualobject_triangle(ManualObjectHandle handle, uint32 i1, uint32 i2, uint32 i3); //void quad(uint32 i1, uint32 i2, uint32 i3, uint32 i4); void manualobject_quad(ManualObjectHandle handle, uint32 i1, uint32 i2, uint32 i3, uint32 i4); //size_t getCurrentVertexCount() const; size_t manualobject_get_current_vertex_count(const ManualObjectHandle handle); //size_t getCurrentIndexCount() const; size_t manualobject_get_current_index_count(const ManualObjectHandle handle); //ManualObjectSection* end(void); ManualObjectSectionHandle manualobject_end(ManualObjectHandle handle); //void setMaterialName(size_t subIndex, const String& name, const String & group = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); void manualobject_set_material_name(ManualObjectHandle handle, size_t sub_index, const char* name, const char* group); //MeshPtr convertToMesh(const String& meshName, const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); MeshHandle manualobject_convert_to_mesh(ManualObjectHandle handle, const char* mesh_name, const char* group_name); //void setUseIdentityProjection(bool useIdentityProjection); void manualobject_set_use_identity_projection(ManualObjectHandle handle, bool use_identity_projection); //bool getUseIdentityProjection(void) const; int manualobject_get_use_identity_projection(const ManualObjectHandle handle); //void setUseIdentityView(bool useIdentityView); void manualobject_set_use_identity_view(ManualObjectHandle handle, int use_identity_view); //bool getUseIdentityView(void) const; int manualobject_get_use_identity_view(const ManualObjectHandle handle); //void setBoundingBox(const AxisAlignedBox& box); void manualobject_set_bounding_box(ManualObjectHandle handle, const AxisAlignedBoxHandle box); //ManualObjectSection* getSection(unsigned int index) const; ManualObjectSectionHandle manualobject_get_section(const ManualObjectHandle handle, uint index); //unsigned int getNumSections(void) const; uint manualobject_get_num_sections(const ManualObjectHandle handle); //void setKeepDeclarationOrder(bool keepOrder); void manualobject_set_keep_declaration_order(ManualObjectHandle handle, int keep_order); //bool getKeepDeclarationOrder() const; int manualobject_get_keep_declaration_order(const ManualObjectHandle handle); //const String& getMovableType(void) const; const(char*) manualobject_get_movable_type(const ManualObjectHandle handle); //const AxisAlignedBox& getBoundingBox(void) const; const(AxisAlignedBoxHandle) manualobject_get_bounding_box(const ManualObjectHandle handle); //Real getBoundingRadius(void) const; coiReal manualobject_get_bounding_radius(const ManualObjectHandle handle); //TODO: void _updateRenderQueue(RenderQueue* queue); //TODO: EdgeData* getEdgeList(void); //bool hasEdgeList(void); int manualobject_has_edge_list(ManualObjectHandle handle); //TODO: ShadowRenderableListIterator getShadowVolumeRenderableIterator(ShadowTechnique shadowTechnique, const Light* light, HardwareIndexBufferSharedPtr* indexBuffer, bool extrudeVertices, Real extrusionDist, unsigned long flags = 0); // Ogre::ManualObject::ManualObjectSection //ManualObjectSection(ManualObject* parent, const String& materialName, RenderOperation::OperationType opType, const String & groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); ManualObjectSectionHandle create_manualobjectsection(ManualObjectHandle parent, const char* material_name, operation_type op_type, const char* group_name); //~ManualObjectSection(); void destroy_manualobjectsection(ManualObjectSectionHandle handle); //RenderOperation* getRenderOperation(void); RenderOperationHandle manualobjectsection_get_render_operation(ManualObjectSectionHandle handle); //const String& getMaterialName(void) const const(char*) manualobjectsection_get_material_name(const ManualObjectSectionHandle handle); //const String& getMaterialGroup(void) const const(char*) manualobjectsection_get_material_group(const ManualObjectSectionHandle handle); //void setMaterialName(const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ) void manualobjectsection_set_material_name(ManualObjectSectionHandle handle, const char* name, const char* group_name); //void set32BitIndices(bool n32) void manualobjectsection_set_32_bit_indices(ManualObjectSectionHandle handle, int n32); //bool get32BitIndices() const int manualobjectsection_get_32_bit_indices(const ManualObjectSectionHandle handle); //TODO:const MaterialPtr& getMaterial(void) const //void getRenderOperation(RenderOperation& op) void manualobjectsection_renderable_get_render_operation(ManualObjectSectionHandle handle, RenderOperationHandle renderOp); //void getWorldTransforms(Matrix4* xform) const void manualobjectsection_get_world_transforms(const ManualObjectSectionHandle handle, ref coiMatrix4 xform); //Real getSquaredViewDepth(const Ogre::Camera *) const coiReal manualobjectsection_get_squared_view_depth(const ManualObjectSectionHandle handle, const CameraHandle cam); //TODO: const LightList &getLights(void) const //Ogre::Resource::Listener ResourceListenerHandle create_resourcelistener(loadingCompleteCB loading_cb, preparingCompleteCB preparing_cb, unloadingCompleteCB unloading_cb, void* userdata); void destroy_resourcelistener(ResourceListenerHandle handle); // Ogre::Resource void destroy_resource(coiResourceHandle handle); //void prepare(bool backgroundThread = false) void resource_prepare(coiResourceHandle handle, int background_thread); //void load(bool backgroundThread = false) void resource_load(coiResourceHandle handle, int background_thread); //void reload() void resource_reload(coiResourceHandle handle); //bool isReloadable(void) const int resource_is_reloadable(const coiResourceHandle handle); //bool isManuallyLoaded(void) const int resource_is_manually_loaded(const coiResourceHandle handle); //void unload(void) void resource_unload(coiResourceHandle handle); //size_t getSize(void) const size_t resource_get_size(const coiResourceHandle handle); //void touch(void) void resource_touch(coiResourceHandle handle); //const String& getName(void) const const(char*) resource_get_name(const coiResourceHandle handle); //ResourceHandle getHandle(void) const ResourceHandle resource_get_handle(const coiResourceHandle handle); //bool isPrepared(void) const int resource_is_prepared(const coiResourceHandle handle); //bool isLoaded(void) const int resource_is_loaded(const coiResourceHandle handle); //bool isLoading() const int resource_is_loading(const coiResourceHandle handle); //LoadingState getLoadingState() const loading_state resource_get_loading_state(const coiResourceHandle handle); //bool isBackgroundLoaded(void) const int resource_is_background_loaded(const coiResourceHandle handle); //void setBackgroundLoaded(bool bl) void resource_set_background_loaded(coiResourceHandle handle, int bl); //void escalateLoading() void resource_escalate_loading(coiResourceHandle handle); //void addListener(Listener* lis) void resource_add_listener(coiResourceHandle handle, ResourceListenerHandle listener); //void removeListener(Listener* lis) void resource_remove_listener(coiResourceHandle handle, ResourceListenerHandle listener); //const String& getGroup(void) const const(char*) resource_get_group(const coiResourceHandle handle); //void changeGroupOwnership(const String& newGroup) void resource_change_group_ownership(coiResourceHandle handle, const char* new_group); //ResourceManager* getCreator(void) ResourceManagerHandle resource_get_creator(coiResourceHandle handle); //const String& getOrigin(void) const const(char*) resource_get_origin(const coiResourceHandle handle); //void _notifyOrigin(const String& origin) void resource__notify_origin(coiResourceHandle handle, const char* origin); //size_t getStateCount() const size_t resource_get_state_count(const coiResourceHandle handle); //void _dirtyState() void resource__dirty_state(coiResourceHandle handle); //void _fireLoadingComplete(bool wasBackgroundLoaded) void resource__fire_loading_complete(coiResourceHandle handle, int was_background_loaded); //void _firePreparingComplete(bool wasBackgroundLoaded) void resource__fire_preparing_complete(coiResourceHandle handle, int was_background_loaded); //void _fireUnloadingComplete(void) void resource__fire_unloading_complete(coiResourceHandle handle); //typedef SharedPtr<Resource> ResourcePtr //Ogre::ManualResourceLoader //~ManualResourceLoader() void destroy_manualresourceloader(ManualResourceLoaderHandle handle); //void prepareResource(Resource* resource) void manualresourceloader_prepare_resource(ManualResourceLoaderHandle handle, coiResourceHandle resource); //void loadResource(Resource* resource) void manualresourceloader_load_resource(ManualResourceLoaderHandle handle, coiResourceHandle resource); //Ogre::ResourceManager //~ResourceManager(); void destroy_resourcemanager(ResourceManagerHandle handle); //ResourcePtr create(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* createParams = 0) ResourcePtrHandle resourcemanager_create(ResourceManagerHandle handle, const char* name, const char* group, int is_manual, ManualResourceLoaderHandle l, const NameValuePairListHandle nvp); //typedef std::pair<ResourcePtr, bool> ResourceCreateOrRetrieveResult //TODO: ResourceCreateOrRetrieveResult createOrRetrieve(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* createParams = 0) //void setMemoryBudget( size_t bytes) void resourcemanager_set_memory_budget(ResourceManagerHandle handle, size_t bytes); //size_t getMemoryBudget(void) const size_t resourcemanager_get_memory_budget(const ResourceManagerHandle handle); //size_t getMemoryUsage(void) const size_t resourcemanager_get_memory_usage(const ResourceManagerHandle handle); //void unload(const String& name) void resourcemanager_unload_by_name(ResourceManagerHandle handle, const char* name); //void unload(ResourceHandle handle) void resourcemanager_unload_by_handle(ResourceManagerHandle handle, ResourceHandle res_handle); //void unloadAll(bool reloadableOnly = true) void resourcemanager_unload_all(ResourceManagerHandle handle, int reloadable_only); //void reloadAll(bool reloadableOnly = true) void resourcemanager_reload_all(ResourceManagerHandle handle, int reloadable_only); //void unloadUnreferencedResources(bool reloadableOnly = true) void resourcemanager_unload_unreferenced_resources(ResourceManagerHandle handle, int reloadable_only); //void reloadUnreferencedResources(bool reloadableOnly = true) void resourcemanager_reload_unreferenced_resources(ResourceManagerHandle handle, int reloadable_only); //void remove(ResourcePtr& r) void resourcemanager_remove_by_ptr(ResourceManagerHandle handle, ResourcePtrHandle resource_ptr); //void remove(const String& name) void resourcemanager_remove_by_name(ResourceManagerHandle handle, const char* name); //void remove(ResourceHandle handle) void resourcemanager_remove_by_handle(ResourceManagerHandle handle, ResourceHandle res_handle); //void removeAll(void) void resourcemanager_remove_all(ResourceManagerHandle handle); //void removeUnreferencedResources(bool reloadableOnly = true) void resourcemanager_remove_unreferenced_resources(ResourceManagerHandle handle, int reloadable_only); //ResourcePtr getByName(const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) ResourcePtrHandle resourcemanager_get_by_name(ResourceManagerHandle handle, const char* name, const char* group_name); //ResourcePtr getByHandle(ResourceHandle handle) ResourcePtrHandle resourcemanager_get_by_handle(ResourceManagerHandle handle, ResourceHandle res_handle); //bool resourceExists(const String& name) bool resourcemanager_exists_by_name(ResourceManagerHandle handle, const char* name); //bool resourceExists(ResourceHandle handle) bool resourcemanager_exists_by_handle(ResourceManagerHandle handle, ResourceHandle res_handle); //void _notifyResourceTouched(Resource* res) void resourcemanager__notify_resource_touched(ResourceManagerHandle handle, coiResourceHandle res); //void _notifyResourceLoaded(Resource* res) void resourcemanager__notify_resource_loaded(ResourceManagerHandle handle, coiResourceHandle res); //void _notifyResourceUnloaded(Resource* res) void resourcemanager__notify_resource_unloaded(ResourceManagerHandle handle, coiResourceHandle res); //ResourcePtr prepare(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0, bool backgroundThread = false) ResourcePtrHandle resourcemanager_prepare(ResourceManagerHandle handle, const char* name, const char* group, int is_manual, ManualResourceLoaderHandle loader, NameValuePairListHandle load_params, int background_thread); //ResourcePtr load(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0, bool backgroundThread = false) ResourcePtrHandle resourcemanager_load(ResourceManagerHandle handle, const char* name, const char* group, int is_manual, ManualResourceLoaderHandle loader, NameValuePairListHandle load_params, int background_thread); //TODO:const StringVector& getScriptPatterns(void) const //TODO: void parseScript(DataStreamPtr& stream, const String& groupName) //Real getLoadingOrder(void) const coiReal resourcemanager_get_loading_order(const ResourceManagerHandle handle); //const String& getResourceType(void) const const(char*) resourcemanager_get_resource_type(const ResourceManagerHandle handle); //void setVerbose(bool v) void resourcemanager_set_verbose(ResourceManagerHandle handle, int v); //bool getVerbose(void) bool resourcemanager_get_verbose(ResourceManagerHandle handle);
/****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* MeshHandle; alias void* TimerHandle; alias void* WindowListenerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { /// Point light sources give off light equally in all directions, so require only position not direction LT_POINT = 0, /// Directional lights simulate parallel light beams from a distant source, hence have direction but no position LT_DIRECTIONAL = 1, /// Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); TimerHandle root_get_timer(); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); void scenemanager_set_sky_box(SceneManagerHandle handle, int enable, const char* material_name, float distance, int draw_first, const coiQuaternion* orientation, const char* group_name); void scenemanager_set_sky_dome(SceneManagerHandle handle, int enable, const char* material_name, float curvature, float tiling, float distance, int draw_first, const coiQuaternion* orientation, int xsegments, int ysegments, int ysegments_keep, const char* group_name); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); void destroy_light(LightHandle handle); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref ColourValue colour); void light_set_specular_colour(LightHandle handle, const ref ColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); WindowListenerHandle add_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerEvent window_event, void* userdata); void remove_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerHandle listener_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); void render_window_get_custom_attribute(RenderWindowHandle handle, const char* attribute, void* pdata); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); void plane_get_normal(PlaneHandle handle, coiVector3* normal); void plane_set_normal(PlaneHandle handle, const coiVector3* normal); coiReal plane_get_d(PlaneHandle handle); void plane_set_d(PlaneHandle handle, coiReal d); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); // Ogre::Timer int timer_set_option(TimerHandle handle, const char* key, void* value); ulong timer_get_milliseconds(TimerHandle handle); ulong timer_get_microseconds(TimerHandle handle); ulong timer_get_milliseconds_cpu(TimerHandle handle); ulong timer_get_microseconds_cpu(TimerHandle handle); void timer_reset(TimerHandle handle); missed a file in the last commit /****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* MeshHandle; alias void* TimerHandle; alias void* WindowListenerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { /// Point light sources give off light equally in all directions, so require only position not direction LT_POINT = 0, /// Directional lights simulate parallel light beams from a distant source, hence have direction but no position LT_DIRECTIONAL = 1, /// Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); TimerHandle root_get_timer(); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); void scenemanager_set_sky_box(SceneManagerHandle handle, int enable, const char* material_name, float distance, int draw_first, const coiQuaternion* orientation, const char* group_name); void scenemanager_set_sky_dome(SceneManagerHandle handle, int enable, const char* material_name, float curvature, float tiling, float distance, int draw_first, const coiQuaternion* orientation, int xsegments, int ysegments, int ysegments_keep, const char* group_name); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_derived_position(SceneNodeHandle handle, const coiVector3* pos); void scenenode_get_derived_position(SceneNodeHandle handle, coiVector3* pos); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); void destroy_light(LightHandle handle); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref ColourValue colour); void light_set_specular_colour(LightHandle handle, const ref ColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); WindowListenerHandle add_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerEvent window_event, void* userdata); void remove_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerHandle listener_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); void render_window_get_custom_attribute(RenderWindowHandle handle, const char* attribute, void* pdata); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); void plane_get_normal(PlaneHandle handle, coiVector3* normal); void plane_set_normal(PlaneHandle handle, const coiVector3* normal); coiReal plane_get_d(PlaneHandle handle); void plane_set_d(PlaneHandle handle, coiReal d); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); // Ogre::Timer int timer_set_option(TimerHandle handle, const char* key, void* value); ulong timer_get_milliseconds(TimerHandle handle); ulong timer_get_microseconds(TimerHandle handle); ulong timer_get_milliseconds_cpu(TimerHandle handle); ulong timer_get_microseconds_cpu(TimerHandle handle); void timer_reset(TimerHandle handle);
/****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; }; struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; }; struct ColourValue { float r; float g; float b; float a; }; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); void destroy_light(LightHandle handle); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle create_plane(); void destroy_plane(PlaneHandle handle); exposed new wrapped methods, enums, etc in D2 as well. /****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* MeshHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); void destroy_light(LightHandle handle); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer);
/****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; } ; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; enum logging_level { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum log_message_level { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; alias void function(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void load_ogre_plugin(const char * plugin); SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); void log_message(const char* message); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message); //LogManager::destroyLog void logmanager_set_log_detail(logging_level lvl); // XXX: How should we handle functions with multiple overloads? // e.g., this can take either an Ogre::String or a Log* //LogManager::destroyLog void logmanager_destroy_log(const char* name); void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener void add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::removeListener void remove_log_listener(LogListenerEvent log_event, LogHandle log_handle); added newly exposed methods to D2 interface /****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* NameValuePairListHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; } ; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; enum logging_level { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum log_message_level { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message); //LogManager::destroyLog void logmanager_set_log_detail(logging_level lvl); // XXX: How should we handle functions with multiple overloads? // e.g., this can take either an Ogre::String or a Log* //LogManager::destroyLog void logmanager_destroy_log(const char* name); void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener void add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::removeListener void remove_log_listener(LogListenerEvent log_event, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, .../*int zorder, float left, float top, float width, float height*/); int render_window_is_closed(RenderWindowHandle handle);
/****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; }; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); added newly exposed methods and typedefs to D2 interface file. /****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; alias ushort uint16; alias ushort SceneTypeMask; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; }; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum SceneType { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE();
/****************************************************************************** * ogre_interface.d - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; private import core.stdc.config : c_long, c_ulong; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* NodeHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* PlaneListHandle; alias void* PlaneBoundedVolumeHandle; alias void* MeshHandle; alias void* TimerHandle; alias void* WindowListenerHandle; alias void* AxisAlignedBoxHandle; alias void* RayHandle; alias void* SphereHandle; alias void* SceneQueryHandle; alias void* RaySceneQueryHandle; alias void* RaySceneQueryResultHandle; alias void* SceneQueryListenerHandle; alias void* RaySceneQueryListenerHandle; alias void* SceneQueryResultHandle; alias void* MovableObjectHandle; alias void* RenderOperationHandle; alias void* OverlayHandle; alias void* OverlayManagerHandle; alias void* OverlayElementHandle; alias void* PanelOverlayElementHandle; alias void* OverlayContainerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; alias int function(const ref world_fragment frag, void* userdata) SceneQueryFragmentResult; alias int function(MovableObjectHandle handle, void* userdata) SceneQueryObjectResult; alias int function(const ref world_fragment frag, coiReal distance, void* userdata) RaySceneQueryFragmentResult; alias int function(MovableObjectHandle handle, coiReal distance, void* userdata) RaySceneQueryObjectResult; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct coiMatrix3 { coiReal m[3][3]; } struct coiMatrix4 { coiReal m[4][4]; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; } struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ray_pair { int intersects; coiReal distance; } struct coiColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; c_ulong bestFrameTime; c_ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; struct world_fragment { world_fragment_type fragment_type; coiVector3 single_intersection; PlaneListHandle planes; void* geometry; RenderOperationHandle render_op; } struct rayscenequery_result_entry { coiReal distance; MovableObjectHandle movable; world_fragment* fragment; } enum logging_level { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum log_message_level { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum orientation_mode { OR_DEGREE_0 = 0, OR_DEGREE_90 = 1, OR_DEGREE_180 = 2, OR_DEGREE_270 = 3, OR_PORTRAIT = OR_DEGREE_0, OR_LANDSCAPERIGHT = OR_DEGREE_90, OR_LANDSCAPELEFT = OR_DEGREE_270 } enum projection_type { PT_ORTHOGRAPHIC, PT_PERSPECTIVE } enum frustum_plane { FRUSTUM_PLANE_NEAR = 0, FRUSTUM_PLANE_FAR = 1, FRUSTUM_PLANE_LEFT = 2, FRUSTUM_PLANE_RIGHT = 3, FRUSTUM_PLANE_TOP = 4, FRUSTUM_PLANE_BOTTOM = 5 } enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF } enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { /// Point light sources give off light equally in all directions, so require only position not direction LT_POINT = 0, /// Directional lights simulate parallel light beams from a distant source, hence have direction but no position LT_DIRECTIONAL = 1, /// Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; enum Extent { EXTENT_NULL, EXTENT_FINITE, EXTENT_INFINITE }; enum CornerEnum { FAR_LEFT_BOTTOM = 0, FAR_LEFT_TOP = 1, FAR_RIGHT_TOP = 2, FAR_RIGHT_BOTTOM = 3, NEAR_RIGHT_BOTTOM = 7, NEAR_LEFT_BOTTOM = 6, NEAR_LEFT_TOP = 5, NEAR_RIGHT_TOP = 4 }; enum plane_side { NO_SIDE, POSITIVE_SIDE, NEGATIVE_SIDE, BOTH_SIDE }; enum world_fragment_type { /// Return no world geometry hits at all WFT_NONE, /// Return pointers to convex plane-bounded regions WFT_PLANE_BOUNDED_REGION, /// Return a single intersection point (typically RaySceneQuery only) WFT_SINGLE_INTERSECTION, /// Custom geometry as defined by the SceneManager WFT_CUSTOM_GEOMETRY, /// General RenderOperation structure WFT_RENDER_OPERATION }; enum gui_metrics_mode { GMM_RELATIVE, GMM_PIXELS, GMM_RELATIVE_ASPECT_ADJUSTED }; enum gui_horizontal_alignment { GHA_LEFT, GHA_CENTER, GHA_RIGHT }; enum gui_vertical_alignment { GVA_TOP, GVA_CENTER, GVA_BOTTOM }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); TimerHandle root_get_timer(); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, c_ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char* plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); void scenemanager_set_sky_box(SceneManagerHandle handle, int enable, const char* material_name, float distance, int draw_first, const coiQuaternion* orientation, const char* group_name); void scenemanager_set_sky_dome(SceneManagerHandle handle, int enable, const char* material_name, float curvature, float tiling, float distance, int draw_first, const coiQuaternion* orientation, int xsegments, int ysegments, int ysegments_keep, const char* group_name); const(char*) scenemanager_get_name(SceneManagerHandle handle); //void SceneManager::destroyQuery(Ogre::SceneQuery* query); void scenemanager_destroy_scenequery(SceneManagerHandle handle, SceneQueryHandle query); // Ogre::SceneManager::createRayQuery(Ogre::Ray const&, unsigned long) RaySceneQueryHandle scenemanager_create_rayquery(SceneQueryHandle handle, RayHandle ray_handle, c_ulong mask); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Ogre::Node //Ogre::Node::getName() const const(char*) node_get_name(NodeHandle handle); //Ogre::Node::getParent() const //XXX: May be NULL if this is the root node. NodeHandle node_get_parent(NodeHandle handle); //Ogre::Node::getOrientation() const void node_get_orientation(NodeHandle handle, ref coiQuaternion result); //Ogre::Node::setOrientation(Ogre::Quaternion const&) void node_set_orientation(NodeHandle handle, const ref coiQuaternion orientation); //Ogre::Node::setScale(Ogre::Vector3 const&) void node_set_scale(NodeHandle handle, const ref coiVector3 in_scale); //Ogre::Node::setScale(Ogre::Vector3 const&) void node_set_scale_xyz(NodeHandle handle, const float x, const float y, const float z); //Ogre::Node::getScale() const void node_get_scale(NodeHandle handle, ref coiVector3 result); //Ogre::Node::setInheritOrientation(bool) void node_set_inherit_orientation(NodeHandle handle, int inherit); //Ogre::Node::getInheritOrientation() const int node_get_inherit_orientation(NodeHandle handle); //Ogre::Node::resetOrientation() void node_reset_orientation(NodeHandle handle); //Ogre::Node::setInheritScale(bool) void node_set_inherit_scale(NodeHandle handle, int inherit); //Ogre::Node::getInheritScale() const int node_get_inherit_scale(NodeHandle handle); //Ogre::Node::scale(Ogre::Vector3 const&) void node_scale(NodeHandle handle, const ref coiVector3 scale); //Ogre::Node::scale(Ogre::Vector3 const&) void node_scale_xyz(NodeHandle handle, const float x, const float y, const float z); //Ogre::Node::translate(Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate(NodeHandle handle, const ref coiVector3 d, transform_space relative_to); //Ogre::Node::translate(Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate_xyz(NodeHandle handle, const float x, const float y, const float z, transform_space relative_to); //Ogre::Node::translate(Ogre::Matrix3 const&, float, float, float, Ogre::Node::TransformSpace) //Ogre::Node::translate(Ogre::Matrix3 const&, Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate_m(NodeHandle handle, const ref coiMatrix3 axes, const ref coiVector3 move, transform_space relative_to); //Ogre::Node::roll(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_roll(NodeHandle handle, const coiReal angle, transform_space relative_to); //Ogre::Node::pitch(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_pitch(NodeHandle handle, const coiReal angle, transform_space relative_to); // Ogre::Node::yaw(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_yaw(NodeHandle handle, const coiReal angle, transform_space relative_to); //Ogre::Node::rotate(Ogre::Vector3 const&, Ogre::Radian const&, Ogre::Node::TransformSpace) void node_rotate(NodeHandle handle, const ref coiVector3 axis, const coiReal angle, transform_space relative_to); //Ogre::Node::rotate(Ogre::Quaternion const&, Ogre::Node::TransformSpace) void node_rotate_q(NodeHandle handle, const ref coiQuaternion q, transform_space relative_to); //Ogre::Node::getLocalAxes() const void node_get_local_axes(NodeHandle handle, ref coiMatrix3 result); //Ogre::Node::createChild(Ogre::Vector3 const&, Ogre::Quaternion const&) NodeHandle node_create_child(NodeHandle handle, const ref coiVector3 translate, const ref coiQuaternion rotate); //Ogre::Node::createChild(std::string const&, Ogre::Vector3 const&, Ogre::Quaternion const&) NodeHandle node_create_named_child(NodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); //Ogre::Node::addChild(Ogre::Node*) void node_add_child(NodeHandle handle, NodeHandle child); //Ogre::Node::numChildren() const ushort node_num_children(NodeHandle handle); //Ogre::Node::getChild(unsigned short) const NodeHandle node_get_child_by_index(NodeHandle handle, ushort index); //Ogre::Node::getChild(std::string const&) const NodeHandle node_get_child_by_name(NodeHandle handle, const char* name); // Ogre::SceneNode SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); ushort scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_get_position(SceneNodeHandle handle, ref coiVector3 pos); void scenenode_set_derived_position(SceneNodeHandle handle, const ref coiVector3 pos); void scenenode_get_derived_position(SceneNodeHandle handle, ref coiVector3 pos); //void setFixedYawAxis( bool useFixed, const Vector3& fixedAxis = Vector3::UNIT_Y ); void scenenode_set_fixed_yaw_axis(SceneNodeHandle handle, int use_fixed, const ref coiVector3 fixed_axis); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle, transform_space relative_to); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref coiColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); //Ogre::Viewport::setDimensions(float, float, float, float) void viewport_set_dimensions(ViewportHandle handle, coiReal left, coiReal top, coiReal width, coiReal height); //Ogre::Viewport::getActualDimensions(int&, int&, int&, int&) const void viewport_get_actual_dimensions(ViewportHandle handle, ref int left, ref int top, ref int width, ref int height); //Ogre::Viewport::getBackgroundColour() const void viewport_get_background_colour(ViewportHandle handle, ref coiColourValue cv); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, ref coiVector3 v3); void camera_get_up(CameraHandle handle, ref coiVector3 up); void camera_get_right(CameraHandle handle, ref coiVector3 right); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); void camera_roll(CameraHandle handle, coiReal angle); void camera_yaw(CameraHandle handle, coiReal angle); void camera_pitch(CameraHandle handle, coiReal angle); void camera_rotate(CameraHandle handle, const ref coiVector3 axis, coiReal angle); void camera_rotate_q(CameraHandle handle, const ref coiQuaternion q); //Ogre::Camera::setFixedYawAxis(bool, Ogre::Vector3 const&) void camera_set_fixed_yaw_axis(CameraHandle handle, int on, const ref coiVector3 fixed_axis); //Ogre::Camera::getOrientation() const void camera_get_orientation(CameraHandle handle, ref coiQuaternion orientation); //Ogre::Camera::setOrientation(Ogre::Quaternion const&) void camera_set_orientation(CameraHandle handle, const ref coiQuaternion orientation); //Ogre::Camera::getDerivedOrientation() const void camera_get_derived_orientation(CameraHandle handle, ref coiQuaternion orientation); //Ogre::Camera::getDerivedPosition() const void camera_get_derived_position(CameraHandle handle, ref coiVector3 position); //Ogre::Camera::getDerivedDirection() const void camera_get_derived_direction(CameraHandle handle, ref coiVector3 direction); //Ogre::Camera::getDerivedUp() const void camera_get_derived_up(CameraHandle handle, ref coiVector3 up); //Ogre::Camera::getDerivedRight() const void camera_get_derived_right(CameraHandle handle, ref coiVector3 right); //Ogre::Camera::setAutoTracking(bool, Ogre::SceneNode*, Ogre::Vector3 const&) void camera_set_autotracking(CameraHandle handle, int on, SceneNodeHandle sn_handle, const ref coiVector3 offset); //Ogre::Camera::setLodBias(float) void camera_set_lod_bias(CameraHandle handle, coiReal factor); //Ogre::Camera::getLodBias() const coiReal camera_get_lod_bias(CameraHandle handle); //Ogre::Camera::getCameraToViewportRay(float, float, Ogre::Ray*) const void camera_get_camera_to_viewport_ray(CameraHandle handle, coiReal screenx, coiReal screeny, RayHandle ray); //Ogre::Camera::setWindow(float, float, float, float) void camera_set_window(CameraHandle handle, coiReal left, coiReal top, coiReal right, coiReal bottom); SceneManagerHandle camera_get_scenemanager(CameraHandle handle); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); //Ogre::Entity::getBoundingBox() const AxisAlignedBoxHandle entity_get_bounding_box(EntityHandle handle); //Ogre::Entity::getBoundingRadius() const coiReal entity_get_bounding_radius(EntityHandle handle); // Light LightHandle create_light(const char* light_name); void destroy_light(LightHandle handle); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); //Ogre::Light::getPosition() const void light_get_position(LightHandle handle, ref coiVector3 pos); //Ogre::Light::getPosition() const void light_get_position_xyz(LightHandle handle, ref float x, ref float y, ref float z); //Ogre::Light::getPosition() const void light_get_position_xyz(LightHandle handle, float* x, float* y, float* z); //Ogre::Light::setDirection(float, float, float) void light_set_direction_xyz(LightHandle handle, const float x, const float y, const float z); //Ogre::Light::setDirection(Ogre::Vector3 const&) void light_set_direction(LightHandle handle, const ref coiVector3 direction); //Ogre::Light::getDirection() const void light_get_direction(LightHandle handle, ref coiVector3 direction); //Ogre::Light::setSpotlightRange(Ogre::Radian const&, Ogre::Radian const&, float) void light_set_spotlight_range(LightHandle handle, const coiReal inner_angle, const coiReal outer_angle, coiReal fall_off); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref coiColourValue colour); void light_set_specular_colour(LightHandle handle, const ref coiColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); WindowListenerHandle add_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerEvent window_event, void* userdata); void remove_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerHandle listener_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(logging_level lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); //Log::logMessage void log_log_message(LogHandle handle, const char* message, log_message_level lml, int maskDebug); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); void render_window_get_custom_attribute(RenderWindowHandle handle, const char* attribute, void* pdata); uint render_window_get_width(RenderWindowHandle handle); uint render_window_get_height(RenderWindowHandle handle); void renderwindow_get_statistics(RenderWindowHandle handle, ref FrameStats stats); void renderwindow_get_statistics_ex(RenderWindowHandle handle, ref float lastFPS, ref float avgFPS, ref float bestFPS, ref float worstFPS); // ColourValue void colourvalue_zero(ref coiColourValue c); void colourvalue_black(ref coiColourValue c); void colourvalue_white(ref coiColourValue c); void colourvalue_red(ref coiColourValue c); void colourvalue_green(ref coiColourValue c); void colourvalue_blue(ref coiColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); void plane_get_normal(PlaneHandle handle, ref coiVector3 normal); void plane_set_normal(PlaneHandle handle, const ref coiVector3 normal); coiReal plane_get_d(PlaneHandle handle); void plane_set_d(PlaneHandle handle, coiReal d); // PlaneList (typedef vector<Plane>::type PlaneList) PlaneListHandle create_planelist(); void destroy_planelist(PlaneListHandle handle); // PlaneBoundedVolume PlaneBoundedVolumeHandle create_planeboundedvolume(plane_side the_outside); void destroy_planeboundedvolume(PlaneBoundedVolumeHandle handle); // bool intersects(const AxisAlignedBox&) const int planeboundedvolume_intersects_axisalignedbox(PlaneBoundedVolumeHandle handle, AxisAlignedBoxHandle query); // bool intersects(const Sphere&) const int planeboundedvolume_intersects_sphere(PlaneBoundedVolumeHandle handle, SphereHandle query); // std::pair<bool, Real> intersects(const Ray&) const void planeboundedvolume_intersects_ray(PlaneBoundedVolumeHandle handle, RayHandle query, ref ray_pair result); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); // Ogre::Timer int timer_set_option(TimerHandle handle, const char* key, void* value); c_ulong timer_get_milliseconds(TimerHandle handle); c_ulong timer_get_microseconds(TimerHandle handle); c_ulong timer_get_milliseconds_cpu(TimerHandle handle); c_ulong timer_get_microseconds_cpu(TimerHandle handle); void timer_reset(TimerHandle handle); // Ogre::AxisAlignedBox AxisAlignedBoxHandle create_axis_aligned_box(); AxisAlignedBoxHandle create_axis_aligned_box_ex(Extent e); AxisAlignedBoxHandle create_axis_aligned_box_v3(const ref coiVector3 min, const ref coiVector3 max); void destroy_axis_aligned_box(AxisAlignedBoxHandle handle); void axisalignedbox_get_size(AxisAlignedBoxHandle handle, ref coiVector3 size); void axisalignedbox_get_minimum(AxisAlignedBoxHandle handle, ref coiVector3 minimum); void axisalignedbox_get_maximum(AxisAlignedBoxHandle handle, ref coiVector3 maximum); void axisalignedbox_set_minimum_x(AxisAlignedBoxHandle handle, coiReal x); void axisalignedbox_set_minimum_y(AxisAlignedBoxHandle handle, coiReal y); void axisalignedbox_set_minimum_z(AxisAlignedBoxHandle handle, coiReal z); void axisalignedbox_set_minimum(AxisAlignedBoxHandle handle, const ref coiVector3 min); void axisalignedbox_set_maximum(AxisAlignedBoxHandle handle, const ref coiVector3 max); void axisalignedbox_set_maximum_x(AxisAlignedBoxHandle handle, coiReal x); void axisalignedbox_set_maximum_y(AxisAlignedBoxHandle handle, coiReal y); void axisalignedbox_set_maximum_z(AxisAlignedBoxHandle handle, coiReal z); void axisalignedbox_set_extents(AxisAlignedBoxHandle handle, const ref coiVector3 min, const ref coiVector3 max); void axisalignedbox_get_corner(AxisAlignedBoxHandle handle, CornerEnum e, ref coiVector3 corner); //Ogre::Ray RayHandle create_ray(const ref coiVector3 origin, const ref coiVector3 direction); void destroy_ray(RayHandle handle); //Ray::setOrigin void ray_set_origin(RayHandle handle, const ref coiVector3 origin); //Ray::getOrigin void ray_get_origin(RayHandle handle, ref coiVector3 origin); //Ray::setDirection void ray_set_direction(RayHandle handle, const ref coiVector3 direction); //Ray::getDirection void ray_get_direction(RayHandle handle, ref coiVector3 direction); //Ray::getPoint void ray_get_point(RayHandle handle, coiReal units, ref coiVector3 point); //Ray::intersects(Plane) void ray_intersects_plane(RayHandle handle, PlaneHandle plane_handle, ref ray_pair result); //Ray::intersects(AxisAlignedBox) void ray_intersects_axisalignedbox(RayHandle handle, AxisAlignedBoxHandle query_handle, ref ray_pair result); //Ray::intersects(Sphere) void ray_intersects_sphere(RayHandle handle, SphereHandle query_handle, ref ray_pair result); // Ogre::Sphere SphereHandle create_sphere(const ref coiVector3 center, coiReal radius); void destroy_sphere(SphereHandle handle); //void setRadius(Real) void sphere_set_radius(SphereHandle handle, coiReal radius); //Real getRadius(void) const coiReal sphere_get_radius(SphereHandle handle); //void setCenter(Vector3) void sphere_set_center(SphereHandle handle, const ref coiVector3 center); //Real getCenter(void) const void sphere_get_center(SphereHandle handle, ref coiVector3 center); // bool intersects(const Sphere&) const int sphere_intersects_sphere(SphereHandle handle, SphereHandle query); // bool intersects(const AxisAlignedBox&) const int sphere_intersects_axisalignedbox(SphereHandle handle, AxisAlignedBoxHandle query); // bool intersects(const Plane&) const int sphere_intersects_plane(SphereHandle handle, PlaneHandle query); // bool intersects(const Vector3&) const int sphere_intersects_vector3(SphereHandle handle, const ref coiVector3 query); // void merge(const Sphere&) void sphere_merge(SphereHandle handle, SphereHandle other_sphere); // Ogre::SceneQuery // SceneQuery::setQueryMask(uint32 mask) void scenequery_set_query_mask(SceneQueryHandle handle, uint32 mask); //uint32 SceneQuery::getQueryMask(void) const uint32 scenequery_get_query_mask(SceneQueryHandle handle); //void SceneQuery::setWorldFragmentType(enum WorldFragmentType wft); void scenequery_set_world_fragment_type(SceneQueryHandle handle, world_fragment_type wft); //WorldFragmentType SceneQuery::getWorldFragmentType(void) const; world_fragment_type scenequery_get_world_fragment_type(SceneQueryHandle handle); // SceneQueryListener SceneQueryListenerHandle create_scenequerylistener(SceneQueryFragmentResult fragment_callback, SceneQueryObjectResult object_callback, void* userdata); void destroy_scenequerylistener(SceneQueryListenerHandle handle); size_t scenequeryresult_movables_count(SceneQueryResultHandle handle); MovableObjectHandle scenequeryresult_movables_at(SceneQueryResultHandle handle, int index); size_t scenequeryresult_worldfragments_count(SceneQueryResultHandle handle, int index); void scenequeryresult_worldfragments_at(SceneQueryResultHandle handle, int index, ref world_fragment result); RaySceneQueryListenerHandle create_rayscenequerylistener(RaySceneQueryFragmentResult fragment_callback, RaySceneQueryObjectResult object_callback, void* userdata); void destroy_rayscenequerylistener(RaySceneQueryListenerHandle handle); //setRay void rayscenequery_set_ray(RaySceneQueryHandle handle, RayHandle ray_handle); //getRay RayHandle rayscenequery_get_ray(RaySceneQueryHandle handle); //void setSortByDistance(bool sort, ushort maxresults = 0); void rayscenequery_set_sort_by_distance(RaySceneQueryHandle handle, int on, ushort maxresults); //bool getSortByDistance(void) const; int rayscenequery_get_sort_by_distance(RaySceneQueryHandle handle); //ushort getMaxResults(void) const; ushort rayscenequery_get_max_results(RaySceneQueryHandle handle); // typedef vector<RaySceneQueryResultEntry>::type RaySceneQueryResult; size_t rayscenequeryresult_count(RaySceneQueryResultHandle handle); void rayscenequeryresult_at(RaySceneQueryResultHandle handle, int index, ref rayscenequery_result_entry result); // Ogre::Overlay //const String& getName(void) const; const(char[]) overlay_get_name(OverlayHandle handle); //void setZOrder(ushort zorder); void overlay_set_zorder(OverlayHandle handle, ushort zorder); //ushort getZOrder(void) const; ushort overlay_get_zorder(OverlayHandle handle); //bool isVisible(void) const; int overlay_is_visible(OverlayHandle handle); //bool isInitialised(void) const; int overlay_is_initialised(OverlayHandle handle); //void show(void); void overlay_show(OverlayHandle handle); //void hide(void); void overlay_hide(OverlayHandle handle); //void add2D(OverlayContainer* cont); void overlay_add_2d(OverlayHandle handle, OverlayContainerHandle cont); //void remove2D(OverlayContainer* cont); void overlay_remove_2d(OverlayHandle handle, OverlayContainerHandle cont); //void add3D(SceneNode* node); void overlay_add_3d(OverlayHandle handle, SceneNodeHandle node_handle); //void remove3D(SceneNode* node); void overlay_remove_3d(OverlayHandle handle, SceneNodeHandle node_handle); // void clear(); void overlay_clear(OverlayHandle handle); //void setScroll(Real x, Real y); void overlay_set_scroll(OverlayHandle handle, coiReal x, coiReal y); //Real getScrollX(void) const; coiReal overlay_get_scroll_x(OverlayHandle handle); //Real getScrollY(void) const; coiReal overlay_get_scroll_y(OverlayHandle handle); //void scroll(Real xoff, Real yoff); void overlay_scroll(OverlayHandle handle, coiReal x, coiReal y); //void setRotate(const Radian& angle); void overlay_set_rotate(OverlayHandle handle, coiReal angle); //const Radian &getRotate(void) const; coiReal overlay_get_rotate(OverlayHandle handle); //void rotate(const Radian& angle); void overlay_rotate(OverlayHandle handle, coiReal angle); //void setScale(Real x, Real y); void overlay_set_scale(OverlayHandle handle, coiReal x, coiReal y); //Real getScaleX(void) const; coiReal overlay_get_scale_x(OverlayHandle handle); //Real getScaleY(void) const; coiReal overlay_get_scale_y(OverlayHandle handle); //void _getWorldTransforms(Matrix4* xform) const; void overlay_get_world_transforms(OverlayHandle handle, ref coiMatrix4 xform); //const String& getOrigin(void) const; const(char[]) overlay_get_origin(OverlayHandle handle); //void _notifyOrigin(const String& origin); void overlay_notify_origin(OverlayHandle handle, const(char*) origin); //Ogre::OverlayManager //OverlayManager(); OverlayManagerHandle create_overlaymanager(); //~OverlayManager(); void destroy_overlaymanager(OverlayManagerHandle handle); //Real getLoadingOrder(void) const; coiReal overlaymanager_get_loading_order(OverlayManagerHandle handle); //Overlay* create(const String& name); OverlayHandle overlaymanager_create(OverlayManagerHandle handle, const char* name); //Overlay* getByName(const String& name); OverlayHandle overlaymanager_get_by_name(OverlayManagerHandle handle, const char* name); //void destroy(const String& name); void overlaymanager_destroy_by_name(OverlayManagerHandle handle, const char* name); //void destroy(Overlay* overlay); void overlaymanager_destroy(OverlayManagerHandle handle, OverlayHandle overlay_handle); //void destroyAll(void); void overlaymanager_destroy_all(OverlayManagerHandle handle); //bool hasViewportChanged(void) const; int overlaymanager_has_viewport_changed(OverlayManagerHandle handle); //int getViewportHeight(void) const; int overlaymanager_get_viewport_height(OverlayManagerHandle handle); //int getViewportWidth(void) const; int overlaymanager_get_viewport_width(OverlayManagerHandle handle); //Real getViewportAspectRatio(void) const; coiReal overlaymanager_get_viewport_aspect_ratio(OverlayManagerHandle handle); //OrientationMode getViewportOrientationMode(void) const; orientation_mode overlaymanager_get_viewport_orientation_mode(OverlayManagerHandle handle); //OverlayElement* createOverlayElement(const String& typeName, const String& instanceName, bool isTemplate = false); OverlayElementHandle overlaymanager_create_overlayelement(OverlayManagerHandle handle, const char* type_name, const char* instance_name, int is_template); //OverlayElement* getOverlayElement(const String& name, bool isTemplate = false); OverlayElementHandle overlaymanager_get_overlayelement(OverlayManagerHandle handle, const char* name, int is_template); //bool hasOverlayElement(const String& name, bool isTemplate = false); int overlaymanager_has_overlay_element(OverlayManagerHandle handle, const char* name, int is_template); //void destroyOverlayElement(const String& instanceName, bool isTemplate = false); void overlaymanager_destroy_overlay_element(OverlayManagerHandle handle, const char* name, int is_template); //void destroyOverlayElement(OverlayElement* pInstance, bool isTemplate = false); void overlaymanager_destroy_overlay_element_instance(OverlayManagerHandle handle, OverlayElementHandle instance, int is_template); //void destroyAllOverlayElements(bool isTemplate = false); void overlaymanager_destroy_all_overlay_elements(OverlayManagerHandle handle); //OverlayElement* createOverlayElementFromTemplate(const String& templateName, const String& typeName, const String& instanceName, bool isTemplate = false); OverlayElementHandle overlaymanager_create_overlayelement_from_template(OverlayManagerHandle handle, const char* template_name, const char* type_name, const char* instance_name, int is_template); //OverlayElement* cloneOverlayElementFromTemplate(const String& templateName, const String& instanceName); OverlayElementHandle overlaymanager_clone_overlayelement_from_template(OverlayManagerHandle handle, const char* template_name, const char* instance_name); //OverlayElement* createOverlayElementFromFactory(const String& typeName, const String& instanceName); OverlayElementHandle overlaymanager_create_overlayelement_from_factory(OverlayManagerHandle handle, const char* type_name, const char* instance_name); //bool isTemplate (String strName) const int overlaymanager_is_template(OverlayManagerHandle handle, const char* name); //static OverlayManager* getSingletonPtr(void); OverlayManagerHandle overlaymanager_get_singleton_ptr(); // Ogre::OverlayElement //~OverlayElement void destroy_overlayelement(OverlayElementHandle handle); //void initialise(void) void overlayelement_initialise(OverlayElementHandle handle); //const String& getName(void) const; const(char[]) overlayelement_get_name(OverlayElementHandle handle); //void show(void); void overlayelement_show(OverlayElementHandle handle); //void hide(void); void overlayelement_hide(OverlayElementHandle handle); //bool isVisible(void) const; int overlayelement_is_visible(OverlayElementHandle handle); //bool isEnabled() const; int overlayelement_is_enabled(OverlayElementHandle handle); //void setEnabled(bool b); void overlayelement_set_enabled(OverlayElementHandle handle, int b); //void setDimensions(Real width, Real height); void overlayelement_set_dimensions(OverlayElementHandle handle, coiReal width, coiReal height); //void setPosition(Real left, Real top); void overlayelement_set_position(OverlayElementHandle handle, coiReal left, coiReal top); //void setWidth(Real width); void overlayelement_set_width(OverlayElementHandle handle, coiReal width); //Real getWidth(void) const; coiReal overlayelement_get_width(OverlayElementHandle handle); //void setHeight(Real height); void overlayelement_set_height(OverlayElementHandle handle, coiReal height); //Real getHeight(void) const; coiReal overlayelement_get_height(OverlayElementHandle handle); //void setLeft(Real left); void overlayelement_set_left(OverlayElementHandle handle, coiReal left); //Real getLeft(void) const; coiReal overlayelement_get_left(OverlayElementHandle handle); //void setTop(Real Top); void overlayelement_set_top(OverlayElementHandle handle, coiReal top); //Real getTop(void) const; coiReal overlayelement_get_top(OverlayElementHandle handle); //Real _getLeft(void) const; coiReal overlayelement__get_left(OverlayElementHandle handle); //Real _getTop(void) const; coiReal overlayelement__get_top(OverlayElementHandle handle); //Real _getWidth(void) const; coiReal overlayelement__get_width(OverlayElementHandle handle); //Real _getHeight(void) const; coiReal overlayelement__get_height(OverlayElementHandle handle); //void _setLeft(Real left); void overlayelement__set_left(OverlayElementHandle handle, coiReal left); //void _setTop(Real top); void overlayelement__set_top(OverlayElementHandle handle, coiReal top); //void _setWidth(Real width); void overlayelement__set_width(OverlayElementHandle handle, coiReal width); //void _setHeight(Real height); void overlayelement__set_height(OverlayElementHandle handle, coiReal height); //void _setPosition(Real left, Real top); void overlayelement__set_position(OverlayElementHandle handle, coiReal left, coiReal top); //void _setDimensions(Real width, Real height); void overlayelement__set_dimensions(OverlayElementHandle handle, coiReal width, coiReal height); //const String& getMaterialName(void) const; const(char[]) overlayelement_get_material_name(OverlayElementHandle handle); //void setMaterialName(const String& matName); void overlayelement_set_material_name(OverlayElementHandle handle, const char* name); //void getWorldTransforms(Matrix4* xform) const; void overlayelement_get_world_transforms(OverlayElementHandle handle, ref coiMatrix4 xform); //void _positionsOutOfDate(void); void overlayelement__positions_out_of_date(OverlayElementHandle handle); //void _update(void); void overlayelement__update(OverlayElementHandle handle); //void _updateFromParent(void); void overlayelement__update_from_parent(OverlayElementHandle handle); //void _notifyParent(OverlayContainer* parent, Overlay* overlay); void overlayelement__notify_parent(OverlayElementHandle handle, OverlayContainerHandle parent_handle, OverlayHandle overlay_handle); //Real _getDerivedLeft(void); coiReal overlayelement__get_derived_left(OverlayElementHandle handle); //Real _getDerivedTop(void); coiReal overlayelement__get_derived_top(OverlayElementHandle handle); //Real _getRelativeWidth(void); coiReal overlayelement__get_relative_width(OverlayElementHandle handle); //Real _getRelativeHeight(void); coiReal overlayelement__get_relative_height(OverlayElementHandle handle); //ushort _notifyZOrder(ushort newZOrder); ushort overlayelement__notify_zorder(OverlayElementHandle handle, ushort new_zorder); //void _notifyWorldTransforms(const Matrix4& xform); void overlayelement__notify_world_transforms(OverlayElementHandle handle, const ref coiMatrix4 xform); //void _notifyViewport(); void overlayelement__notify_viewport(OverlayElementHandle handle); //const String& getTypeName(void) const; const(char[]) overlayelement_get_type_name(OverlayElementHandle handle); //void setCaption(const DisplayString& text); void overlayelement_set_caption(OverlayElementHandle handle, const char* text); //const DisplayString& getCaption(void) const; const(char[]) overlayelement_get_caption(OverlayElementHandle handle); //void setColour(const ColourValue& col); void overlayelement_set_colour(OverlayElementHandle handle, const ref coiColourValue col); //const ColourValue& getColour(void) const; void overlayelement_get_colour(OverlayElementHandle handle, ref coiColourValue col); //void setMetricsMode(GuiMetricsMode gmm); void overlayelement_set_metrics_mode(OverlayElementHandle handle, gui_metrics_mode gmm); //GuiMetricsMode getMetricsMode(void) const; gui_metrics_mode overlayelement_get_metrics_mode(OverlayElementHandle handle); //void setHorizontalAlignment(GuiHorizontalAlignment gha); void overlayelement_set_horizontal_alignment(OverlayElementHandle handle, gui_horizontal_alignment gha); //GuiHorizontalAlignment getHorizontalAlignment(void) const; gui_horizontal_alignment overlayelement_get_horizontal_alignment(OverlayElementHandle handle); //void setVerticalAlignment(GuiVerticalAlignment gva); void overlayelement_set_vertical_alignment(OverlayElementHandle handle, gui_vertical_alignment gva); //GuiVerticalAlignment getVerticalAlignment(void) const; gui_vertical_alignment overlayelement_get_vertical_alignment(OverlayElementHandle handle); //bool contains(Real x, Real y) const; int overlayelement_contains(OverlayElementHandle handle, coiReal x, coiReal y); //OverlayElement* findElementAt(Real x, Real y); OverlayElementHandle overlayelement_find_element_at(OverlayElementHandle handle, coiReal x, coiReal y); //bool isContainer() const; int overlayelement_is_container(OverlayElementHandle handle); //bool isKeyEnabled() const; int overlayelement_is_key_enabled(OverlayElementHandle handle); //bool isCloneable() const int overlayelement_is_cloneable(OverlayElementHandle handle); //void setCloneable(bool c); void overlayelement_set_cloneable(OverlayElementHandle handle, int c); //OverlayContainer* getParent(); OverlayContainerHandle overlayelement_get_parent(OverlayElementHandle handle); //void _setParent(OverlayContainer* parent); void overlayelement_set_parent(OverlayElementHandle handle, OverlayContainerHandle parent_handle); //ushort getZOrder() const; ushort overlayelement_get_zorder(OverlayElementHandle handle); //Real getSquaredViewDepth(const Camera* cam) const; coiReal overlayelement_get_squared_view_depth(OverlayElementHandle handle, CameraHandle camera_handle); //void copyFromTemplate(OverlayElement* templateOverlay); void overlayelement_copy_from_template(OverlayElementHandle handle, OverlayElementHandle template_handle); //OverlayElement* clone(const String& instanceName); OverlayElementHandle overlayelement_clone(OverlayElementHandle handle, const char* instance_name); //const OverlayElement* getSourceTemplate () const; const(OverlayElementHandle) overlayelement_get_source_template(OverlayElementHandle handle); // Ogre::OverlayContainer void destroy_overlaycontainer(OverlayContainerHandle handle); //void addChild(OverlayElement* elem); void overlaycontainer_add_child(OverlayContainerHandle handle, OverlayElementHandle child_handle); //void addChildImpl(OverlayElement* elem); void overlaycontainer_add_child_impl(OverlayContainerHandle handle, OverlayElementHandle child_handle); //void addChildImpl(OverlayContainer* cont); void overlaycontainer_add_child_container_impl(OverlayContainerHandle handle, OverlayContainerHandle child_handle); //void removeChild(const String& name); void overlaycontainer_remove_child(OverlayContainerHandle handle, const char* name); //OverlayElement* getChild(const String& name); OverlayElementHandle overlaycontainer_get_child(OverlayContainerHandle handle, const char* name); //void initialise(void); void overlaycontainer_initialise(OverlayContainerHandle handle); //void _addChild(OverlayElement* elem); void overlaycontainer__add_child(OverlayContainerHandle handle, OverlayElementHandle elem); //void _removeChild(OverlayElement* elem); void overlaycontainer__remove_child(OverlayContainerHandle handle, OverlayElementHandle elem); //void _removeChild(const String& name); void overlaycontainer__remove_child_by_name(OverlayContainerHandle handle, const char* name); //void _positionsOutOfDate(void); void overlaycontainer__positions_out_of_date(OverlayContainerHandle handle); //void _update(void); void overlaycontainer__update(OverlayContainerHandle handle); //ushort _notifyZOrder(ushort newZOrder); ushort overlaycontainer__notify_zorder(OverlayContainerHandle handle, ushort new_zorder); //void _notifyViewport(); void overlaycontainer__notify_viewport(OverlayContainerHandle handle); //void _notifyWorldTransforms(const Matrix4& xform); void overlaycontainer__notify_world_transforms(OverlayContainerHandle handle, const ref coiMatrix4 xform); //void _notifyParent(OverlayContainer* parent, Overlay* overlay); void overlaycontainer__notify_parent(OverlayContainerHandle handle, OverlayContainerHandle parent_handle, OverlayHandle overlay_handle); //bool isContainer() const; int overlaycontainer_is_container(OverlayContainerHandle handle); //bool isChildrenProcessEvents() const; int overlaycontainer_is_children_process_events(OverlayContainerHandle handle); //void setChildrenProcessEvents(bool val); void overlaycontainer_set_children_process_events(OverlayContainerHandle handle, int val); //OverlayElement* findElementAt(Real x, Real y); OverlayElementHandle overlaycontainer_find_element_at(OverlayContainerHandle handle, coiReal x, coiReal y); //void copyFromTemplate(OverlayElement* templateOverlay); void overlaycontainer_copy_from_template(OverlayContainerHandle handle, OverlayElementHandle template_overlay); //virtual OverlayElement* clone(const String& instanceName); OverlayElementHandle overlaycontainer_clone(OverlayContainerHandle handle, const char* instance_name); // Ogre::PanelOverlayElement //PanelOverlayElement(const String& name); PanelOverlayElementHandle create_paneloverlayelement(const char* name); //~PanelOverlayElement(); void destroy_paneloverlayelement(PanelOverlayElementHandle handle); //void initialise(void); void paneloverlayelement_initialise(PanelOverlayElementHandle handle); //void setTiling(Real x, Real y, ushort layer = 0); void paneloverlayelement_set_tiling(PanelOverlayElementHandle handle, coiReal x, coiReal y, ushort layer); //Real getTileX(ushort layer = 0) const; coiReal paneloverlayelement_get_tile_x(const PanelOverlayElementHandle handle, ushort layer); //Real getTileY(ushort layer = 0) const; coiReal paneloverlayelement_get_tile_y(const PanelOverlayElementHandle handle, ushort layer); //void setUV(Real u1, Real v1, Real u2, Real v2); void paneloverlayelement_set_uv(PanelOverlayElementHandle handle, coiReal u1, coiReal v1, coiReal u2, coiReal v2); //void getUV(Real& u1, Real& v1, Real& u2, Real& v2) const; void paneloverlayelement_get_uv(const PanelOverlayElementHandle handle, ref coiReal u1, ref coiReal v1, ref coiReal u2, ref coiReal v2); //void setTransparent(bool isTransparent); void paneloverlayelement_set_transparent(PanelOverlayElementHandle handle, int is_transparent); //bool isTransparent(void) const; int paneloverlayelement_is_transparent(const PanelOverlayElementHandle handle); //const String& getTypeName(void) const; const(char[]) paneloverlayelement_get_type_name(const PanelOverlayElementHandle handle); //TODO: void getRenderOperation(RenderOperation& op); //void setMaterialName(const String& matName); void paneloverlayelement_set_material_name(PanelOverlayElementHandle handle, const char* mat_name); //TODO: void _updateRenderQueue(RenderQueue* queue); update interface file /****************************************************************************** * ogre_interface.d - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; private import core.stdc.config : c_long, c_ulong; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* NodeHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* PlaneListHandle; alias void* PlaneBoundedVolumeHandle; alias void* MeshHandle; alias void* TimerHandle; alias void* WindowListenerHandle; alias void* AxisAlignedBoxHandle; alias void* RayHandle; alias void* SphereHandle; alias void* SceneQueryHandle; alias void* RaySceneQueryHandle; alias void* RaySceneQueryResultHandle; alias void* SceneQueryListenerHandle; alias void* RaySceneQueryListenerHandle; alias void* SceneQueryResultHandle; alias void* MovableObjectHandle; alias void* RenderOperationHandle; alias void* OverlayHandle; alias void* OverlayManagerHandle; alias void* OverlayElementHandle; alias void* PanelOverlayElementHandle; alias void* TextAreaOverlayElementHandle; alias void* OverlayContainerHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; alias int function(const ref world_fragment frag, void* userdata) SceneQueryFragmentResult; alias int function(MovableObjectHandle handle, void* userdata) SceneQueryObjectResult; alias int function(const ref world_fragment frag, coiReal distance, void* userdata) RaySceneQueryFragmentResult; alias int function(MovableObjectHandle handle, coiReal distance, void* userdata) RaySceneQueryObjectResult; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct coiMatrix3 { coiReal m[3][3]; } struct coiMatrix4 { coiReal m[4][4]; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; } struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ray_pair { int intersects; coiReal distance; } struct coiColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; c_ulong bestFrameTime; c_ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; struct world_fragment { world_fragment_type fragment_type; coiVector3 single_intersection; PlaneListHandle planes; void* geometry; RenderOperationHandle render_op; } struct rayscenequery_result_entry { coiReal distance; MovableObjectHandle movable; world_fragment* fragment; } enum logging_level { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum log_message_level { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum orientation_mode { OR_DEGREE_0 = 0, OR_DEGREE_90 = 1, OR_DEGREE_180 = 2, OR_DEGREE_270 = 3, OR_PORTRAIT = OR_DEGREE_0, OR_LANDSCAPERIGHT = OR_DEGREE_90, OR_LANDSCAPELEFT = OR_DEGREE_270 } enum projection_type { PT_ORTHOGRAPHIC, PT_PERSPECTIVE } enum frustum_plane { FRUSTUM_PLANE_NEAR = 0, FRUSTUM_PLANE_FAR = 1, FRUSTUM_PLANE_LEFT = 2, FRUSTUM_PLANE_RIGHT = 3, FRUSTUM_PLANE_TOP = 4, FRUSTUM_PLANE_BOTTOM = 5 } enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF } enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { /// Point light sources give off light equally in all directions, so require only position not direction LT_POINT = 0, /// Directional lights simulate parallel light beams from a distant source, hence have direction but no position LT_DIRECTIONAL = 1, /// Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; enum Extent { EXTENT_NULL, EXTENT_FINITE, EXTENT_INFINITE }; enum CornerEnum { FAR_LEFT_BOTTOM = 0, FAR_LEFT_TOP = 1, FAR_RIGHT_TOP = 2, FAR_RIGHT_BOTTOM = 3, NEAR_RIGHT_BOTTOM = 7, NEAR_LEFT_BOTTOM = 6, NEAR_LEFT_TOP = 5, NEAR_RIGHT_TOP = 4 }; enum plane_side { NO_SIDE, POSITIVE_SIDE, NEGATIVE_SIDE, BOTH_SIDE }; enum world_fragment_type { /// Return no world geometry hits at all WFT_NONE, /// Return pointers to convex plane-bounded regions WFT_PLANE_BOUNDED_REGION, /// Return a single intersection point (typically RaySceneQuery only) WFT_SINGLE_INTERSECTION, /// Custom geometry as defined by the SceneManager WFT_CUSTOM_GEOMETRY, /// General RenderOperation structure WFT_RENDER_OPERATION }; enum gui_metrics_mode { GMM_RELATIVE, GMM_PIXELS, GMM_RELATIVE_ASPECT_ADJUSTED }; enum gui_horizontal_alignment { GHA_LEFT, GHA_CENTER, GHA_RIGHT }; enum gui_vertical_alignment { GVA_TOP, GVA_CENTER, GVA_BOTTOM }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); TimerHandle root_get_timer(); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, c_ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char* plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); void scenemanager_set_sky_box(SceneManagerHandle handle, int enable, const char* material_name, float distance, int draw_first, const coiQuaternion* orientation, const char* group_name); void scenemanager_set_sky_dome(SceneManagerHandle handle, int enable, const char* material_name, float curvature, float tiling, float distance, int draw_first, const coiQuaternion* orientation, int xsegments, int ysegments, int ysegments_keep, const char* group_name); const(char*) scenemanager_get_name(SceneManagerHandle handle); //void SceneManager::destroyQuery(Ogre::SceneQuery* query); void scenemanager_destroy_scenequery(SceneManagerHandle handle, SceneQueryHandle query); // Ogre::SceneManager::createRayQuery(Ogre::Ray const&, unsigned long) RaySceneQueryHandle scenemanager_create_rayquery(SceneQueryHandle handle, RayHandle ray_handle, c_ulong mask); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Ogre::Node //Ogre::Node::getName() const const(char*) node_get_name(NodeHandle handle); //Ogre::Node::getParent() const //XXX: May be NULL if this is the root node. NodeHandle node_get_parent(NodeHandle handle); //Ogre::Node::getOrientation() const void node_get_orientation(NodeHandle handle, ref coiQuaternion result); //Ogre::Node::setOrientation(Ogre::Quaternion const&) void node_set_orientation(NodeHandle handle, const ref coiQuaternion orientation); //Ogre::Node::setScale(Ogre::Vector3 const&) void node_set_scale(NodeHandle handle, const ref coiVector3 in_scale); //Ogre::Node::setScale(Ogre::Vector3 const&) void node_set_scale_xyz(NodeHandle handle, const float x, const float y, const float z); //Ogre::Node::getScale() const void node_get_scale(NodeHandle handle, ref coiVector3 result); //Ogre::Node::setInheritOrientation(bool) void node_set_inherit_orientation(NodeHandle handle, int inherit); //Ogre::Node::getInheritOrientation() const int node_get_inherit_orientation(NodeHandle handle); //Ogre::Node::resetOrientation() void node_reset_orientation(NodeHandle handle); //Ogre::Node::setInheritScale(bool) void node_set_inherit_scale(NodeHandle handle, int inherit); //Ogre::Node::getInheritScale() const int node_get_inherit_scale(NodeHandle handle); //Ogre::Node::scale(Ogre::Vector3 const&) void node_scale(NodeHandle handle, const ref coiVector3 scale); //Ogre::Node::scale(Ogre::Vector3 const&) void node_scale_xyz(NodeHandle handle, const float x, const float y, const float z); //Ogre::Node::translate(Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate(NodeHandle handle, const ref coiVector3 d, transform_space relative_to); //Ogre::Node::translate(Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate_xyz(NodeHandle handle, const float x, const float y, const float z, transform_space relative_to); //Ogre::Node::translate(Ogre::Matrix3 const&, float, float, float, Ogre::Node::TransformSpace) //Ogre::Node::translate(Ogre::Matrix3 const&, Ogre::Vector3 const&, Ogre::Node::TransformSpace) void node_translate_m(NodeHandle handle, const ref coiMatrix3 axes, const ref coiVector3 move, transform_space relative_to); //Ogre::Node::roll(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_roll(NodeHandle handle, const coiReal angle, transform_space relative_to); //Ogre::Node::pitch(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_pitch(NodeHandle handle, const coiReal angle, transform_space relative_to); // Ogre::Node::yaw(Ogre::Radian const&, Ogre::Node::TransformSpace) void node_yaw(NodeHandle handle, const coiReal angle, transform_space relative_to); //Ogre::Node::rotate(Ogre::Vector3 const&, Ogre::Radian const&, Ogre::Node::TransformSpace) void node_rotate(NodeHandle handle, const ref coiVector3 axis, const coiReal angle, transform_space relative_to); //Ogre::Node::rotate(Ogre::Quaternion const&, Ogre::Node::TransformSpace) void node_rotate_q(NodeHandle handle, const ref coiQuaternion q, transform_space relative_to); //Ogre::Node::getLocalAxes() const void node_get_local_axes(NodeHandle handle, ref coiMatrix3 result); //Ogre::Node::createChild(Ogre::Vector3 const&, Ogre::Quaternion const&) NodeHandle node_create_child(NodeHandle handle, const ref coiVector3 translate, const ref coiQuaternion rotate); //Ogre::Node::createChild(std::string const&, Ogre::Vector3 const&, Ogre::Quaternion const&) NodeHandle node_create_named_child(NodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); //Ogre::Node::addChild(Ogre::Node*) void node_add_child(NodeHandle handle, NodeHandle child); //Ogre::Node::numChildren() const ushort node_num_children(NodeHandle handle); //Ogre::Node::getChild(unsigned short) const NodeHandle node_get_child_by_index(NodeHandle handle, ushort index); //Ogre::Node::getChild(std::string const&) const NodeHandle node_get_child_by_name(NodeHandle handle, const char* name); // Ogre::SceneNode SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); ushort scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_get_position(SceneNodeHandle handle, ref coiVector3 pos); void scenenode_set_derived_position(SceneNodeHandle handle, const ref coiVector3 pos); void scenenode_get_derived_position(SceneNodeHandle handle, ref coiVector3 pos); //void setFixedYawAxis( bool useFixed, const Vector3& fixedAxis = Vector3::UNIT_Y ); void scenenode_set_fixed_yaw_axis(SceneNodeHandle handle, int use_fixed, const ref coiVector3 fixed_axis); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle, transform_space relative_to); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref coiColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); //Ogre::Viewport::setDimensions(float, float, float, float) void viewport_set_dimensions(ViewportHandle handle, coiReal left, coiReal top, coiReal width, coiReal height); //Ogre::Viewport::getActualDimensions(int&, int&, int&, int&) const void viewport_get_actual_dimensions(ViewportHandle handle, ref int left, ref int top, ref int width, ref int height); //Ogre::Viewport::getBackgroundColour() const void viewport_get_background_colour(ViewportHandle handle, ref coiColourValue cv); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, ref coiVector3 v3); void camera_get_up(CameraHandle handle, ref coiVector3 up); void camera_get_right(CameraHandle handle, ref coiVector3 right); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); void camera_roll(CameraHandle handle, coiReal angle); void camera_yaw(CameraHandle handle, coiReal angle); void camera_pitch(CameraHandle handle, coiReal angle); void camera_rotate(CameraHandle handle, const ref coiVector3 axis, coiReal angle); void camera_rotate_q(CameraHandle handle, const ref coiQuaternion q); //Ogre::Camera::setFixedYawAxis(bool, Ogre::Vector3 const&) void camera_set_fixed_yaw_axis(CameraHandle handle, int on, const ref coiVector3 fixed_axis); //Ogre::Camera::getOrientation() const void camera_get_orientation(CameraHandle handle, ref coiQuaternion orientation); //Ogre::Camera::setOrientation(Ogre::Quaternion const&) void camera_set_orientation(CameraHandle handle, const ref coiQuaternion orientation); //Ogre::Camera::getDerivedOrientation() const void camera_get_derived_orientation(CameraHandle handle, ref coiQuaternion orientation); //Ogre::Camera::getDerivedPosition() const void camera_get_derived_position(CameraHandle handle, ref coiVector3 position); //Ogre::Camera::getDerivedDirection() const void camera_get_derived_direction(CameraHandle handle, ref coiVector3 direction); //Ogre::Camera::getDerivedUp() const void camera_get_derived_up(CameraHandle handle, ref coiVector3 up); //Ogre::Camera::getDerivedRight() const void camera_get_derived_right(CameraHandle handle, ref coiVector3 right); //Ogre::Camera::setAutoTracking(bool, Ogre::SceneNode*, Ogre::Vector3 const&) void camera_set_autotracking(CameraHandle handle, int on, SceneNodeHandle sn_handle, const ref coiVector3 offset); //Ogre::Camera::setLodBias(float) void camera_set_lod_bias(CameraHandle handle, coiReal factor); //Ogre::Camera::getLodBias() const coiReal camera_get_lod_bias(CameraHandle handle); //Ogre::Camera::getCameraToViewportRay(float, float, Ogre::Ray*) const void camera_get_camera_to_viewport_ray(CameraHandle handle, coiReal screenx, coiReal screeny, RayHandle ray); //Ogre::Camera::setWindow(float, float, float, float) void camera_set_window(CameraHandle handle, coiReal left, coiReal top, coiReal right, coiReal bottom); SceneManagerHandle camera_get_scenemanager(CameraHandle handle); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); //Ogre::Entity::getBoundingBox() const AxisAlignedBoxHandle entity_get_bounding_box(EntityHandle handle); //Ogre::Entity::getBoundingRadius() const coiReal entity_get_bounding_radius(EntityHandle handle); // Light LightHandle create_light(const char* light_name); void destroy_light(LightHandle handle); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); //Ogre::Light::getPosition() const void light_get_position(LightHandle handle, ref coiVector3 pos); //Ogre::Light::getPosition() const void light_get_position_xyz(LightHandle handle, ref float x, ref float y, ref float z); //Ogre::Light::getPosition() const void light_get_position_xyz(LightHandle handle, float* x, float* y, float* z); //Ogre::Light::setDirection(float, float, float) void light_set_direction_xyz(LightHandle handle, const float x, const float y, const float z); //Ogre::Light::setDirection(Ogre::Vector3 const&) void light_set_direction(LightHandle handle, const ref coiVector3 direction); //Ogre::Light::getDirection() const void light_get_direction(LightHandle handle, ref coiVector3 direction); //Ogre::Light::setSpotlightRange(Ogre::Radian const&, Ogre::Radian const&, float) void light_set_spotlight_range(LightHandle handle, const coiReal inner_angle, const coiReal outer_angle, coiReal fall_off); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref coiColourValue colour); void light_set_specular_colour(LightHandle handle, const ref coiColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); WindowListenerHandle add_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerEvent window_event, void* userdata); void remove_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerHandle listener_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(logging_level lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); //Log::logMessage void log_log_message(LogHandle handle, const char* message, log_message_level lml, int maskDebug); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); void render_window_get_custom_attribute(RenderWindowHandle handle, const char* attribute, void* pdata); uint render_window_get_width(RenderWindowHandle handle); uint render_window_get_height(RenderWindowHandle handle); void renderwindow_get_statistics(RenderWindowHandle handle, ref FrameStats stats); void renderwindow_get_statistics_ex(RenderWindowHandle handle, ref float lastFPS, ref float avgFPS, ref float bestFPS, ref float worstFPS); // ColourValue void colourvalue_zero(ref coiColourValue c); void colourvalue_black(ref coiColourValue c); void colourvalue_white(ref coiColourValue c); void colourvalue_red(ref coiColourValue c); void colourvalue_green(ref coiColourValue c); void colourvalue_blue(ref coiColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); void plane_get_normal(PlaneHandle handle, ref coiVector3 normal); void plane_set_normal(PlaneHandle handle, const ref coiVector3 normal); coiReal plane_get_d(PlaneHandle handle); void plane_set_d(PlaneHandle handle, coiReal d); // PlaneList (typedef vector<Plane>::type PlaneList) PlaneListHandle create_planelist(); void destroy_planelist(PlaneListHandle handle); // PlaneBoundedVolume PlaneBoundedVolumeHandle create_planeboundedvolume(plane_side the_outside); void destroy_planeboundedvolume(PlaneBoundedVolumeHandle handle); // bool intersects(const AxisAlignedBox&) const int planeboundedvolume_intersects_axisalignedbox(PlaneBoundedVolumeHandle handle, AxisAlignedBoxHandle query); // bool intersects(const Sphere&) const int planeboundedvolume_intersects_sphere(PlaneBoundedVolumeHandle handle, SphereHandle query); // std::pair<bool, Real> intersects(const Ray&) const void planeboundedvolume_intersects_ray(PlaneBoundedVolumeHandle handle, RayHandle query, ref ray_pair result); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); // Ogre::Timer int timer_set_option(TimerHandle handle, const char* key, void* value); c_ulong timer_get_milliseconds(TimerHandle handle); c_ulong timer_get_microseconds(TimerHandle handle); c_ulong timer_get_milliseconds_cpu(TimerHandle handle); c_ulong timer_get_microseconds_cpu(TimerHandle handle); void timer_reset(TimerHandle handle); // Ogre::AxisAlignedBox AxisAlignedBoxHandle create_axis_aligned_box(); AxisAlignedBoxHandle create_axis_aligned_box_ex(Extent e); AxisAlignedBoxHandle create_axis_aligned_box_v3(const ref coiVector3 min, const ref coiVector3 max); void destroy_axis_aligned_box(AxisAlignedBoxHandle handle); void axisalignedbox_get_size(AxisAlignedBoxHandle handle, ref coiVector3 size); void axisalignedbox_get_minimum(AxisAlignedBoxHandle handle, ref coiVector3 minimum); void axisalignedbox_get_maximum(AxisAlignedBoxHandle handle, ref coiVector3 maximum); void axisalignedbox_set_minimum_x(AxisAlignedBoxHandle handle, coiReal x); void axisalignedbox_set_minimum_y(AxisAlignedBoxHandle handle, coiReal y); void axisalignedbox_set_minimum_z(AxisAlignedBoxHandle handle, coiReal z); void axisalignedbox_set_minimum(AxisAlignedBoxHandle handle, const ref coiVector3 min); void axisalignedbox_set_maximum(AxisAlignedBoxHandle handle, const ref coiVector3 max); void axisalignedbox_set_maximum_x(AxisAlignedBoxHandle handle, coiReal x); void axisalignedbox_set_maximum_y(AxisAlignedBoxHandle handle, coiReal y); void axisalignedbox_set_maximum_z(AxisAlignedBoxHandle handle, coiReal z); void axisalignedbox_set_extents(AxisAlignedBoxHandle handle, const ref coiVector3 min, const ref coiVector3 max); void axisalignedbox_get_corner(AxisAlignedBoxHandle handle, CornerEnum e, ref coiVector3 corner); //Ogre::Ray RayHandle create_ray(const ref coiVector3 origin, const ref coiVector3 direction); void destroy_ray(RayHandle handle); //Ray::setOrigin void ray_set_origin(RayHandle handle, const ref coiVector3 origin); //Ray::getOrigin void ray_get_origin(RayHandle handle, ref coiVector3 origin); //Ray::setDirection void ray_set_direction(RayHandle handle, const ref coiVector3 direction); //Ray::getDirection void ray_get_direction(RayHandle handle, ref coiVector3 direction); //Ray::getPoint void ray_get_point(RayHandle handle, coiReal units, ref coiVector3 point); //Ray::intersects(Plane) void ray_intersects_plane(RayHandle handle, PlaneHandle plane_handle, ref ray_pair result); //Ray::intersects(AxisAlignedBox) void ray_intersects_axisalignedbox(RayHandle handle, AxisAlignedBoxHandle query_handle, ref ray_pair result); //Ray::intersects(Sphere) void ray_intersects_sphere(RayHandle handle, SphereHandle query_handle, ref ray_pair result); // Ogre::Sphere SphereHandle create_sphere(const ref coiVector3 center, coiReal radius); void destroy_sphere(SphereHandle handle); //void setRadius(Real) void sphere_set_radius(SphereHandle handle, coiReal radius); //Real getRadius(void) const coiReal sphere_get_radius(SphereHandle handle); //void setCenter(Vector3) void sphere_set_center(SphereHandle handle, const ref coiVector3 center); //Real getCenter(void) const void sphere_get_center(SphereHandle handle, ref coiVector3 center); // bool intersects(const Sphere&) const int sphere_intersects_sphere(SphereHandle handle, SphereHandle query); // bool intersects(const AxisAlignedBox&) const int sphere_intersects_axisalignedbox(SphereHandle handle, AxisAlignedBoxHandle query); // bool intersects(const Plane&) const int sphere_intersects_plane(SphereHandle handle, PlaneHandle query); // bool intersects(const Vector3&) const int sphere_intersects_vector3(SphereHandle handle, const ref coiVector3 query); // void merge(const Sphere&) void sphere_merge(SphereHandle handle, SphereHandle other_sphere); // Ogre::SceneQuery // SceneQuery::setQueryMask(uint32 mask) void scenequery_set_query_mask(SceneQueryHandle handle, uint32 mask); //uint32 SceneQuery::getQueryMask(void) const uint32 scenequery_get_query_mask(SceneQueryHandle handle); //void SceneQuery::setWorldFragmentType(enum WorldFragmentType wft); void scenequery_set_world_fragment_type(SceneQueryHandle handle, world_fragment_type wft); //WorldFragmentType SceneQuery::getWorldFragmentType(void) const; world_fragment_type scenequery_get_world_fragment_type(SceneQueryHandle handle); // SceneQueryListener SceneQueryListenerHandle create_scenequerylistener(SceneQueryFragmentResult fragment_callback, SceneQueryObjectResult object_callback, void* userdata); void destroy_scenequerylistener(SceneQueryListenerHandle handle); size_t scenequeryresult_movables_count(SceneQueryResultHandle handle); MovableObjectHandle scenequeryresult_movables_at(SceneQueryResultHandle handle, int index); size_t scenequeryresult_worldfragments_count(SceneQueryResultHandle handle, int index); void scenequeryresult_worldfragments_at(SceneQueryResultHandle handle, int index, ref world_fragment result); RaySceneQueryListenerHandle create_rayscenequerylistener(RaySceneQueryFragmentResult fragment_callback, RaySceneQueryObjectResult object_callback, void* userdata); void destroy_rayscenequerylistener(RaySceneQueryListenerHandle handle); //setRay void rayscenequery_set_ray(RaySceneQueryHandle handle, RayHandle ray_handle); //getRay RayHandle rayscenequery_get_ray(RaySceneQueryHandle handle); //void setSortByDistance(bool sort, ushort maxresults = 0); void rayscenequery_set_sort_by_distance(RaySceneQueryHandle handle, int on, ushort maxresults); //bool getSortByDistance(void) const; int rayscenequery_get_sort_by_distance(RaySceneQueryHandle handle); //ushort getMaxResults(void) const; ushort rayscenequery_get_max_results(RaySceneQueryHandle handle); // typedef vector<RaySceneQueryResultEntry>::type RaySceneQueryResult; size_t rayscenequeryresult_count(RaySceneQueryResultHandle handle); void rayscenequeryresult_at(RaySceneQueryResultHandle handle, int index, ref rayscenequery_result_entry result); // Ogre::Overlay //const String& getName(void) const; const(char[]) overlay_get_name(OverlayHandle handle); //void setZOrder(ushort zorder); void overlay_set_zorder(OverlayHandle handle, ushort zorder); //ushort getZOrder(void) const; ushort overlay_get_zorder(OverlayHandle handle); //bool isVisible(void) const; int overlay_is_visible(OverlayHandle handle); //bool isInitialised(void) const; int overlay_is_initialised(OverlayHandle handle); //void show(void); void overlay_show(OverlayHandle handle); //void hide(void); void overlay_hide(OverlayHandle handle); //void add2D(OverlayContainer* cont); void overlay_add_2d(OverlayHandle handle, OverlayContainerHandle cont); //void remove2D(OverlayContainer* cont); void overlay_remove_2d(OverlayHandle handle, OverlayContainerHandle cont); //void add3D(SceneNode* node); void overlay_add_3d(OverlayHandle handle, SceneNodeHandle node_handle); //void remove3D(SceneNode* node); void overlay_remove_3d(OverlayHandle handle, SceneNodeHandle node_handle); // void clear(); void overlay_clear(OverlayHandle handle); //void setScroll(Real x, Real y); void overlay_set_scroll(OverlayHandle handle, coiReal x, coiReal y); //Real getScrollX(void) const; coiReal overlay_get_scroll_x(OverlayHandle handle); //Real getScrollY(void) const; coiReal overlay_get_scroll_y(OverlayHandle handle); //void scroll(Real xoff, Real yoff); void overlay_scroll(OverlayHandle handle, coiReal x, coiReal y); //void setRotate(const Radian& angle); void overlay_set_rotate(OverlayHandle handle, coiReal angle); //const Radian &getRotate(void) const; coiReal overlay_get_rotate(OverlayHandle handle); //void rotate(const Radian& angle); void overlay_rotate(OverlayHandle handle, coiReal angle); //void setScale(Real x, Real y); void overlay_set_scale(OverlayHandle handle, coiReal x, coiReal y); //Real getScaleX(void) const; coiReal overlay_get_scale_x(OverlayHandle handle); //Real getScaleY(void) const; coiReal overlay_get_scale_y(OverlayHandle handle); //void _getWorldTransforms(Matrix4* xform) const; void overlay_get_world_transforms(OverlayHandle handle, ref coiMatrix4 xform); //const String& getOrigin(void) const; const(char[]) overlay_get_origin(OverlayHandle handle); //void _notifyOrigin(const String& origin); void overlay_notify_origin(OverlayHandle handle, const(char*) origin); //Ogre::OverlayManager //OverlayManager(); OverlayManagerHandle create_overlaymanager(); //~OverlayManager(); void destroy_overlaymanager(OverlayManagerHandle handle); //Real getLoadingOrder(void) const; coiReal overlaymanager_get_loading_order(OverlayManagerHandle handle); //Overlay* create(const String& name); OverlayHandle overlaymanager_create(OverlayManagerHandle handle, const char* name); //Overlay* getByName(const String& name); OverlayHandle overlaymanager_get_by_name(OverlayManagerHandle handle, const char* name); //void destroy(const String& name); void overlaymanager_destroy_by_name(OverlayManagerHandle handle, const char* name); //void destroy(Overlay* overlay); void overlaymanager_destroy(OverlayManagerHandle handle, OverlayHandle overlay_handle); //void destroyAll(void); void overlaymanager_destroy_all(OverlayManagerHandle handle); //bool hasViewportChanged(void) const; int overlaymanager_has_viewport_changed(OverlayManagerHandle handle); //int getViewportHeight(void) const; int overlaymanager_get_viewport_height(OverlayManagerHandle handle); //int getViewportWidth(void) const; int overlaymanager_get_viewport_width(OverlayManagerHandle handle); //Real getViewportAspectRatio(void) const; coiReal overlaymanager_get_viewport_aspect_ratio(OverlayManagerHandle handle); //OrientationMode getViewportOrientationMode(void) const; orientation_mode overlaymanager_get_viewport_orientation_mode(OverlayManagerHandle handle); //OverlayElement* createOverlayElement(const String& typeName, const String& instanceName, bool isTemplate = false); OverlayElementHandle overlaymanager_create_overlayelement(OverlayManagerHandle handle, const char* type_name, const char* instance_name, int is_template); //OverlayElement* getOverlayElement(const String& name, bool isTemplate = false); OverlayElementHandle overlaymanager_get_overlayelement(OverlayManagerHandle handle, const char* name, int is_template); //bool hasOverlayElement(const String& name, bool isTemplate = false); int overlaymanager_has_overlay_element(OverlayManagerHandle handle, const char* name, int is_template); //void destroyOverlayElement(const String& instanceName, bool isTemplate = false); void overlaymanager_destroy_overlay_element(OverlayManagerHandle handle, const char* name, int is_template); //void destroyOverlayElement(OverlayElement* pInstance, bool isTemplate = false); void overlaymanager_destroy_overlay_element_instance(OverlayManagerHandle handle, OverlayElementHandle instance, int is_template); //void destroyAllOverlayElements(bool isTemplate = false); void overlaymanager_destroy_all_overlay_elements(OverlayManagerHandle handle); //OverlayElement* createOverlayElementFromTemplate(const String& templateName, const String& typeName, const String& instanceName, bool isTemplate = false); OverlayElementHandle overlaymanager_create_overlayelement_from_template(OverlayManagerHandle handle, const char* template_name, const char* type_name, const char* instance_name, int is_template); //OverlayElement* cloneOverlayElementFromTemplate(const String& templateName, const String& instanceName); OverlayElementHandle overlaymanager_clone_overlayelement_from_template(OverlayManagerHandle handle, const char* template_name, const char* instance_name); //OverlayElement* createOverlayElementFromFactory(const String& typeName, const String& instanceName); OverlayElementHandle overlaymanager_create_overlayelement_from_factory(OverlayManagerHandle handle, const char* type_name, const char* instance_name); //bool isTemplate (String strName) const int overlaymanager_is_template(OverlayManagerHandle handle, const char* name); //static OverlayManager* getSingletonPtr(void); OverlayManagerHandle overlaymanager_get_singleton_ptr(); // Ogre::OverlayElement //~OverlayElement void destroy_overlayelement(OverlayElementHandle handle); //void initialise(void) void overlayelement_initialise(OverlayElementHandle handle); //const String& getName(void) const; const(char[]) overlayelement_get_name(OverlayElementHandle handle); //void show(void); void overlayelement_show(OverlayElementHandle handle); //void hide(void); void overlayelement_hide(OverlayElementHandle handle); //bool isVisible(void) const; int overlayelement_is_visible(OverlayElementHandle handle); //bool isEnabled() const; int overlayelement_is_enabled(OverlayElementHandle handle); //void setEnabled(bool b); void overlayelement_set_enabled(OverlayElementHandle handle, int b); //void setDimensions(Real width, Real height); void overlayelement_set_dimensions(OverlayElementHandle handle, coiReal width, coiReal height); //void setPosition(Real left, Real top); void overlayelement_set_position(OverlayElementHandle handle, coiReal left, coiReal top); //void setWidth(Real width); void overlayelement_set_width(OverlayElementHandle handle, coiReal width); //Real getWidth(void) const; coiReal overlayelement_get_width(OverlayElementHandle handle); //void setHeight(Real height); void overlayelement_set_height(OverlayElementHandle handle, coiReal height); //Real getHeight(void) const; coiReal overlayelement_get_height(OverlayElementHandle handle); //void setLeft(Real left); void overlayelement_set_left(OverlayElementHandle handle, coiReal left); //Real getLeft(void) const; coiReal overlayelement_get_left(OverlayElementHandle handle); //void setTop(Real Top); void overlayelement_set_top(OverlayElementHandle handle, coiReal top); //Real getTop(void) const; coiReal overlayelement_get_top(OverlayElementHandle handle); //Real _getLeft(void) const; coiReal overlayelement__get_left(OverlayElementHandle handle); //Real _getTop(void) const; coiReal overlayelement__get_top(OverlayElementHandle handle); //Real _getWidth(void) const; coiReal overlayelement__get_width(OverlayElementHandle handle); //Real _getHeight(void) const; coiReal overlayelement__get_height(OverlayElementHandle handle); //void _setLeft(Real left); void overlayelement__set_left(OverlayElementHandle handle, coiReal left); //void _setTop(Real top); void overlayelement__set_top(OverlayElementHandle handle, coiReal top); //void _setWidth(Real width); void overlayelement__set_width(OverlayElementHandle handle, coiReal width); //void _setHeight(Real height); void overlayelement__set_height(OverlayElementHandle handle, coiReal height); //void _setPosition(Real left, Real top); void overlayelement__set_position(OverlayElementHandle handle, coiReal left, coiReal top); //void _setDimensions(Real width, Real height); void overlayelement__set_dimensions(OverlayElementHandle handle, coiReal width, coiReal height); //const String& getMaterialName(void) const; const(char[]) overlayelement_get_material_name(OverlayElementHandle handle); //void setMaterialName(const String& matName); void overlayelement_set_material_name(OverlayElementHandle handle, const char* name); //void getWorldTransforms(Matrix4* xform) const; void overlayelement_get_world_transforms(OverlayElementHandle handle, ref coiMatrix4 xform); //void _positionsOutOfDate(void); void overlayelement__positions_out_of_date(OverlayElementHandle handle); //void _update(void); void overlayelement__update(OverlayElementHandle handle); //void _updateFromParent(void); void overlayelement__update_from_parent(OverlayElementHandle handle); //void _notifyParent(OverlayContainer* parent, Overlay* overlay); void overlayelement__notify_parent(OverlayElementHandle handle, OverlayContainerHandle parent_handle, OverlayHandle overlay_handle); //Real _getDerivedLeft(void); coiReal overlayelement__get_derived_left(OverlayElementHandle handle); //Real _getDerivedTop(void); coiReal overlayelement__get_derived_top(OverlayElementHandle handle); //Real _getRelativeWidth(void); coiReal overlayelement__get_relative_width(OverlayElementHandle handle); //Real _getRelativeHeight(void); coiReal overlayelement__get_relative_height(OverlayElementHandle handle); //ushort _notifyZOrder(ushort newZOrder); ushort overlayelement__notify_zorder(OverlayElementHandle handle, ushort new_zorder); //void _notifyWorldTransforms(const Matrix4& xform); void overlayelement__notify_world_transforms(OverlayElementHandle handle, const ref coiMatrix4 xform); //void _notifyViewport(); void overlayelement__notify_viewport(OverlayElementHandle handle); //const String& getTypeName(void) const; const(char[]) overlayelement_get_type_name(OverlayElementHandle handle); //void setCaption(const DisplayString& text); void overlayelement_set_caption(OverlayElementHandle handle, const char* text); //const DisplayString& getCaption(void) const; const(char[]) overlayelement_get_caption(OverlayElementHandle handle); //void setColour(const ColourValue& col); void overlayelement_set_colour(OverlayElementHandle handle, const ref coiColourValue col); //const ColourValue& getColour(void) const; void overlayelement_get_colour(OverlayElementHandle handle, ref coiColourValue col); //void setMetricsMode(GuiMetricsMode gmm); void overlayelement_set_metrics_mode(OverlayElementHandle handle, gui_metrics_mode gmm); //GuiMetricsMode getMetricsMode(void) const; gui_metrics_mode overlayelement_get_metrics_mode(OverlayElementHandle handle); //void setHorizontalAlignment(GuiHorizontalAlignment gha); void overlayelement_set_horizontal_alignment(OverlayElementHandle handle, gui_horizontal_alignment gha); //GuiHorizontalAlignment getHorizontalAlignment(void) const; gui_horizontal_alignment overlayelement_get_horizontal_alignment(OverlayElementHandle handle); //void setVerticalAlignment(GuiVerticalAlignment gva); void overlayelement_set_vertical_alignment(OverlayElementHandle handle, gui_vertical_alignment gva); //GuiVerticalAlignment getVerticalAlignment(void) const; gui_vertical_alignment overlayelement_get_vertical_alignment(OverlayElementHandle handle); //bool contains(Real x, Real y) const; int overlayelement_contains(OverlayElementHandle handle, coiReal x, coiReal y); //OverlayElement* findElementAt(Real x, Real y); OverlayElementHandle overlayelement_find_element_at(OverlayElementHandle handle, coiReal x, coiReal y); //bool isContainer() const; int overlayelement_is_container(OverlayElementHandle handle); //bool isKeyEnabled() const; int overlayelement_is_key_enabled(OverlayElementHandle handle); //bool isCloneable() const int overlayelement_is_cloneable(OverlayElementHandle handle); //void setCloneable(bool c); void overlayelement_set_cloneable(OverlayElementHandle handle, int c); //OverlayContainer* getParent(); OverlayContainerHandle overlayelement_get_parent(OverlayElementHandle handle); //void _setParent(OverlayContainer* parent); void overlayelement_set_parent(OverlayElementHandle handle, OverlayContainerHandle parent_handle); //ushort getZOrder() const; ushort overlayelement_get_zorder(OverlayElementHandle handle); //Real getSquaredViewDepth(const Camera* cam) const; coiReal overlayelement_get_squared_view_depth(OverlayElementHandle handle, CameraHandle camera_handle); //void copyFromTemplate(OverlayElement* templateOverlay); void overlayelement_copy_from_template(OverlayElementHandle handle, OverlayElementHandle template_handle); //OverlayElement* clone(const String& instanceName); OverlayElementHandle overlayelement_clone(OverlayElementHandle handle, const char* instance_name); //const OverlayElement* getSourceTemplate () const; const(OverlayElementHandle) overlayelement_get_source_template(OverlayElementHandle handle); // Ogre::OverlayContainer void destroy_overlaycontainer(OverlayContainerHandle handle); //void addChild(OverlayElement* elem); void overlaycontainer_add_child(OverlayContainerHandle handle, OverlayElementHandle child_handle); //void addChildImpl(OverlayElement* elem); void overlaycontainer_add_child_impl(OverlayContainerHandle handle, OverlayElementHandle child_handle); //void addChildImpl(OverlayContainer* cont); void overlaycontainer_add_child_container_impl(OverlayContainerHandle handle, OverlayContainerHandle child_handle); //void removeChild(const String& name); void overlaycontainer_remove_child(OverlayContainerHandle handle, const char* name); //OverlayElement* getChild(const String& name); OverlayElementHandle overlaycontainer_get_child(OverlayContainerHandle handle, const char* name); //void initialise(void); void overlaycontainer_initialise(OverlayContainerHandle handle); //void _addChild(OverlayElement* elem); void overlaycontainer__add_child(OverlayContainerHandle handle, OverlayElementHandle elem); //void _removeChild(OverlayElement* elem); void overlaycontainer__remove_child(OverlayContainerHandle handle, OverlayElementHandle elem); //void _removeChild(const String& name); void overlaycontainer__remove_child_by_name(OverlayContainerHandle handle, const char* name); //void _positionsOutOfDate(void); void overlaycontainer__positions_out_of_date(OverlayContainerHandle handle); //void _update(void); void overlaycontainer__update(OverlayContainerHandle handle); //ushort _notifyZOrder(ushort newZOrder); ushort overlaycontainer__notify_zorder(OverlayContainerHandle handle, ushort new_zorder); //void _notifyViewport(); void overlaycontainer__notify_viewport(OverlayContainerHandle handle); //void _notifyWorldTransforms(const Matrix4& xform); void overlaycontainer__notify_world_transforms(OverlayContainerHandle handle, const ref coiMatrix4 xform); //void _notifyParent(OverlayContainer* parent, Overlay* overlay); void overlaycontainer__notify_parent(OverlayContainerHandle handle, OverlayContainerHandle parent_handle, OverlayHandle overlay_handle); //bool isContainer() const; int overlaycontainer_is_container(OverlayContainerHandle handle); //bool isChildrenProcessEvents() const; int overlaycontainer_is_children_process_events(OverlayContainerHandle handle); //void setChildrenProcessEvents(bool val); void overlaycontainer_set_children_process_events(OverlayContainerHandle handle, int val); //OverlayElement* findElementAt(Real x, Real y); OverlayElementHandle overlaycontainer_find_element_at(OverlayContainerHandle handle, coiReal x, coiReal y); //void copyFromTemplate(OverlayElement* templateOverlay); void overlaycontainer_copy_from_template(OverlayContainerHandle handle, OverlayElementHandle template_overlay); //virtual OverlayElement* clone(const String& instanceName); OverlayElementHandle overlaycontainer_clone(OverlayContainerHandle handle, const char* instance_name); // Ogre::PanelOverlayElement //PanelOverlayElement(const String& name); PanelOverlayElementHandle create_paneloverlayelement(const char* name); //~PanelOverlayElement(); void destroy_paneloverlayelement(PanelOverlayElementHandle handle); //void initialise(void); void paneloverlayelement_initialise(PanelOverlayElementHandle handle); //void setTiling(Real x, Real y, ushort layer = 0); void paneloverlayelement_set_tiling(PanelOverlayElementHandle handle, coiReal x, coiReal y, ushort layer); //Real getTileX(ushort layer = 0) const; coiReal paneloverlayelement_get_tile_x(const PanelOverlayElementHandle handle, ushort layer); //Real getTileY(ushort layer = 0) const; coiReal paneloverlayelement_get_tile_y(const PanelOverlayElementHandle handle, ushort layer); //void setUV(Real u1, Real v1, Real u2, Real v2); void paneloverlayelement_set_uv(PanelOverlayElementHandle handle, coiReal u1, coiReal v1, coiReal u2, coiReal v2); //void getUV(Real& u1, Real& v1, Real& u2, Real& v2) const; void paneloverlayelement_get_uv(const PanelOverlayElementHandle handle, ref coiReal u1, ref coiReal v1, ref coiReal u2, ref coiReal v2); //void setTransparent(bool isTransparent); void paneloverlayelement_set_transparent(PanelOverlayElementHandle handle, int is_transparent); //bool isTransparent(void) const; int paneloverlayelement_is_transparent(const PanelOverlayElementHandle handle); //const String& getTypeName(void) const; const(char[]) paneloverlayelement_get_type_name(const PanelOverlayElementHandle handle); //TODO: void getRenderOperation(RenderOperation& op); //void setMaterialName(const String& matName); void paneloverlayelement_set_material_name(PanelOverlayElementHandle handle, const char* mat_name); //TODO: void _updateRenderQueue(RenderQueue* queue); // Ogre::TextAreaOverlayElement //TextAreaOverlayElement(const String& name); TextAreaOverlayElementHandle create_textareaoverlayelement(const char* name); //~TextAreaOverlayElement(); void destroy_textareaoverlayelement(TextAreaOverlayElementHandle handle);
/****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* MeshHandle; alias void* TimerHandle; alias void* WindowListenerHandle; alias void* AxisAlignedBoxHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { /// Point light sources give off light equally in all directions, so require only position not direction LT_POINT = 0, /// Directional lights simulate parallel light beams from a distant source, hence have direction but no position LT_DIRECTIONAL = 1, /// Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); TimerHandle root_get_timer(); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); void scenemanager_set_sky_box(SceneManagerHandle handle, int enable, const char* material_name, float distance, int draw_first, const coiQuaternion* orientation, const char* group_name); void scenemanager_set_sky_dome(SceneManagerHandle handle, int enable, const char* material_name, float curvature, float tiling, float distance, int draw_first, const coiQuaternion* orientation, int xsegments, int ysegments, int ysegments_keep, const char* group_name); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_get_position(SceneNodeHandle handle, ref coiVector3 pos); void scenenode_set_derived_position(SceneNodeHandle handle, const coiVector3* pos); void scenenode_get_derived_position(SceneNodeHandle handle, coiVector3* pos); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle, transform_space relative_to); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); void camera_roll(CameraHandle handle, coiReal angle); void camera_yaw(CameraHandle handle, coiReal angle); void camera_pitch(CameraHandle handle, coiReal angle); void camera_rotate(CameraHandle handle, const coiVector3* axis, coiReal angle); void camera_rotate_q(CameraHandle handle, const coiQuaternion* q); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); //Ogre::Entity::getBoundingBox() const AxisAlignedBoxHandle entity_get_bounding_box(EntityHandle handle); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); void destroy_light(LightHandle handle); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref ColourValue colour); void light_set_specular_colour(LightHandle handle, const ref ColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); WindowListenerHandle add_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerEvent window_event, void* userdata); void remove_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerHandle listener_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); void render_window_get_custom_attribute(RenderWindowHandle handle, const char* attribute, void* pdata); uint render_window_get_width(RenderWindowHandle handle); uint render_window_get_height(RenderWindowHandle handle); void renderwindow_get_statistics(RenderWindowHandle handle, ref FrameStats stats); void renderwindow_get_statistics_ex(RenderWindowHandle handle, ref float lastFPS, ref float avgFPS, ref float bestFPS, ref float worstFPS); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); void plane_get_normal(PlaneHandle handle, coiVector3* normal); void plane_set_normal(PlaneHandle handle, const coiVector3* normal); coiReal plane_get_d(PlaneHandle handle); void plane_set_d(PlaneHandle handle, coiReal d); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); // Ogre::Timer int timer_set_option(TimerHandle handle, const char* key, void* value); ulong timer_get_milliseconds(TimerHandle handle); ulong timer_get_microseconds(TimerHandle handle); ulong timer_get_milliseconds_cpu(TimerHandle handle); ulong timer_get_microseconds_cpu(TimerHandle handle); void timer_reset(TimerHandle handle); // Ogre::AxisAlignedBox AxisAlignedBoxHandle create_axis_aligned_box(); void destroy_axis_aligned_box(AxisAlignedBoxHandle handle); add missing enums, plus getSize /****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; // From OgrePlatform.h alias uint uint32; alias ushort uint16; alias ubyte uint8; alias int int32; alias short int16; alias byte int8; // OgreSceneManager.h alias ushort SceneTypeMask; // OgreColourValue.h alias uint32 RGBA; alias uint32 ARGB; alias uint32 ABGR; alias uint32 BGRA; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; alias void* FrameListenerHandle; alias void* PlaneHandle; alias void* MeshHandle; alias void* TimerHandle; alias void* WindowListenerHandle; alias void* AxisAlignedBoxHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; alias int function(const ref FrameEvent evt, int frame_type, void* userdata) FrameListenerCtx; struct coiQuaternion { float w; float x; float y; float z; } struct coiVector3 { float x; float y; float z; } struct ViewPoint { coiVector3 position; coiQuaternion orientation; }; struct FrameEvent { coiReal timeSinceLastEvent; coiReal timeSinceLastFrame; } struct ColourValue { float r; float g; float b; float a; } struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; struct FrameStats { float lastFPS; float avgFPS; float bestFPS; float worstFPS; ulong bestFrameTime; ulong worstFrameTime; size_t triangleCount; size_t batchCount; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; enum stat_flags { SF_NONE = 0, SF_FPS = 1, SF_AVG_FPS = 2, SF_BEST_FPS = 4, SF_WORST_FPS = 8, SF_TRIANGLE_COUNT = 16, SF_ALL = 0xFFFF }; enum frame_buffer { FB_FRONT, FB_BACK, FB_AUTO }; enum scene_type { ST_GENERIC = 1, ST_EXTERIOR_CLOSE = 2, ST_EXTERIOR_FAR = 4, ST_EXTERIOR_REAL_FAR = 8, ST_INTERIOR = 16 }; enum hardware_buffer_usage { HBU_STATIC = 1, HBU_DYNAMIC = 2, HBU_WRITE_ONLY = 4, HBU_DISCARDABLE = 8, HBU_STATIC_WRITE_ONLY = 5, HBU_DYNAMIC_WRITE_ONLY = 6, HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = 14 } enum light_types { /// Point light sources give off light equally in all directions, so require only position not direction LT_POINT = 0, /// Directional lights simulate parallel light beams from a distant source, hence have direction but no position LT_DIRECTIONAL = 1, /// Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff LT_SPOTLIGHT = 2 }; enum transform_space { TS_LOCAL, TS_PARENT, TS_WORLD }; enum Extent { EXTENT_NULL, EXTENT_FINITE, EXTENT_INFINITE }; enum CornerEnum { FAR_LEFT_BOTTOM = 0, FAR_LEFT_TOP = 1, FAR_RIGHT_TOP = 2, FAR_RIGHT_BOTTOM = 3, NEAR_RIGHT_BOTTOM = 7, NEAR_LEFT_BOTTOM = 6, NEAR_LEFT_TOP = 5, NEAR_RIGHT_TOP = 4 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); TimerHandle root_get_timer(); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); // Doesn't use OgreManager. Can still throw if type_name doesn't exist. SceneManagerHandle root_create_scene_manager(const char* type_name, const char* instance_name); // Doesn't use OgreManager. If a specific scene manager is not found, // the default implementation is always returned. SceneManagerHandle root_create_scene_manager_by_mask(SceneTypeMask type_mask, const char* instance_name); // Does use OgreManager. SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // Ogre::SceneManager calls EntityHandle scenemanager_create_entity(SceneManagerHandle handle, const char* name, const char* mesh_name, const char* group_name); SceneNodeHandle scenemanager_get_root_scene_node(SceneManagerHandle handle); LightHandle scenemanager_create_light(SceneManagerHandle handle, const char* name); void scenemanager_set_sky_box(SceneManagerHandle handle, int enable, const char* material_name, float distance, int draw_first, const coiQuaternion* orientation, const char* group_name); void scenemanager_set_sky_dome(SceneManagerHandle handle, int enable, const char* material_name, float curvature, float tiling, float distance, int draw_first, const coiQuaternion* orientation, int xsegments, int ysegments, int ysegments_keep, const char* group_name); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); const(char*) render_system_get_name(RenderSystemHandle handle); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_get_position(SceneNodeHandle handle, ref coiVector3 pos); void scenenode_set_derived_position(SceneNodeHandle handle, const coiVector3* pos); void scenenode_get_derived_position(SceneNodeHandle handle, coiVector3* pos); void scenenode_yaw_degree(SceneNodeHandle handle, coiReal angle, transform_space relative_to); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z, transform_space relative_to); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians, transform_space relative_to); SceneNodeHandle scenenode_create_child_scenenode(SceneNodeHandle handle, const char* name, const ref coiVector3 translate, const ref coiQuaternion rotate); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b, float a); void viewport_set_background_colour_cv(ViewportHandle viewport_handle, ref ColourValue cv); void viewport_set_auto_updated(ViewportHandle handle, int autoupdate); int viewport_is_auto_updated(ViewportHandle handle); float viewport_get_top(ViewportHandle handle); float viewport_get_left(ViewportHandle handle); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); int viewport_get_actual_top(ViewportHandle handle); int viewport_get_actual_left(ViewportHandle handle); int viewport_get_actual_width(ViewportHandle handle); int viewport_get_actual_height(ViewportHandle handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); const(char*) resourcegroupmanager_DEFAULT_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_INTERNAL_RESOURCE_GROUP_NAME(); const(char*) resourcegroupmanager_AUTODETECT_RESOURCE_GROUP_NAME(); size_t resourcegroupmanager_RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_move(CameraHandle handle, const float x, const float y, const float z); void camera_move_relative(CameraHandle handle, const float x, const float y, const float z); void camera_set_direction(CameraHandle handle, const float x, const float y, const float z); void camera_get_direction(CameraHandle handle, coiVector3* v3); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_aspect_ratio_ex(CameraHandle handle, float ratio); float camera_get_aspect_ratio(CameraHandle handle); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_get_position(CameraHandle handle, ref coiVector3 result); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); void camera_roll(CameraHandle handle, coiReal angle); void camera_yaw(CameraHandle handle, coiReal angle); void camera_pitch(CameraHandle handle, coiReal angle); void camera_rotate(CameraHandle handle, const coiVector3* axis, coiReal angle); void camera_rotate_q(CameraHandle handle, const coiQuaternion* q); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); void entity_set_cast_shadows(EntityHandle handle, int enabled); int entity_get_cast_shadows(EntityHandle handle); int entity_get_receives_shadows(EntityHandle handle); void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name); //Ogre::Entity::getBoundingBox() const AxisAlignedBoxHandle entity_get_bounding_box(EntityHandle handle); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); void destroy_light(LightHandle handle); void light_set_type(LightHandle handle, light_types type); void light_set_diffuse_colour(LightHandle handle, const ref ColourValue colour); void light_set_specular_colour(LightHandle handle, const ref ColourValue colour); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); FrameListenerHandle add_frame_listener_ctx(FrameListenerCtx callback, void* userdata); void remove_frame_listener_ctx(FrameListenerHandle handle); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); WindowListenerHandle add_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerEvent window_event, void* userdata); void remove_window_listener_ctx(RenderWindowHandle window_handle, WindowListenerHandle listener_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height); int render_window_is_closed(RenderWindowHandle handle); void render_window_set_active(RenderWindowHandle handle, int state); void render_window_swap_buffers(RenderWindowHandle handle, int wait_for_vsync); void render_window_get_custom_attribute(RenderWindowHandle handle, const char* attribute, void* pdata); uint render_window_get_width(RenderWindowHandle handle); uint render_window_get_height(RenderWindowHandle handle); void renderwindow_get_statistics(RenderWindowHandle handle, ref FrameStats stats); void renderwindow_get_statistics_ex(RenderWindowHandle handle, ref float lastFPS, ref float avgFPS, ref float bestFPS, ref float worstFPS); // ColourValue void colourvalue_zero(ref ColourValue c); void colourvalue_black(ref ColourValue c); void colourvalue_white(ref ColourValue c); void colourvalue_red(ref ColourValue c); void colourvalue_green(ref ColourValue c); void colourvalue_blue(ref ColourValue c); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); // Plane PlaneHandle plane_create_plane(); PlaneHandle plane_create_plane_normal(float x, float y, float z, float distance); void plane_destroy_plane(PlaneHandle handle); void plane_get_normal(PlaneHandle handle, coiVector3* normal); void plane_set_normal(PlaneHandle handle, const coiVector3* normal); coiReal plane_get_d(PlaneHandle handle); void plane_set_d(PlaneHandle handle, coiReal d); // MeshManager MeshHandle meshmanager_create_plane(const char* name, const char* group_name, PlaneHandle plane, float width, float height, int xsegments, int ysegments, int normals, ushort num_tex_coord_sets, float utile, float vtile, ref coiVector3 up_vector, hardware_buffer_usage vertex_buffer_usage, hardware_buffer_usage index_buffer_usage, int vertex_shadow_buffer, int index_shadow_buffer); // Ogre::Timer int timer_set_option(TimerHandle handle, const char* key, void* value); ulong timer_get_milliseconds(TimerHandle handle); ulong timer_get_microseconds(TimerHandle handle); ulong timer_get_milliseconds_cpu(TimerHandle handle); ulong timer_get_microseconds_cpu(TimerHandle handle); void timer_reset(TimerHandle handle); // Ogre::AxisAlignedBox AxisAlignedBoxHandle create_axis_aligned_box(); void destroy_axis_aligned_box(AxisAlignedBoxHandle handle); void axisalignedbox_get_size(AxisAlignedBoxHandle handle, ref coiVector3 size);
/****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* NameValuePairListHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void delegate(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message) LogListenerDelegate; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; } ; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; enum logging_level { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum log_message_level { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, log_message_level lml, int maskDebug, const char* log_name, int skip_message); //LogManager::destroyLog void logmanager_set_log_detail(logging_level lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener void add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::removeListener void remove_log_listener(LogListenerEvent log_event, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, .../*int zorder, float left, float top, float width, float height*/); int render_window_is_closed(RenderWindowHandle handle); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE(); Updated D2 interface files to match changes to API. Can now pass functions, delegates, classes, whatever via void* userdata in log listener calls. /****************************************************************************** * ogre_interface.di - main interface file for D clients ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ module llcoi.ogre_interface; extern(C): alias float coiReal; const int EVENT_FRAME_STARTED = 1; const int EVENT_FRAME_RENDERING_QUEUED = 2; const int EVENT_FRAME_ENDED = 4; alias void* CameraHandle; alias void* EntityHandle; alias void* SceneNodeHandle; alias void* LightHandle; alias void* RenderWindowHandle; alias void* RootHandle; alias void* RenderSystemHandle; alias void* RenderSystemListHandle; alias void* SceneManagerHandle; alias void* ViewportHandle; alias void* LogManagerHandle; alias void* LogHandle; alias void* LogListenerHandle; alias void* NameValuePairListHandle; // listener typedefs alias int function(float,float,int) FrameListenerEvent; alias void function(RenderWindowHandle) WindowListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message) LogListenerEvent; alias void function(const char* message, int lml, int maskDebug, const char* log_name, int skip_message, void* userdata) LogListenerCtx; struct coiQuaternion { float w; float x; float y; float z; }; struct coiVector3 { float x; float y; float z; } ; struct engine_options { const char* renderer_s; const char* plugin_folder_s; const char* window_title; const char* log_name; int width, height, auto_window; }; enum LoggingLevel { LL_LOW = 1, LL_NORMAL = 2, LL_BOREME = 3 }; enum LogMessageLevel { LML_TRIVIAL = 1, LML_NORMAL = 2, LML_CRITICAL = 3 }; // Root functions void release_engine(); void default_engine_options(engine_options* options); void init_engine(const engine_options options); RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName); RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title); RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen); RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, ulong hwnd); uint render_window_get_hwnd(RenderWindowHandle window_handle); void render_window_set_visible(RenderWindowHandle window_handle, int visible); void render_window_update(RenderWindowHandle window_handle, int swap_buffers); void current_window_update(int swap_buffers); void render_window_resize(uint width, uint height); void render_window_moved_or_resized(); int render_window_closed(); int root_is_initialised(); void save_config(); int restore_config(); int show_config_dialog(); void load_ogre_plugin(const char * plugin); SceneManagerHandle create_scene_manager(const char* type_name, const char* instance_name); SceneManagerHandle get_scene_manager(); SceneManagerHandle get_scene_manager_by_name(const char* scene_manager_instance_name); int render_one_frame(); int render_one_frame_ex(float time_since_last_frame); void render_loop(); void pump_messages(); void log_message(const char* message); RenderWindowHandle root_create_render_window(const char* name, uint width, uint height, int fullscreen, NameValuePairListHandle params); RenderSystemListHandle root_get_available_renderers(); // RenderSystem functions void add_render_system(RenderSystemHandle render_system); void set_render_system(RenderSystemHandle render_system); RenderSystemHandle get_render_system(); RenderSystemHandle get_render_system_by_name(const char* render_system_name); void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value); uint render_system_list_size(RenderSystemListHandle list_handle); RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, uint at); void destroy_render_system_list(RenderSystemListHandle handle); // SceneManager functions void set_default_num_mipmaps(int number); void set_ambient_light_rgba(const float r, const float g, const float b, const float a); void set_ambient_light_rgb(const float r, const float g, const float b); ViewportHandle add_viewport(CameraHandle camera_handle); void scene_manager_log_name(); // Scene nodes SceneNodeHandle create_child_scenenode(const char* node_name); void attach_entity_to_scenenode(EntityHandle entity_handle, SceneNodeHandle scenenode_handle); void scenenode_update(SceneNodeHandle scenenode_handle, int update_children, int parent_has_changed); void scenenode_update_bounds(SceneNodeHandle scenenode_handle); EntityHandle scenenode_get_attached_entity_int(SceneNodeHandle scenenode_handle, int entity_index); EntityHandle scenenode_get_attached_entity(SceneNodeHandle scenenode_handle, const char* entity_name); int scenenode_num_attached_objects(SceneNodeHandle scenenode_handle); void scenenode_detach_entity_int(SceneNodeHandle scenenode_handle, int entity_index); void scenenode_detach_entity(SceneNodeHandle scenenode_handle, EntityHandle entity_handle); void scenenode_detach_entity_string(SceneNodeHandle scenenode_handle, const char* entity_name); void scenenode_detach_all_objects(SceneNodeHandle scenenode_handle); int scenenode_is_in_scenegraph(SceneNodeHandle scenenode_handle); void scenenode_notify_rootnode(SceneNodeHandle scenenode_handle); void scenenode_show_boundingbox(SceneNodeHandle scenenode_handle, int show_boundingbox); void scenenode_hide_boundingbox(SceneNodeHandle scenenode_handle, int hide_boundingbox); int scenenode_get_show_boundingbox(SceneNodeHandle scenenode_handle); SceneNodeHandle scenenode_get_parent_scenenode(SceneNodeHandle scenenode_handle); void scenenode_set_visible(SceneNodeHandle scenenode_handle, int visible); void scenenode_set_visible_ex(SceneNodeHandle scenenode_handle, int visible, int cascade); void scenenode_flip_visibility(SceneNodeHandle scenenode_handle); void scenenode_flip_visibility_ex(SceneNodeHandle scenenode_handle, int cascade); void scenenode_set_debug_display_enabled(SceneNodeHandle scenenode_handle, int enabled); void scenenode_set_debug_display_enabled_ex(SceneNodeHandle scenenode_handle, int enabled, int cascade); SceneManagerHandle scenenode_get_creator(SceneNodeHandle scenenode_handle); void scenenode_set_direction(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_set_orientation(SceneNodeHandle scenenode_handle, float w, float x, float y, float z); void scenenode_set_position(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_yaw(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_set_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_scale(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_translate(SceneNodeHandle scenenode_handle, float x, float y, float z); void scenenode_roll(SceneNodeHandle scenenode_handle, coiReal radians); void scenenode_pitch(SceneNodeHandle scenenode_handle, coiReal radians); // Viewports void viewport_set_background_colour(ViewportHandle viewport_handle, float r, float g, float b); float viewport_get_width(ViewportHandle viewport_handle); float viewport_get_height(ViewportHandle viewport_handle); // Resource management void setup_resources(const char* resources_cfg); void add_resource_location(const char* location, const char* type, const char* group); void initialise_all_resourcegroups(); // Camera CameraHandle create_camera(const char* camera_name); CameraHandle get_camera(const char* camera_name); void camera_set_near_clip_distance(CameraHandle camera_handle, float d); void camera_set_far_clip_distance(CameraHandle camera_handle, float d); void camera_set_aspect_ratio(CameraHandle camera_handle, float w, float h); void camera_set_auto_aspect_ratio(CameraHandle camera_handle, int on); void camera_set_fovy(CameraHandle camera_handle, float angle); void camera_set_frustum_offset(CameraHandle camera_handle, const int offset_x, const int offset_y); void camera_set_focal_length(CameraHandle camera_handle, float fl); void camera_set_position(CameraHandle camera_handle, const float x, const float y, const float z); void camera_lookat(CameraHandle camera_handle, const float x, const float y, const float z); // Entity EntityHandle create_entity(const char* entity_name, const char* mesh_file); // Light LightHandle create_light(const char* light_name); void light_set_position(LightHandle light_handle, const float x, const float y, const float z); // FrameListener void add_frame_listener(FrameListenerEvent frame_event,const int frame_event_type); void remove_frame_listener(FrameListenerEvent frame_event); // WindowListener void add_window_listener(RenderWindowHandle window_handle, WindowListenerEvent window_event); void remove_window_listener(RenderWindowHandle window_handle); // LogManager LogManagerHandle create_log_manager(); // LogManager::getSingletonPtr LogManagerHandle get_log_manager(); //LogManager::getLog LogHandle logmanager_get_log(const char* name); //LogManager::getDefaultLog LogHandle logmanager_get_default_log(); //LogManager::setDefaultLog LogHandle logmanager_set_default_log(LogHandle log_handle); //LogManager::createLog LogHandle logmanager_create_log(const char* name, int default_log, int debugger_output, int suppress_file_output); // n.b., Allows for finer grained control over the log messages at the cost of // having to supply all these variables. If you don't need this control, // use log_message above. //LogManager::logMessage void logmanager_log_message(const char* message, LogMessageLevel lml, int maskDebug, const char* log_name, int skip_message); //LogManager::setLogDetail void logmanager_set_log_detail(LoggingLevel lvl); //LogManager::destroyLog void logmanager_destroy_log(const char* name); //LogManager::destroyLog overload void logmanager_destroy_log_by_handle(LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener(LogListenerEvent log_event, LogHandle log_handle); //Log::addListener LogListenerHandle add_log_listener_ctx(LogListenerCtx log_event, LogHandle log_handle, void* userdata); //Log::removeListener void remove_log_listener(LogListenerHandle llh, LogHandle log_handle); //Log::removeListener void remove_log_listener_ctx(LogListenerHandle llh, LogHandle log_handle); // NameValuePairList NameValuePairListHandle create_name_value_pair_list(); void add_pair(NameValuePairListHandle params, const char* name, const char* value); void destroy_name_value_pair_list(NameValuePairListHandle params); // RenderWindow ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, .../*int zorder, float left, float top, float width, float height*/); int render_window_is_closed(RenderWindowHandle handle); // Vector3 //Vector3::operator != int vector3_notequals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator == int vector3_equals_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator + coiVector3 vector3_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator += void vector3_update_add_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator -= void vector3_update_subtract_vector3(coiVector3 lhs, coiVector3 rhs); //Vector3::operator - coiVector3 vector3_negate(coiVector3 v3); // Vector3::operator/ coiVector3 vector3_divide_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::operator* coiVector3 vector3_multiply_vector3(coiVector3 lhs, coiVector3 rhs); // Vector3::isNaN int vector3_is_nan(coiVector3 v3); //Vector3::primaryAxis coiVector3 vector3_primary_axis(coiVector3); // Vector3::ZERO coiVector3 vector3_ZERO(); coiVector3 vector3_UNIT_X(); coiVector3 vector3_UNIT_Y(); coiVector3 vector3_UNIT_Z(); coiVector3 vector3_NEGATIVE_UNIT_X(); coiVector3 vector3_NEGATIVE_UNIT_Y(); coiVector3 vector3_NEGATIVE_UNIT_Z(); coiVector3 vector3_UNIT_SCALE();